github.com/qiniu/go-sdk/v7@v7.27.0/internal/api-generator/response.go (about) 1 package main 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/dave/jennifer/jen" 8 "gopkg.in/yaml.v3" 9 ) 10 11 type ( 12 ApiResponseDescription struct { 13 Body *ResponseBody `yaml:"body,omitempty"` 14 } 15 16 ResponseBody struct { 17 Json *JsonType 18 BinaryDataStream bool 19 } 20 ) 21 22 func (response *ApiResponseDescription) generate(group *jen.Group, opts CodeGeneratorOptions) (err error) { 23 if opts.Documentation != "" { 24 group.Add(jen.Comment(opts.Documentation)) 25 } 26 group.Add(jen.Type(). 27 Id(opts.camelCaseName()). 28 StructFunc(func(group *jen.Group) { 29 err = response.addFields(group) 30 })) 31 if err != nil { 32 return 33 } 34 35 if body := response.Body; body != nil { 36 if bodyJson := body.Json; bodyJson != nil { 37 err = bodyJson.generate(group, opts) 38 } 39 } 40 41 return 42 } 43 44 func (response *ApiResponseDescription) addFields(group *jen.Group) (err error) { 45 if body := response.Body; body != nil { 46 if bodyJson := body.Json; bodyJson != nil { 47 if jsonStruct := bodyJson.Struct; jsonStruct != nil { 48 if err = jsonStruct.addFields(group, false); err != nil { 49 return 50 } 51 } else if jsonArray := bodyJson.Array; jsonArray != nil { 52 if err = jsonArray.addFields(group); err != nil { 53 return 54 } 55 } else if bodyJson.Any { 56 group.Add(jen.Id("Body").Interface()) 57 } else if bodyJson.StringMap { 58 group.Add(jen.Id("Body").Map(jen.String()).String()) 59 } else { 60 return errors.New("response body should be struct or array") 61 } 62 } else if body.BinaryDataStream { 63 group.Add(jen.Id("Body").Qual("io", "ReadCloser")) 64 } 65 } 66 return 67 } 68 69 func (body *ResponseBody) UnmarshalYAML(value *yaml.Node) error { 70 switch value.ShortTag() { 71 case "!!str": 72 switch value.Value { 73 case "binary_data_stream": 74 body.BinaryDataStream = true 75 return nil 76 default: 77 return fmt.Errorf("unknown response body type: %s", value.Value) 78 } 79 case "!!map": 80 switch value.Content[0].Value { 81 case "json": 82 return value.Content[1].Decode(&body.Json) 83 default: 84 return fmt.Errorf("unknown response body type: %s", value.Content[0].Value) 85 } 86 default: 87 return fmt.Errorf("unknown response body type: %s", value.ShortTag()) 88 } 89 }