-
Notifications
You must be signed in to change notification settings - Fork 0
/
goai_path.go
400 lines (360 loc) · 12 KB
/
goai_path.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package goai
import (
"net/http"
"reflect"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/os/gstructs"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gmeta"
"github.com/gogf/gf/v2/util/gtag"
)
type Path struct {
Ref string `json:"$ref,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Connect *Operation `json:"connect,omitempty"`
Delete *Operation `json:"delete,omitempty"`
Get *Operation `json:"get,omitempty"`
Head *Operation `json:"head,omitempty"`
Options *Operation `json:"options,omitempty"`
Patch *Operation `json:"patch,omitempty"`
Post *Operation `json:"post,omitempty"`
Put *Operation `json:"put,omitempty"`
Trace *Operation `json:"trace,omitempty"`
Servers Servers `json:"servers,omitempty"`
Parameters Parameters `json:"parameters,omitempty"`
XExtensions XExtensions `json:"-"`
}
// Paths are specified by OpenAPI/Swagger standard version 3.0.
type Paths map[string]Path
const (
responseOkKey = `200`
)
type addPathInput struct {
Path string // Precise route path.
Prefix string // Route path prefix.
Method string // Route method.
Function interface{} // Uniformed function.
}
func (oai *OpenApiV3) addPath(in addPathInput) error {
if oai.Paths == nil {
oai.Paths = map[string]Path{}
}
var (
reflectType = reflect.TypeOf(in.Function)
)
if reflectType.NumIn() != 2 || reflectType.NumOut() != 2 {
return gerror.NewCodef(
gcode.CodeInvalidParameter,
`unsupported function "%s" for OpenAPI Path register, there should be input & output structures`,
reflectType.String(),
)
}
var (
inputObject reflect.Value
outputObject reflect.Value
)
// Create instance according input/output types.
if reflectType.In(1).Kind() == reflect.Ptr {
inputObject = reflect.New(reflectType.In(1).Elem()).Elem()
} else {
inputObject = reflect.New(reflectType.In(1)).Elem()
}
if reflectType.Out(0).Kind() == reflect.Ptr {
outputObject = reflect.New(reflectType.Out(0).Elem()).Elem()
} else {
outputObject = reflect.New(reflectType.Out(0)).Elem()
}
var (
mime string
path = Path{XExtensions: make(XExtensions)}
inputMetaMap = gmeta.Data(inputObject.Interface())
outputMetaMap = gmeta.Data(outputObject.Interface())
isInputStructEmpty = oai.doesStructHasNoFields(inputObject.Interface())
inputStructTypeName = oai.golangTypeToSchemaName(inputObject.Type())
outputStructTypeName = oai.golangTypeToSchemaName(outputObject.Type())
operation = Operation{
Responses: map[string]ResponseRef{},
XExtensions: make(XExtensions),
}
seRequirement = SecurityRequirement{}
)
// Path check.
if in.Path == "" {
in.Path = gmeta.Get(inputObject.Interface(), gtag.Path).String()
if in.Prefix != "" {
in.Path = gstr.TrimRight(in.Prefix, "/") + "/" + gstr.TrimLeft(in.Path, "/")
}
}
if in.Path == "" {
return gerror.NewCodef(
gcode.CodeMissingParameter,
`missing necessary path parameter "%s" for input struct "%s", missing tag in attribute Meta?`,
gtag.Path, inputStructTypeName,
)
}
if v, ok := oai.Paths[in.Path]; ok {
path = v
}
// Method check.
if in.Method == "" {
in.Method = gmeta.Get(inputObject.Interface(), gtag.Method).String()
}
if in.Method == "" {
return gerror.NewCodef(
gcode.CodeMissingParameter,
`missing necessary method parameter "%s" for input struct "%s", missing tag in attribute Meta?`,
gtag.Method, inputStructTypeName,
)
}
if err := oai.addSchema(inputObject.Interface(), outputObject.Interface()); err != nil {
return err
}
if len(inputMetaMap) > 0 {
if err := oai.tagMapToPath(inputMetaMap, &path); err != nil {
return err
}
if err := oai.tagMapToOperation(inputMetaMap, &operation); err != nil {
return err
}
// Allowed request mime.
if mime = inputMetaMap[gtag.Mime]; mime == "" {
mime = inputMetaMap[gtag.Consumes]
}
}
// path security
// note: the security schema type only support http and apiKey;not support oauth2 and openIdConnect.
// multi schema separate with comma, e.g. `security: apiKey1,apiKey2`
TagNameSecurity := gmeta.Get(inputObject.Interface(), gtag.Security).String()
securities := gstr.SplitAndTrim(TagNameSecurity, ",")
for _, sec := range securities {
seRequirement[sec] = []string{}
}
if len(securities) > 0 {
operation.Security = &SecurityRequirements{seRequirement}
}
// =================================================================================================================
// Request Parameter.
// =================================================================================================================
structFields, _ := gstructs.Fields(gstructs.FieldsInput{
Pointer: inputObject.Interface(),
RecursiveOption: gstructs.RecursiveOptionEmbeddedNoTag,
})
for _, structField := range structFields {
if operation.Parameters == nil {
operation.Parameters = []ParameterRef{}
}
parameterRef, err := oai.newParameterRefWithStructMethod(structField, in.Path, in.Method)
if err != nil {
return err
}
if parameterRef != nil {
operation.Parameters = append(operation.Parameters, *parameterRef)
}
}
// =================================================================================================================
// Request Body.
// =================================================================================================================
if operation.RequestBody == nil {
operation.RequestBody = &RequestBodyRef{}
}
if operation.RequestBody.Value == nil {
var (
requestBody = RequestBody{
Required: true,
Content: map[string]MediaType{},
}
)
// Supported mime types of request.
var (
contentTypes = oai.Config.ReadContentTypes
tagMimeValue = gmeta.Get(inputObject.Interface(), gtag.Mime).String()
)
if tagMimeValue != "" {
contentTypes = gstr.SplitAndTrim(tagMimeValue, ",")
}
for _, v := range contentTypes {
if isInputStructEmpty {
requestBody.Content[v] = MediaType{}
} else {
schemaRef, err := oai.getRequestSchemaRef(getRequestSchemaRefInput{
BusinessStructName: inputStructTypeName,
RequestObject: oai.Config.CommonRequest,
RequestDataField: oai.Config.CommonRequestDataField,
})
if err != nil {
return err
}
requestBody.Content[v] = MediaType{
Schema: schemaRef,
}
}
}
operation.RequestBody = &RequestBodyRef{
Value: &requestBody,
}
}
// =================================================================================================================
// Response.
// =================================================================================================================
if _, ok := operation.Responses[responseOkKey]; !ok {
var (
response = Response{
Content: map[string]MediaType{},
XExtensions: make(XExtensions),
}
)
if len(outputMetaMap) > 0 {
if err := oai.tagMapToResponse(outputMetaMap, &response); err != nil {
return err
}
}
// Supported mime types of response.
var (
contentTypes = oai.Config.ReadContentTypes
tagMimeValue = gmeta.Get(outputObject.Interface(), gtag.Mime).String()
refInput = getResponseSchemaRefInput{
BusinessStructName: outputStructTypeName,
CommonResponseObject: oai.Config.CommonResponse,
CommonResponseDataField: oai.Config.CommonResponseDataField,
}
)
if tagMimeValue != "" {
contentTypes = gstr.SplitAndTrim(tagMimeValue, ",")
}
for _, v := range contentTypes {
// If customized response mime type, it then ignores common response feature.
if tagMimeValue != "" {
refInput.CommonResponseObject = nil
refInput.CommonResponseDataField = ""
}
schemaRef, err := oai.getResponseSchemaRef(refInput)
if err != nil {
return err
}
response.Content[v] = MediaType{
Schema: schemaRef,
}
}
operation.Responses[responseOkKey] = ResponseRef{Value: &response}
}
// Remove operation body duplicated properties.
oai.removeOperationDuplicatedProperties(operation)
// Assign to certain operation attribute.
switch gstr.ToUpper(in.Method) {
case http.MethodGet:
// GET operations cannot have a requestBody.
operation.RequestBody = nil
path.Get = &operation
case http.MethodPut:
path.Put = &operation
case http.MethodPost:
path.Post = &operation
case http.MethodDelete:
// DELETE operations cannot have a requestBody.
operation.RequestBody = nil
path.Delete = &operation
case http.MethodConnect:
// Nothing to do for Connect.
case http.MethodHead:
path.Head = &operation
case http.MethodOptions:
path.Options = &operation
case http.MethodPatch:
path.Patch = &operation
case http.MethodTrace:
path.Trace = &operation
default:
return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid method "%s"`, in.Method)
}
oai.Paths[in.Path] = path
return nil
}
func (oai *OpenApiV3) removeOperationDuplicatedProperties(operation Operation) {
var (
duplicatedParameterNames []interface{}
dataField string
)
for _, parameter := range operation.Parameters {
duplicatedParameterNames = append(duplicatedParameterNames, parameter.Value.Name)
}
// Check operation request body have common request data field.
dataFields := gstr.Split(oai.Config.CommonRequestDataField, ".")
if len(dataFields) > 0 && dataFields[0] != "" {
dataField = dataFields[0]
}
for _, requestBodyContent := range operation.RequestBody.Value.Content {
// Check request body schema
if requestBodyContent.Schema == nil {
continue
}
// Check request body schema ref.
if schema := oai.Components.Schemas.Get(requestBodyContent.Schema.Ref); schema != nil {
schema.Value.Required = oai.removeItemsFromArray(schema.Value.Required, duplicatedParameterNames)
schema.Value.Properties.Removes(duplicatedParameterNames)
continue
}
// Check the Value public field for the request body.
if commonRequest := requestBodyContent.Schema.Value.Properties.Get(dataField); commonRequest != nil {
commonRequest.Value.Required = oai.removeItemsFromArray(commonRequest.Value.Required, duplicatedParameterNames)
commonRequest.Value.Properties.Removes(duplicatedParameterNames)
continue
}
// Check request body schema value.
if requestBodyContent.Schema.Value != nil {
requestBodyContent.Schema.Value.Required = oai.removeItemsFromArray(requestBodyContent.Schema.Value.Required, duplicatedParameterNames)
requestBodyContent.Schema.Value.Properties.Removes(duplicatedParameterNames)
continue
}
}
}
func (oai *OpenApiV3) removeItemsFromArray(array []string, items []interface{}) []string {
arr := garray.NewStrArrayFrom(array)
for _, item := range items {
if value, ok := item.(string); ok {
arr.RemoveValue(value)
}
}
return arr.Slice()
}
func (oai *OpenApiV3) doesStructHasNoFields(s interface{}) bool {
return reflect.TypeOf(s).NumField() == 0
}
func (oai *OpenApiV3) tagMapToPath(tagMap map[string]string, path *Path) error {
var mergedTagMap = oai.fillMapWithShortTags(tagMap)
if err := gconv.Struct(mergedTagMap, path); err != nil {
return gerror.Wrap(err, `mapping struct tags to Path failed`)
}
oai.tagMapToXExtensions(mergedTagMap, path.XExtensions)
return nil
}
func (p Path) MarshalJSON() ([]byte, error) {
var (
b []byte
m map[string]json.RawMessage
err error
)
type tempPath Path // To prevent JSON marshal recursion error.
if b, err = json.Marshal(tempPath(p)); err != nil {
return nil, err
}
if err = json.Unmarshal(b, &m); err != nil {
return nil, err
}
for k, v := range p.XExtensions {
if b, err = json.Marshal(v); err != nil {
return nil, err
}
m[k] = b
}
return json.Marshal(m)
}