-
-
Notifications
You must be signed in to change notification settings - Fork 435
/
openapi3gen.go
353 lines (313 loc) · 9.64 KB
/
openapi3gen.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
// Package openapi3gen generates OpenAPIv3 JSON schemas from Go types.
package openapi3gen
import (
"encoding/json"
"fmt"
"math"
"reflect"
"strings"
"time"
"github.com/getkin/kin-openapi/jsoninfo"
"github.com/getkin/kin-openapi/openapi3"
)
// CycleError indicates that a type graph has one or more possible cycles.
type CycleError struct{}
func (err *CycleError) Error() string { return "detected cycle" }
// Option allows tweaking SchemaRef generation
type Option func(*generatorOpt)
// SchemaCustomizerFn is a callback function, allowing
// the OpenAPI schema definition to be updated with additional
// properties during the generation process, based on the
// name of the field, the Go type, and the struct tags.
// name will be "_root" for the top level object, and tag will be ""
type SchemaCustomizerFn func(name string, t reflect.Type, tag reflect.StructTag, schema *openapi3.Schema) error
type generatorOpt struct {
useAllExportedFields bool
throwErrorOnCycle bool
schemaCustomizer SchemaCustomizerFn
}
// UseAllExportedFields changes the default behavior of only
// generating schemas for struct fields with a JSON tag.
func UseAllExportedFields() Option {
return func(x *generatorOpt) { x.useAllExportedFields = true }
}
// ThrowErrorOnCycle changes the default behavior of creating cycle
// refs to instead error if a cycle is detected.
func ThrowErrorOnCycle() Option {
return func(x *generatorOpt) { x.throwErrorOnCycle = true }
}
// SchemaCustomizer allows customization of the schema that is generated
// for a field, for example to support an additional tagging scheme
func SchemaCustomizer(sc SchemaCustomizerFn) Option {
return func(x *generatorOpt) { x.schemaCustomizer = sc }
}
// NewSchemaRefForValue uses reflection on the given value to produce a SchemaRef.
func NewSchemaRefForValue(value interface{}, opts ...Option) (*openapi3.SchemaRef, map[*openapi3.SchemaRef]int, error) {
g := NewGenerator(opts...)
ref, err := g.GenerateSchemaRef(reflect.TypeOf(value))
for ref := range g.SchemaRefs {
ref.Ref = ""
}
return ref, g.SchemaRefs, err
}
type Generator struct {
opts generatorOpt
Types map[reflect.Type]*openapi3.SchemaRef
// SchemaRefs contains all references and their counts.
// If count is 1, it's not ne
// An OpenAPI identifier has been assigned to each.
SchemaRefs map[*openapi3.SchemaRef]int
}
func NewGenerator(opts ...Option) *Generator {
gOpt := &generatorOpt{}
for _, f := range opts {
f(gOpt)
}
return &Generator{
Types: make(map[reflect.Type]*openapi3.SchemaRef),
SchemaRefs: make(map[*openapi3.SchemaRef]int),
opts: *gOpt,
}
}
func (g *Generator) GenerateSchemaRef(t reflect.Type) (*openapi3.SchemaRef, error) {
//check generatorOpt consistency here
return g.generateSchemaRefFor(nil, t, "_root", "")
}
func (g *Generator) generateSchemaRefFor(parents []*jsoninfo.TypeInfo, t reflect.Type, name string, tag reflect.StructTag) (*openapi3.SchemaRef, error) {
if ref := g.Types[t]; ref != nil && g.opts.schemaCustomizer == nil {
g.SchemaRefs[ref]++
return ref, nil
}
ref, err := g.generateWithoutSaving(parents, t, name, tag)
if ref != nil {
g.Types[t] = ref
g.SchemaRefs[ref]++
}
return ref, err
}
func (g *Generator) generateWithoutSaving(parents []*jsoninfo.TypeInfo, t reflect.Type, name string, tag reflect.StructTag) (*openapi3.SchemaRef, error) {
typeInfo := jsoninfo.GetTypeInfo(t)
for _, parent := range parents {
if parent == typeInfo {
return nil, &CycleError{}
}
}
if cap(parents) == 0 {
parents = make([]*jsoninfo.TypeInfo, 0, 4)
}
parents = append(parents, typeInfo)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if strings.HasSuffix(t.Name(), "Ref") {
_, a := t.FieldByName("Ref")
v, b := t.FieldByName("Value")
if a && b {
vs, err := g.generateSchemaRefFor(parents, v.Type, name, tag)
if err != nil {
if _, ok := err.(*CycleError); ok && !g.opts.throwErrorOnCycle {
g.SchemaRefs[vs]++
return vs, nil
}
return nil, err
}
refSchemaRef := RefSchemaRef
g.SchemaRefs[refSchemaRef]++
ref := openapi3.NewSchemaRef(t.Name(), &openapi3.Schema{
OneOf: []*openapi3.SchemaRef{
refSchemaRef,
vs,
},
})
g.SchemaRefs[ref]++
return ref, nil
}
}
schema := &openapi3.Schema{}
switch t.Kind() {
case reflect.Func, reflect.Chan:
return nil, nil // ignore
case reflect.Bool:
schema.Type = "boolean"
case reflect.Int:
schema.Type = "integer"
case reflect.Int8:
schema.Type = "integer"
schema.Min = &minInt8
schema.Max = &maxInt8
case reflect.Int16:
schema.Type = "integer"
schema.Min = &minInt16
schema.Max = &maxInt16
case reflect.Int32:
schema.Type = "integer"
schema.Format = "int32"
case reflect.Int64:
schema.Type = "integer"
schema.Format = "int64"
case reflect.Uint:
schema.Type = "integer"
schema.Min = &zeroInt
case reflect.Uint8:
schema.Type = "integer"
schema.Min = &zeroInt
schema.Max = &maxUint8
case reflect.Uint16:
schema.Type = "integer"
schema.Min = &zeroInt
schema.Max = &maxUint16
case reflect.Uint32:
schema.Type = "integer"
schema.Min = &zeroInt
schema.Max = &maxUint32
case reflect.Uint64:
schema.Type = "integer"
schema.Min = &zeroInt
schema.Max = &maxUint64
case reflect.Float32:
schema.Type = "number"
schema.Format = "float"
case reflect.Float64:
schema.Type = "number"
schema.Format = "double"
case reflect.String:
schema.Type = "string"
case reflect.Slice:
if t.Elem().Kind() == reflect.Uint8 {
if t == rawMessageType {
return &openapi3.SchemaRef{Value: schema}, nil
}
schema.Type = "string"
schema.Format = "byte"
} else {
schema.Type = "array"
items, err := g.generateSchemaRefFor(parents, t.Elem(), name, tag)
if err != nil {
if _, ok := err.(*CycleError); ok && !g.opts.throwErrorOnCycle {
items = g.generateCycleSchemaRef(t.Elem(), schema)
} else {
return nil, err
}
}
if items != nil {
g.SchemaRefs[items]++
schema.Items = items
}
}
case reflect.Map:
schema.Type = "object"
additionalProperties, err := g.generateSchemaRefFor(parents, t.Elem(), name, tag)
if err != nil {
if _, ok := err.(*CycleError); ok && !g.opts.throwErrorOnCycle {
additionalProperties = g.generateCycleSchemaRef(t.Elem(), schema)
} else {
return nil, err
}
}
if additionalProperties != nil {
g.SchemaRefs[additionalProperties]++
schema.AdditionalProperties = additionalProperties
}
case reflect.Struct:
if t == timeType {
schema.Type = "string"
schema.Format = "date-time"
} else {
for _, fieldInfo := range typeInfo.Fields {
// Only fields with JSON tag are considered (by default)
if !fieldInfo.HasJSONTag && !g.opts.useAllExportedFields {
continue
}
// If asked, try to use yaml tag
fieldName, fType := fieldInfo.JSONName, fieldInfo.Type
if !fieldInfo.HasJSONTag && g.opts.useAllExportedFields {
// Handle anonymous fields/embedded structs
if t.Field(fieldInfo.Index[0]).Anonymous {
ref, err := g.generateSchemaRefFor(parents, fType, fieldName, tag)
if err != nil {
if _, ok := err.(*CycleError); ok && !g.opts.throwErrorOnCycle {
ref = g.generateCycleSchemaRef(fType, schema)
} else {
return nil, err
}
}
if ref != nil {
g.SchemaRefs[ref]++
schema.WithPropertyRef(fieldName, ref)
}
} else {
ff := t.Field(fieldInfo.Index[len(fieldInfo.Index)-1])
if tag, ok := ff.Tag.Lookup("yaml"); ok && tag != "-" {
fieldName, fType = tag, ff.Type
}
}
}
// extract the field tag if we have a customizer
var fieldTag reflect.StructTag
if g.opts.schemaCustomizer != nil {
ff := t.Field(fieldInfo.Index[len(fieldInfo.Index)-1])
fieldTag = ff.Tag
}
ref, err := g.generateSchemaRefFor(parents, fType, fieldName, fieldTag)
if err != nil {
if _, ok := err.(*CycleError); ok && !g.opts.throwErrorOnCycle {
ref = g.generateCycleSchemaRef(fType, schema)
} else {
return nil, err
}
}
if ref != nil {
g.SchemaRefs[ref]++
schema.WithPropertyRef(fieldName, ref)
}
}
// Object only if it has properties
if schema.Properties != nil {
schema.Type = "object"
}
}
}
if g.opts.schemaCustomizer != nil {
if err := g.opts.schemaCustomizer(name, t, tag, schema); err != nil {
return nil, err
}
}
return openapi3.NewSchemaRef(t.Name(), schema), nil
}
func (g *Generator) generateCycleSchemaRef(t reflect.Type, schema *openapi3.Schema) *openapi3.SchemaRef {
var typeName string
switch t.Kind() {
case reflect.Ptr:
return g.generateCycleSchemaRef(t.Elem(), schema)
case reflect.Slice:
ref := g.generateCycleSchemaRef(t.Elem(), schema)
sliceSchema := openapi3.NewSchema()
sliceSchema.Type = "array"
sliceSchema.Items = ref
return openapi3.NewSchemaRef("", sliceSchema)
case reflect.Map:
ref := g.generateCycleSchemaRef(t.Elem(), schema)
mapSchema := openapi3.NewSchema()
mapSchema.Type = "object"
mapSchema.AdditionalProperties = ref
return openapi3.NewSchemaRef("", mapSchema)
default:
typeName = t.Name()
}
return openapi3.NewSchemaRef(fmt.Sprintf("#/components/schemas/%s", typeName), schema)
}
var RefSchemaRef = openapi3.NewSchemaRef("Ref",
openapi3.NewObjectSchema().WithProperty("$ref", openapi3.NewStringSchema().WithMinLength(1)))
var (
timeType = reflect.TypeOf(time.Time{})
rawMessageType = reflect.TypeOf(json.RawMessage{})
zeroInt = float64(0)
maxInt8 = float64(math.MaxInt8)
minInt8 = float64(math.MinInt8)
maxInt16 = float64(math.MaxInt16)
minInt16 = float64(math.MinInt16)
maxUint8 = float64(math.MaxUint8)
maxUint16 = float64(math.MaxUint16)
maxUint32 = float64(math.MaxUint32)
maxUint64 = float64(math.MaxUint64)
)