github.com/gogf/gf/v2@v2.7.4/net/goai/goai_parameter_ref.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package goai 8 9 import ( 10 "fmt" 11 "net/http" 12 13 "github.com/gogf/gf/v2/container/gset" 14 "github.com/gogf/gf/v2/errors/gcode" 15 "github.com/gogf/gf/v2/errors/gerror" 16 "github.com/gogf/gf/v2/internal/json" 17 "github.com/gogf/gf/v2/os/gstructs" 18 "github.com/gogf/gf/v2/text/gstr" 19 ) 20 21 // Parameters is specified by OpenAPI/Swagger 3.0 standard. 22 type Parameters []ParameterRef 23 24 type ParameterRef struct { 25 Ref string 26 Value *Parameter 27 } 28 29 func (oai *OpenApiV3) newParameterRefWithStructMethod(field gstructs.Field, path, method string) (*ParameterRef, error) { 30 var ( 31 tagMap = field.TagMap() 32 fieldName = field.TagPriorityName() 33 ) 34 fieldName = gstr.Split(gstr.Trim(fieldName), ",")[0] 35 if fieldName == "" { 36 fieldName = field.Name() 37 } 38 var parameter = &Parameter{ 39 Name: fieldName, 40 XExtensions: make(XExtensions), 41 } 42 if len(tagMap) > 0 { 43 if err := oai.tagMapToParameter(tagMap, parameter); err != nil { 44 return nil, err 45 } 46 } 47 if parameter.In == "" { 48 // Automatically detect its "in" attribute. 49 if gstr.ContainsI(path, fmt.Sprintf(`{%s}`, parameter.Name)) { 50 parameter.In = ParameterInPath 51 } else { 52 // Default the parameter input to "query" if method is "GET/DELETE". 53 switch gstr.ToUpper(method) { 54 case http.MethodGet, http.MethodDelete: 55 parameter.In = ParameterInQuery 56 57 default: 58 return nil, nil 59 } 60 } 61 } 62 63 switch parameter.In { 64 case ParameterInPath: 65 // Required for path parameter. 66 parameter.Required = true 67 68 case ParameterInCookie, ParameterInHeader, ParameterInQuery: 69 70 default: 71 return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `invalid tag value "%s" for In`, parameter.In) 72 } 73 // Necessary schema or content. 74 schemaRef, err := oai.newSchemaRefWithGolangType(field.Type().Type, tagMap) 75 if err != nil { 76 return nil, err 77 } 78 parameter.Schema = schemaRef 79 80 // Ignore parameter. 81 if !isValidParameterName(parameter.Name) { 82 return nil, nil 83 } 84 85 // Required check. 86 if parameter.Schema.Value != nil && parameter.Schema.Value.ValidationRules != "" { 87 validationRuleArray := gstr.Split(parameter.Schema.Value.ValidationRules, "|") 88 if gset.NewStrSetFrom(validationRuleArray).Contains(validationRuleKeyForRequired) { 89 parameter.Required = true 90 } 91 } 92 93 return &ParameterRef{ 94 Ref: "", 95 Value: parameter, 96 }, nil 97 } 98 99 func (r ParameterRef) MarshalJSON() ([]byte, error) { 100 if r.Ref != "" { 101 return formatRefToBytes(r.Ref), nil 102 } 103 return json.Marshal(r.Value) 104 }