-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.go
75 lines (65 loc) · 1.57 KB
/
response.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
package gomvc
import (
"encoding/json"
"strings"
"github.com/aymerick/raymond"
"github.com/getkin/kin-openapi/openapi3"
"github.com/iancoleman/strcase"
)
func CreateStructFromResponseObject(m *ResponseModel) (string, error) {
tmplString := `
package models
type {{Name}} struct {
{{#if Parent}}
{{Parent}}{{else}}{{#each Properties}}
{{#if this.description}}// {{this.description}}{{/if}}
{{camelize @key}} {{this.GoType}}
{{/each}}{{/if}}
}
`
tmpl, err := raymond.Parse(tmplString)
if err != nil {
return "", err
}
tmpl.RegisterHelper("camelize", func(word string) string {
return strcase.ToCamel(word)
})
result := tmpl.MustExec(m)
return result, nil
}
func LoadResponseObject(name string, r *openapi3.Response) ResponseModel {
// hack
b, _ := json.MarshalIndent(r, "", "\t")
var o ResponseObject
if err := json.Unmarshal(b, &o); err != nil {
panic(err)
}
m := ResponseModel{}
for contentType, content := range o.Content {
m.Name = name
m.ContentType = contentType
// this will be brittel to bad refs
refParts := strings.Split(content.Schema.Ref, "/")
refName := refParts[len(refParts)-1]
if m.Name != refName {
m.Parent = refName
}
}
return m
}
type ResponseObject struct {
Content map[string]SchemaType `json:"content,omitempty"`
Description string `json:"description,omitempty"`
}
type ResponseModel struct {
ContentType string
Parent string
Name string
Properties []Property
}
type SchemaType struct {
Schema Schema `json:"schema,omitempty"`
}
type Schema struct {
Ref string `json:"$ref,omitempty"`
}