523 lines
15 KiB
Go
523 lines
15 KiB
Go
// Package api_doc ...
|
|
//
|
|
// Description : api_doc ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2024-07-22 15:55
|
|
package api_doc
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"git.zhangdeman.cn/gateway/api-doc/define"
|
|
"git.zhangdeman.cn/zhangdeman/consts"
|
|
"git.zhangdeman.cn/zhangdeman/wrapper"
|
|
"net/http"
|
|
"reflect"
|
|
"strings"
|
|
)
|
|
|
|
// NewOpenapiDoc ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 15:56 2024/7/22
|
|
func NewOpenapiDoc(info *define.Info, servers []*define.ServerItem) *Generate {
|
|
if nil == info {
|
|
info = &define.Info{
|
|
Description: "openapi接口文档",
|
|
Title: "openapi接口文档",
|
|
TermsOfService: "",
|
|
Contact: nil,
|
|
License: nil,
|
|
Version: "0.0.1",
|
|
}
|
|
}
|
|
if len(info.Version) == 0 {
|
|
info.Version = "0.0.1"
|
|
}
|
|
if nil == info.License {
|
|
info.License = &define.License{
|
|
Name: consts.LicenseApache20,
|
|
Url: consts.LicenseUrlTable[consts.LicenseApache20],
|
|
}
|
|
}
|
|
if nil == info.Contact {
|
|
info.Contact = &define.Contact{
|
|
Name: "研发人员(developer)",
|
|
Url: "",
|
|
Email: "",
|
|
}
|
|
}
|
|
if nil == servers {
|
|
servers = []*define.ServerItem{}
|
|
}
|
|
return &Generate{
|
|
docData: &define.OpenapiDoc{
|
|
Openapi: consts.SwaggerDocVersion3,
|
|
Info: info,
|
|
Servers: servers,
|
|
Components: &define.Components{Schemas: map[string]*define.Schema{}},
|
|
Tags: make([]*define.TagItem, 0),
|
|
Paths: make(map[string]*define.PathConfig),
|
|
},
|
|
}
|
|
}
|
|
|
|
// Generate 文档生成实例
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 15:57 2024/7/22
|
|
type Generate struct {
|
|
docData *define.OpenapiDoc
|
|
}
|
|
|
|
// SetLicense 设置文档协议
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 14:56 2024/8/14
|
|
func (g *Generate) SetLicense(name string, url string) {
|
|
g.docData.Info.License.Name = name
|
|
g.docData.Info.License.Url = url
|
|
}
|
|
|
|
// AddTag 新增tag
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 14:23 2024/8/14
|
|
func (g *Generate) AddTag(tagName string, tagDesc string) {
|
|
isHasTag := false
|
|
for _, item := range g.docData.Tags {
|
|
if item.Name == tagName {
|
|
if len(tagDesc) > 0 {
|
|
item.Description = tagDesc
|
|
}
|
|
isHasTag = true
|
|
break
|
|
}
|
|
}
|
|
if !isHasTag {
|
|
g.docData.Tags = append(g.docData.Tags, &define.TagItem{
|
|
Name: tagName,
|
|
Description: tagDesc,
|
|
})
|
|
}
|
|
}
|
|
|
|
// AddServer 添加server
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 14:45 2024/8/14
|
|
func (g *Generate) AddServer(serverDomain string, serverDesc string, serverVariable map[string]*define.ServerItemVariable) {
|
|
if nil == serverVariable {
|
|
serverVariable = make(map[string]*define.ServerItemVariable)
|
|
}
|
|
serverDomain = strings.TrimRight(serverDomain, "/")
|
|
isHasServer := false
|
|
for _, item := range g.docData.Servers {
|
|
if item.Url != serverDomain {
|
|
continue
|
|
}
|
|
isHasServer = true
|
|
if len(serverDesc) > 0 {
|
|
item.Description = serverDesc
|
|
}
|
|
for varName, varValue := range serverVariable {
|
|
item.Variables[varName] = varValue
|
|
}
|
|
break
|
|
}
|
|
if !isHasServer {
|
|
g.docData.Servers = append(g.docData.Servers, &define.ServerItem{
|
|
Url: serverDomain,
|
|
Description: serverDesc,
|
|
Variables: serverVariable,
|
|
})
|
|
}
|
|
}
|
|
|
|
// AddApi 新增Api
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 15:04 2024/8/14
|
|
//
|
|
// baseCfg : 接口基础配置, 示例数据
|
|
//
|
|
// &define.UriBaseConfig{
|
|
// Uri: "/foo/bar",
|
|
// Method: http.MethodPost,
|
|
// ContentType: ["application/json"],
|
|
// TagList: []string{"测试标签"},
|
|
// Summary: "这是一份示例基础配置",
|
|
// Description: "这是一份示例基础配置",
|
|
// }
|
|
//
|
|
// paramList : 参数列表
|
|
//
|
|
// resultList : 返回值列表
|
|
func (g *Generate) AddApi(baseCfg *define.UriBaseConfig, paramList []*define.ParamConfig, resultList []*define.ResultConfig) error {
|
|
return nil
|
|
}
|
|
|
|
// AddApiFromInAndOut 通过请求参数的
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 14:22 2025/2/9
|
|
func (g *Generate) AddApiFromInAndOut(baseCfg *define.UriBaseConfig, paramType reflect.Type, resultType reflect.Type) error {
|
|
if nil == baseCfg {
|
|
return errors.New("baseCfg is nil")
|
|
}
|
|
if baseCfg.Method == "" {
|
|
return errors.New("baseCfg.Method is empty")
|
|
}
|
|
if baseCfg.Uri == "" {
|
|
return errors.New("baseCfg.Uri is empty")
|
|
}
|
|
baseCfg.Method = strings.ToUpper(baseCfg.Method)
|
|
paramMethod := []string{
|
|
http.MethodGet, http.MethodHead, http.MethodConnect, http.MethodOptions, http.MethodTrace,
|
|
}
|
|
if wrapper.ArrayType(paramMethod).Has(baseCfg.Method) >= 0 {
|
|
// Get类请求, TODO : get类解析
|
|
return nil
|
|
}
|
|
// post类解析
|
|
if paramType.Kind() == reflect.Ptr {
|
|
paramType = paramType.Elem()
|
|
}
|
|
if resultType.Kind() == reflect.Ptr {
|
|
resultType = resultType.Elem()
|
|
}
|
|
paramSchemaName := g.AddComponentsSchema("", strings.ReplaceAll(paramType.PkgPath(), "/", "-"), paramType)
|
|
resultSchemaName := g.AddComponentsSchema("", strings.ReplaceAll(resultType.PkgPath(), "/", "-"), resultType)
|
|
if _, exist := g.docData.Paths[baseCfg.Uri]; !exist {
|
|
g.docData.Paths[baseCfg.Uri] = &define.PathConfig{}
|
|
}
|
|
defaultPkgPath := wrapper.String(strings.ReplaceAll(strings.TrimLeft(baseCfg.Uri, "/"), "/", "_")).SnakeCaseToCamel()
|
|
cfg := &define.PathItemOperationConfig{
|
|
Tags: baseCfg.TagList,
|
|
Summary: baseCfg.Summary,
|
|
Description: baseCfg.Description,
|
|
ExternalDocs: nil,
|
|
OperationID: defaultPkgPath + baseCfg.Method,
|
|
Parameters: nil,
|
|
RequestBody: &define.RequestBody{
|
|
Required: true,
|
|
Description: "",
|
|
Content: map[string]*define.Media{},
|
|
Ref: "",
|
|
},
|
|
Responses: map[string]*define.Response{
|
|
fmt.Sprintf("%v", http.StatusOK): &define.Response{
|
|
Content: map[string]*define.Media{},
|
|
},
|
|
},
|
|
Callbacks: nil,
|
|
Deprecated: false,
|
|
Security: nil,
|
|
Servers: nil,
|
|
}
|
|
for _, itemType := range baseCfg.ContentType {
|
|
cfg.RequestBody.Content[itemType] = &define.Media{
|
|
Schema: &define.Schema{
|
|
Ref: g.getSchemaRef(paramSchemaName),
|
|
},
|
|
Example: "",
|
|
Examples: nil,
|
|
Encoding: nil,
|
|
}
|
|
}
|
|
for _, itemOutputType := range baseCfg.OutputContentType {
|
|
cfg.Responses[fmt.Sprintf("%v", http.StatusOK)].Content[itemOutputType] = &define.Media{
|
|
Schema: &define.Schema{
|
|
Ref: g.getSchemaRef(resultSchemaName),
|
|
},
|
|
Example: "",
|
|
Examples: nil,
|
|
Encoding: nil,
|
|
}
|
|
}
|
|
switch baseCfg.Method {
|
|
case http.MethodGet:
|
|
g.docData.Paths[baseCfg.Uri].Get = cfg
|
|
case http.MethodHead:
|
|
g.docData.Paths[baseCfg.Uri].Head = cfg
|
|
case http.MethodPost:
|
|
g.docData.Paths[baseCfg.Uri].Post = cfg
|
|
case http.MethodPut:
|
|
g.docData.Paths[baseCfg.Uri].Put = cfg
|
|
case http.MethodPatch:
|
|
g.docData.Paths[baseCfg.Uri].Patch = cfg
|
|
case http.MethodDelete:
|
|
g.docData.Paths[baseCfg.Uri].Delete = cfg
|
|
case http.MethodConnect:
|
|
g.docData.Paths[baseCfg.Uri].Connect = cfg
|
|
case http.MethodOptions:
|
|
g.docData.Paths[baseCfg.Uri].Options = cfg
|
|
case http.MethodTrace:
|
|
g.docData.Paths[baseCfg.Uri].Trace = cfg
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AddComponentsSchema 添加schema
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 15:25 2025/2/8
|
|
func (g *Generate) AddComponentsSchema(rootSchemaName string, pkgPath string, inputType reflect.Type) string {
|
|
schemaName := pkgPath + "." + inputType.Name()
|
|
if _, exist := g.docData.Components.Schemas[schemaName]; !exist {
|
|
g.docData.Components.Schemas[schemaName] = &define.Schema{
|
|
Nullable: false,
|
|
Discriminator: nil,
|
|
ReadOnly: false,
|
|
WriteOnly: false,
|
|
Xml: nil,
|
|
ExternalDocs: nil,
|
|
Example: "",
|
|
Deprecated: false,
|
|
Properties: make(map[string]*define.Property),
|
|
Required: make([]string, 0),
|
|
Enum: make([]any, 0),
|
|
Type: "",
|
|
Ref: g.getSchemaRef(schemaName),
|
|
}
|
|
}
|
|
if inputType.Kind() == reflect.Map {
|
|
// map, 直接添加公共
|
|
g.docData.Components.Schemas[schemaName].Type = consts.SwaggerDataTypeObject
|
|
return schemaName
|
|
}
|
|
// 数组
|
|
if inputType.Kind() == reflect.Slice || inputType.Kind() == reflect.Array {
|
|
if len(rootSchemaName) == 0 {
|
|
g.docData.Components.Schemas[schemaName].Type = consts.SwaggerDataTypeArray
|
|
sliceItemType := g.parseSliceItem(schemaName, inputType)
|
|
g.docData.Components.Schemas[schemaName].Items = &define.PropertyXOf{Ref: g.getSchemaRef(g.getSchemaRef(sliceItemType))}
|
|
} else {
|
|
sliceItemType := g.parseSliceItem(schemaName, inputType)
|
|
g.docData.Components.Schemas[rootSchemaName].Properties[schemaName] = &define.Property{
|
|
Type: consts.SwaggerDataTypeArray,
|
|
Format: inputType.String(),
|
|
Items: &define.PropertyXOf{Ref: g.getSchemaRef(sliceItemType)},
|
|
}
|
|
}
|
|
|
|
return schemaName
|
|
}
|
|
// 结构体
|
|
if inputType.Kind() == reflect.Struct {
|
|
g.docData.Components.Schemas[schemaName].Type = consts.SwaggerDataTypeObject
|
|
for i := 0; i < inputType.NumField(); i++ {
|
|
if inputType.Field(i).Type.Kind() == reflect.Ptr ||
|
|
inputType.Field(i).Type.Kind() == reflect.Struct ||
|
|
inputType.Field(i).Type.Kind() == reflect.Map ||
|
|
inputType.Field(i).Type.Kind() == reflect.Array ||
|
|
inputType.Field(i).Type.Kind() == reflect.Slice {
|
|
if convertType := g.realBaseType2SwaggerType(inputType.Field(i).Type.String()); !strings.HasPrefix(convertType, "[]") && convertType != inputType.Field(i).Type.Kind().String() {
|
|
// 针对基础类型指针
|
|
g.docData.Components.Schemas[schemaName].Properties[g.getParamName(inputType.Field(i))] = &define.Property{
|
|
Type: g.realBaseType2SwaggerType(convertType),
|
|
Format: inputType.Field(i).Type.String(),
|
|
Default: g.getDefaultValue(inputType.Field(i)),
|
|
Description: g.getParamDesc(inputType.Field(i)),
|
|
}
|
|
continue
|
|
}
|
|
if inputType.Field(i).Type.Kind() == reflect.Struct ||
|
|
inputType.Field(i).Type.Kind() == reflect.Map {
|
|
g.docData.Components.Schemas[schemaName].Properties[g.getParamName(inputType.Field(i))] = &define.Property{
|
|
Type: consts.SwaggerDataTypeObject,
|
|
Format: inputType.Field(i).Type.String(),
|
|
Description: g.getParamDesc(inputType.Field(i)),
|
|
Properties: map[string]*define.Property{},
|
|
}
|
|
} else if inputType.Field(i).Type.Kind() == reflect.Array ||
|
|
inputType.Field(i).Type.Kind() == reflect.Slice {
|
|
g.docData.Components.Schemas[schemaName].Properties[g.getParamName(inputType.Field(i))] = &define.Property{
|
|
Type: consts.SwaggerDataTypeArray,
|
|
Format: inputType.Field(i).Type.String(),
|
|
Description: g.getParamDesc(inputType.Field(i)),
|
|
Items: &define.PropertyXOf{
|
|
Ref: g.parseSliceItem(schemaName, inputType.Field(i).Type),
|
|
},
|
|
Properties: map[string]*define.Property{},
|
|
}
|
|
} else if inputType.Field(i).Type.Kind() == reflect.Ptr {
|
|
|
|
} else {
|
|
g.AddComponentsSchema(schemaName, g.getParamName(inputType.Field(i)), inputType.Field(i).Type)
|
|
}
|
|
|
|
} else {
|
|
g.docData.Components.Schemas[schemaName].Properties[g.getParamName(inputType.Field(i))] = &define.Property{
|
|
Type: g.realBaseType2SwaggerType(inputType.Field(i).Type.String()),
|
|
Format: inputType.Field(i).Type.String(),
|
|
Default: g.getDefaultValue(inputType.Field(i)),
|
|
Description: g.getParamDesc(inputType.Field(i)),
|
|
}
|
|
}
|
|
}
|
|
return schemaName
|
|
}
|
|
// 指针
|
|
if inputType.Kind() == reflect.Ptr {
|
|
convertType := g.realBaseType2SwaggerType(inputType.String())
|
|
if convertType == inputType.String() {
|
|
// 非基础数据类型
|
|
return g.AddComponentsSchema(schemaName, inputType.Elem().String(), inputType.Elem())
|
|
} else {
|
|
g.docData.Components.Schemas[schemaName].Properties[schemaName] = &define.Property{
|
|
Type: convertType,
|
|
Format: inputType.String(),
|
|
Properties: map[string]*define.Property{},
|
|
}
|
|
}
|
|
}
|
|
return schemaName
|
|
}
|
|
|
|
// parseSliceItem 解析数组每一项
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 21:33 2025/2/8
|
|
func (g *Generate) parseSliceItem(rootSchemaName string, inputType reflect.Type) string {
|
|
if inputType.Kind() != reflect.Slice && inputType.Kind() != reflect.Array {
|
|
// 不是数组
|
|
return ""
|
|
}
|
|
sliceValue := reflect.MakeSlice(inputType, 1, 1)
|
|
sliceItemType := sliceValue.Index(0).Type()
|
|
g.AddComponentsSchema(rootSchemaName, sliceItemType.PkgPath(), sliceItemType)
|
|
/* if rootSchemaName != "" {
|
|
g.docData.Components.Schemas[rootSchemaName].Properties[sliceItemType.PkgPath()] = &define.Property{
|
|
Type: "",
|
|
Format: inputType.String(),
|
|
Enum: nil,
|
|
Default: "",
|
|
Description: "",
|
|
AllOf: nil,
|
|
OneOf: nil,
|
|
AnyOf: nil,
|
|
Items: nil,
|
|
AdditionalProperties: nil,
|
|
Properties: nil,
|
|
Ref: g.getSchemaRef(sliceItemType.PkgPath()),
|
|
}
|
|
}*/
|
|
if len(sliceItemType.PkgPath()) == 0 {
|
|
return sliceItemType.String()
|
|
}
|
|
return sliceItemType.PkgPath() + "." + sliceItemType.String()
|
|
}
|
|
|
|
// getSchemaRef 获取引用的类型
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 14:25 2025/2/9
|
|
func (g *Generate) getSchemaRef(schemaName string) string {
|
|
if "" == schemaName {
|
|
return ""
|
|
}
|
|
return "#/components/schemas/" + schemaName
|
|
}
|
|
|
|
// realType2SwaggerType golang 真实数据类型转换为golang数据类型
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 20:25 2025/2/11
|
|
func (g *Generate) realBaseType2SwaggerType(realType string) string {
|
|
switch realType {
|
|
case "bool", "*bool":
|
|
return consts.SwaggerDataTypeBoolean
|
|
case "string", "*string":
|
|
return consts.SwaggerDataTypeString
|
|
case "byte", "*byte":
|
|
return consts.SwaggerDataTypeByte
|
|
case "float32", "*float32", "float64", "*float64":
|
|
return consts.SwaggerDataTypeNumber
|
|
case "int", "*int", "uint", "*uint", "int64", "*int64", "uint64", "*uint64":
|
|
return consts.SwaggerDataTypeLong
|
|
case "int8", "*int8", "uint8", "*uint8", "int16", "*int16", "uint16", "*uint16", "int32", "*int32", "uint32", "*uint32":
|
|
return consts.SwaggerDataTypeInteger
|
|
default:
|
|
return realType
|
|
}
|
|
}
|
|
|
|
// realType2SwaggerType ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 21:20 2025/2/11
|
|
func (g *Generate) realType2SwaggerType(realType string) string {
|
|
if strings.HasPrefix(realType, "[]") {
|
|
return consts.SwaggerDataTypeArray
|
|
}
|
|
return g.realBaseType2SwaggerType(realType)
|
|
}
|
|
|
|
// getParamName 获取参数名称
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 21:58 2025/2/11
|
|
func (g *Generate) getParamName(structField reflect.StructField) string {
|
|
paramNameTagList := []string{
|
|
define.TagJson, define.TagForm,
|
|
define.TagXml, define.TagYaml,
|
|
define.TagYml,
|
|
}
|
|
for _, tag := range paramNameTagList {
|
|
tagVal := structField.Tag.Get(tag)
|
|
if tagVal != "" {
|
|
return tagVal
|
|
}
|
|
}
|
|
// 未设置相关字段, 则字段名即为参数名
|
|
return structField.Name
|
|
}
|
|
|
|
// getParamDesc ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 22:01 2025/2/11
|
|
func (g *Generate) getParamDesc(structField reflect.StructField) string {
|
|
descTagList := []string{define.TagDesc, define.TagDescription}
|
|
for _, tag := range descTagList {
|
|
tagVal := structField.Tag.Get(tag)
|
|
if tagVal != "" {
|
|
return tagVal
|
|
}
|
|
}
|
|
// 没有显示的设置参数描述, 则使用参数名作为参数描述
|
|
return g.getParamName(structField)
|
|
}
|
|
|
|
// getDefaultValue 获取默认值
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 22:05 2025/2/11
|
|
func (g *Generate) getDefaultValue(structField reflect.StructField) string {
|
|
defaultTagList := []string{define.TagD, define.TagDefault}
|
|
for _, tag := range defaultTagList {
|
|
if tagVal, exist := structField.Tag.Lookup(tag); exist {
|
|
return tagVal
|
|
}
|
|
}
|
|
return ""
|
|
}
|