-
Notifications
You must be signed in to change notification settings - Fork 0
/
swagger.go
325 lines (280 loc) · 7.78 KB
/
swagger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package swagger
import (
"encoding/json"
"fmt"
"github.com/darwinOrg/go-web/wrapper"
"github.com/go-openapi/spec"
"log"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"
)
const (
contentTypeJson = "application/json"
)
type ExportSwaggerRequest struct {
Title string
Description string
Version string
RequestApis []*wrapper.RequestApi
OutDir string
ServiceName string
}
func ExportSwaggerFile(req *ExportSwaggerRequest) {
if len(req.RequestApis) == 0 {
log.Print("没有需要导出的接口定义")
return
}
if req.ServiceName == "" {
panic("服务名不能为空")
}
swaggerProps := buildSwaggerProps(req)
filename := fmt.Sprintf("%s/%s.swagger.json", req.OutDir, req.ServiceName)
saveToFile(swaggerProps, filename)
}
func CreateSchemaForObject(obj any) *spec.Schema {
return createSchemaForType(reflect.TypeOf(obj), 0)
}
func buildSwaggerProps(req *ExportSwaggerRequest) spec.SwaggerProps {
if req.Title == "" {
req.Title = "接口文档"
}
if req.Description == "" {
req.Description = "接口描述"
}
if req.OutDir == "" {
req.OutDir = "openapi/v1"
}
if req.Version == "" {
req.Version = "v1.0.0"
}
return spec.SwaggerProps{
Swagger: "2.0",
Definitions: spec.Definitions{},
SecurityDefinitions: spec.SecurityDefinitions{},
Info: &spec.Info{
InfoProps: spec.InfoProps{
Title: req.Title,
Description: req.Description,
Version: req.Version,
},
},
Paths: buildApiPaths(req.RequestApis),
}
}
func buildApiPaths(requestApis []*wrapper.RequestApi) *spec.Paths {
paths := map[string]spec.PathItem{}
for _, api := range requestApis {
url := fmt.Sprintf("%s/%s", api.BasePath, api.RelativePath)
url = strings.ReplaceAll(url, "//", "/")
var parameters []spec.Parameter
if api.Method == http.MethodGet {
parameters = buildGetParameters(api)
} else {
parameters = buildPostParameters(api)
}
operation := &spec.Operation{
OperationProps: spec.OperationProps{
Summary: api.Remark,
Description: api.Remark,
Consumes: []string{contentTypeJson},
Produces: []string{contentTypeJson},
Parameters: parameters,
Responses: buildResponses(api),
},
}
itemProps := spec.PathItemProps{}
if api.Method == http.MethodGet {
itemProps.Get = operation
} else {
itemProps.Post = operation
}
paths[url] = spec.PathItem{
PathItemProps: itemProps,
}
}
return &spec.Paths{
Paths: paths,
}
}
func buildGetParameters(api *wrapper.RequestApi) []spec.Parameter {
tpe := reflect.TypeOf(api.RequestObject)
for tpe.Kind() == reflect.Pointer {
tpe = tpe.Elem()
}
cnt := tpe.NumField()
var parameters []spec.Parameter
for i := 0; i < cnt; i++ {
field := tpe.Field(i)
p := *spec.QueryParam(extractNameFromField(field))
switch field.Type.Kind() {
case reflect.String:
p.Type = "string"
case reflect.Bool:
p.Type = "boolean"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p.Type = "integer"
case reflect.Float32, reflect.Float64:
p.Type = "number"
case reflect.Slice, reflect.Array:
p.Type = "array"
case reflect.Map:
continue
default:
fmt.Printf("Unsupported field type: %s\n", field.Type.Kind())
}
p.Required = extractRequiredFlagFromField(field)
p.Description = extractDescriptionFromField(field)
parameters = append(parameters, p)
}
return parameters
}
func buildPostParameters(api *wrapper.RequestApi) []spec.Parameter {
schema := CreateSchemaForObject(api.RequestObject)
bodyParam := *spec.BodyParam("body", schema)
bodyParam.Required = true
return []spec.Parameter{bodyParam}
}
func createSchemaForType(tpe reflect.Type, depth int) *spec.Schema {
// 限制递归深度最大为8
if depth > 8 {
return nil
}
for tpe.Kind() == reflect.Pointer {
tpe = tpe.Elem()
}
schema := &spec.Schema{}
switch tpe.Kind() {
case reflect.String:
schema.Type = []string{"string"}
case reflect.Bool:
schema.Type = []string{"boolean"}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
schema.Type = []string{"integer"}
case reflect.Float32, reflect.Float64:
schema.Type = []string{"number"}
case reflect.Slice, reflect.Array:
elemType := tpe.Elem()
itemSchema := createSchemaForType(elemType, depth+1)
schema.Type = []string{"array"}
schema.Items = &spec.SchemaOrArray{Schema: itemSchema}
case reflect.Map:
keyType := tpe.Key()
if keyType.Kind() != reflect.String {
panic("Map keys must be strings in OpenAPI schemas.")
}
valueType := tpe.Elem()
valueSchema := createSchemaForType(valueType, depth+1)
schema.Type = []string{"object"}
schema.AdditionalProperties = &spec.SchemaOrBool{
Allows: true,
Schema: valueSchema,
}
case reflect.Struct:
schema.Properties = make(map[string]spec.Schema)
schema.Required = make([]string, 0)
cnt := tpe.NumField()
for i := 0; i < cnt; i++ {
field := tpe.Field(i)
if strings.Contains(tpe.String(), "result.Result") && field.Name == "Data" {
rt := reflect.New(tpe).Elem().Interface()
dataType := reflect.ValueOf(rt).Field(i).Type()
for dataType.Kind() == reflect.Pointer {
dataType = dataType.Elem()
}
field.Type = dataType
}
tpeStr := tpe.String()
tpeStr = strings.TrimPrefix(tpeStr, "*")
fieldTypeStr := field.Type.String()
fieldTypeStr = strings.TrimPrefix(fieldTypeStr, "[]")
fieldTypeStr = strings.TrimPrefix(fieldTypeStr, "*")
var property *spec.Schema
// 如果有结构体类型名称和字段名称相同,则不再递归,已免无限递归
if tpeStr == fieldTypeStr {
property = &spec.Schema{}
switch field.Type.Kind() {
case reflect.Slice, reflect.Array:
property.Type = []string{"array"}
default:
property.Type = []string{"object"}
}
} else {
property = createSchemaForType(field.Type, depth+1)
if property == nil {
continue
}
}
property.Title = extractTitleFromField(field)
property.Description = extractDescriptionFromField(field)
fieldName := extractNameFromField(field)
schema.Properties[fieldName] = *property
if extractRequiredFlagFromField(field) {
schema.Required = append(schema.Required, fieldName)
}
}
default:
fmt.Printf("Unsupported field type: %s\n", tpe.Kind())
}
return schema
}
func buildResponses(api *wrapper.RequestApi) *spec.Responses {
return &spec.Responses{
ResponsesProps: spec.ResponsesProps{
StatusCodeResponses: map[int]spec.Response{
http.StatusOK: {
ResponseProps: spec.ResponseProps{
Description: "成功",
Schema: CreateSchemaForObject(api.ResponseObject),
},
},
},
},
}
}
func extractNameFromField(field reflect.StructField) string {
jsonTag := field.Tag.Get("json")
if jsonTag != "" && jsonTag != "-" {
return strings.ReplaceAll(jsonTag, ",omitempty", "")
} else {
if len(field.Name) == 1 {
return strings.ToLower(field.Name)
}
return strings.ToLower(field.Name[0:1]) + field.Name[1:]
}
}
func extractTitleFromField(field reflect.StructField) string {
title := field.Tag.Get("title")
if title != "" {
return title
} else {
return extractDescriptionFromField(field)
}
}
func extractRequiredFlagFromField(field reflect.StructField) bool {
bindingTag := field.Tag.Get("binding")
return bindingTag != "" && strings.Contains(bindingTag, "required")
}
func extractDescriptionFromField(field reflect.StructField) string {
return field.Tag.Get("remark")
}
func saveToFile(swaggerProps spec.SwaggerProps, filename string) {
swaggerJSON, err := json.MarshalIndent(swaggerProps, "", " ")
if err != nil {
panic(err)
}
dirPath := filepath.Dir(filename)
if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
panic(err)
}
_, err = os.Create(filename)
if err != nil {
panic(err)
}
err = os.WriteFile(filename, swaggerJSON, os.ModePerm)
if err != nil {
panic(err)
}
}