-
Notifications
You must be signed in to change notification settings - Fork 52
/
generator.go
1310 lines (1219 loc) · 35 KB
/
generator.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package openapi
import (
"errors"
"fmt"
"net/http"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"github.com/gofrs/uuid"
"github.com/loopfz/gadgeto/tonic"
)
const (
version = "3.0.1"
anyMediaType = "*/*"
formatTag = "format"
deprecatedTag = "deprecated"
descriptionTag = "description"
componentsSchemaPath = "#/components/schemas/"
)
var (
paramsInPathRe = regexp.MustCompile(`\{(.*?)\}`)
ginPathParamRe = regexp.MustCompile(`\/:([^\/]*)`)
)
// mediaTags maps media types to well-known
// struct tags used for marshaling.
var mediaTags = map[string]string{
"application/json": "json",
"application/xml": "xml",
}
// Generator is an OpenAPI 3 generator.
type Generator struct {
api *OpenAPI
config *SpecGenConfig
schemaTypes map[reflect.Type]struct{}
typeNames map[reflect.Type]string
dataTypes map[reflect.Type]*OverridedDataType
operationsIDS map[string]struct{}
errors []error
fullNames bool
sortParams bool
sortTags bool
}
// NewGenerator returns a new OpenAPI generator.
func NewGenerator(conf *SpecGenConfig) (*Generator, error) {
if conf == nil {
return nil, errors.New("missing config")
}
components := &Components{
Schemas: make(map[string]*SchemaOrRef),
Responses: make(map[string]*ResponseOrRef),
Parameters: make(map[string]*ParameterOrRef),
Headers: make(map[string]*HeaderOrRef),
}
return &Generator{
config: conf,
api: &OpenAPI{
OpenAPI: version,
Info: &Info{},
Paths: make(Paths),
Components: components,
},
schemaTypes: make(map[reflect.Type]struct{}),
typeNames: make(map[reflect.Type]string),
dataTypes: make(map[reflect.Type]*OverridedDataType),
operationsIDS: make(map[string]struct{}),
fullNames: true,
sortParams: true,
sortTags: true,
}, nil
}
// SpecGenConfig represents the configuration
// of the spec generator.
type SpecGenConfig struct {
// Name of the tag used by the validator.v8
// package. This is used by the spec generator
// to determine if a field is required.
ValidatorTag string
PathLocationTag string
QueryLocationTag string
HeaderLocationTag string
EnumTag string
DefaultTag string
}
// SetInfo uses the given OpenAPI info for the
// current specification.
func (g *Generator) SetInfo(info *Info) {
g.api.Info = info
}
// SetServers sets the server list for the
// current specification.
func (g *Generator) SetServers(servers []*Server) {
g.api.Servers = servers
}
// SetSecurityRequirement sets the security options for the
// current specification.
func (g *Generator) SetSecurityRequirement(security []*SecurityRequirement) {
g.api.Security = security
}
// SetSecuritySchemes sets the security schemes that can be used
// inside the operations of the specification.
func (g *Generator) SetSecuritySchemes(security map[string]*SecuritySchemeOrRef) {
g.api.Components.SecuritySchemes = security
}
// API returns a copy of the internal OpenAPI object.
func (g *Generator) API() *OpenAPI {
cpy := *g.api
return &cpy
}
// Errors returns the errors thar occurred during
// the generation of the specification.
func (g *Generator) Errors() []error {
return g.errors
}
// UseFullSchemaNames defines whether the generator should generates
// a full name for the components using the package name of the type
// as a prefix.
// Omitting the package part of the name increases the risks of conflicts.
// It is the responsibility of the developper to ensure that unique type
// names are used across all the packages of the application.
// Default to true.
func (g *Generator) UseFullSchemaNames(b bool) {
g.fullNames = b
}
// SetSortParams controls whether the generator should
// sort the parameters of an operation by location and
// name in ascending order.
func (g *Generator) SetSortParams(b bool) {
g.sortParams = b
}
// SetSortTags controls whether the generator should
// sort the global tags sections.
func (g *Generator) SetSortTags(b bool) {
g.sortTags = b
}
// OverrideTypeName registers a custom name for a
// type that will override the default generation
// and have precedence over types that implements
// the Typer interface.
func (g *Generator) OverrideTypeName(t reflect.Type, name string) error {
if name == "" {
return errors.New("type name is empty")
}
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if _, ok := g.typeNames[t]; ok {
return errors.New("type name already overrided")
}
g.typeNames[t] = name
return nil
}
// OverrideDataType registers a custom schema type and
// format for the given type that will overrided the
// default generation.
func (g *Generator) OverrideDataType(t reflect.Type, typ, format string) error {
if typ == "" {
return errors.New("type is mandatory")
}
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if _, ok := g.dataTypes[t]; ok {
return errors.New("data type already overrided")
}
g.dataTypes[t] = &OverridedDataType{
format: format,
typ: typ,
}
return nil
}
func (g *Generator) datatype(t reflect.Type) DataType {
if dt, ok := g.dataTypes[t]; ok {
return dt
}
return DataTypeFromType(t)
}
// AddTag adds a new tag to the OpenAPI specification.
// If a tag already exists with the same name, it is
// overwritten.
func (g *Generator) AddTag(name, desc string) {
if name == "" {
return
}
// Search for an existing tag with the same name,
// and update its description before returning
// if one is found.
for _, tag := range g.api.Tags {
if tag != nil {
if tag.Name == name {
tag.Description = desc
return
}
}
}
// Add a new tag to the spec.
g.api.Tags = append(g.api.Tags, &Tag{
Name: name,
Description: desc,
})
if g.sortTags {
sort.SliceStable(g.api.Tags, func(i, j int) bool {
if g.api.Tags[i] != nil && g.api.Tags[j] != nil {
return g.api.Tags[i].Name < g.api.Tags[j].Name
}
return false
})
}
}
// AddOperation add a new operation to the OpenAPI specification
// using the method and path of the route and the tonic
// handler informations.
func (g *Generator) AddOperation(path, method, tag string, in, out reflect.Type, info *OperationInfo) (*Operation, error) {
op := &Operation{
ID: uuid.Must(uuid.NewV4()).String(),
}
path = rewritePath(path)
if info != nil {
// Ensure that the provided operation ID is unique.
if _, ok := g.operationsIDS[info.ID]; ok {
return nil, fmt.Errorf("ID %s is already used by another operation", info.ID)
}
g.operationsIDS[info.ID] = struct{}{}
}
// If a PathItem does not exists for this
// path, create a new one.
item, ok := g.api.Paths[path]
if !ok {
item = new(PathItem)
g.api.Paths[path] = item
}
// Create a new operation and set it
// to the according method of the PathItem.
if info != nil {
op.ID = info.ID
op.Summary = info.Summary
op.Description = info.Description
op.Deprecated = info.Deprecated
op.Responses = make(Responses)
op.XCodeSamples = info.XCodeSamples
op.Security = info.Security
op.XInternal = info.XInternal
}
if tag != "" {
op.Tags = append(op.Tags, tag)
}
// Operations with methods GET/HEAD/DELETE cannot have a body.
// Non parameters fields will be ignored.
allowBody := method != http.MethodGet &&
method != http.MethodHead &&
method != http.MethodDelete
if in != nil {
if in.Kind() == reflect.Ptr {
in = in.Elem()
}
if in.Kind() != reflect.Struct {
return nil, errors.New("input type is not a struct")
}
if err := g.setOperationParams(op, in, in, allowBody, path); err != nil {
return nil, err
}
}
// Generate the default response from the tonic
// handler return type. If the handler has no output
// type, the response won't have a schema.
if err := g.setOperationResponse(op, out, strconv.Itoa(info.StatusCode), tonic.MediaType(), info.StatusDescription, info.Headers, nil, nil); err != nil {
return nil, err
}
// Generate additional responses from the operation
// informations.
for _, resp := range info.Responses {
if resp != nil {
if err := g.setOperationResponse(op,
reflect.TypeOf(resp.Model),
resp.Code,
tonic.MediaType(),
resp.Description,
resp.Headers,
resp.Example,
resp.Examples,
); err != nil {
return nil, err
}
}
}
setOperationBymethod(item, op, method)
return op, nil
}
// rewritePath converts a Gin operation path that use
// colons and asterisks to declare path parameters, to
// an OpenAPI representation that use curly braces.
func rewritePath(path string) string {
return ginPathParamRe.ReplaceAllString(path, "/{$1}")
}
// setOperationBymethod sets the operation op to the appropriate
// field of item according to the given method.
func setOperationBymethod(item *PathItem, op *Operation, method string) {
switch method {
case "GET":
item.GET = op
case "PUT":
item.PUT = op
case "POST":
item.POST = op
case "PATCH":
item.PATCH = op
case "HEAD":
item.HEAD = op
case "OPTIONS":
item.OPTIONS = op
case "TRACE":
item.TRACE = op
case "DELETE":
item.DELETE = op
}
}
func isResponseCodeRange(code string) bool {
if len(code) != 3 {
return false
}
// First char must be 1, 2, 3, 4 or 5.
pre := code[0]
if pre < 49 || pre > 53 {
return false
}
// Last two chars are wildcard letter X.
if code[1] != 'X' || code[2] != 'X' {
return false
}
return true
}
// setOperationResponse adds a response to the operation that
// return the type t with the given media type and status code.
func (g *Generator) setOperationResponse(op *Operation, t reflect.Type, code, mt, desc string, headers []*ResponseHeader, example interface{}, examples map[string]interface{}) error {
if _, ok := op.Responses[code]; ok {
// A response already exists for this code.
return fmt.Errorf("response with code %s already exists", code)
}
if example != nil && examples != nil {
// Cannot set both 'example' and 'examples' values
return fmt.Errorf("'example' and 'examples' are mutually exclusive")
}
// Check that the response code is valid per the spec:
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#patterned-fields-1
if code != "default" {
if !isResponseCodeRange(code) { // ignore ranges
// Convert code to number and check that it is
// between 100 and 599.
ci, err := strconv.Atoi(code)
if err != nil {
return fmt.Errorf("invalid response code: %s", err)
}
if ci < 100 || ci > 599 {
return fmt.Errorf("response code out of range: %s", code)
}
if desc == "" {
desc = http.StatusText(ci)
}
}
}
r := &Response{
Description: desc,
Content: make(map[string]*MediaTypeOrRef),
Headers: make(map[string]*HeaderOrRef),
}
var castedExamples map[string]*ExampleOrRef
if examples != nil {
castedExamples = make(map[string]*ExampleOrRef)
for name, val := range examples {
castedExamples[name] = &ExampleOrRef{Example: &Example{Value: val}}
}
}
// The response may have no content type specified,
// in which case we don't assign a schema.
schema := g.newSchemaFromType(t)
if schema != nil || example != nil || castedExamples != nil {
r.Content[mt] = &MediaTypeOrRef{MediaType: &MediaType{
Schema: schema,
Example: example,
Examples: castedExamples,
}}
}
// Assign headers.
for _, h := range headers {
if h != nil {
var sor *SchemaOrRef
if h.Model == nil {
// default to string if no type is given.
sor = &SchemaOrRef{Schema: &Schema{Type: "string"}}
} else {
sor = g.newSchemaFromType(reflect.TypeOf(h.Model))
}
r.Headers[h.Name] = &HeaderOrRef{Header: &Header{
Description: h.Description,
Schema: sor,
}}
}
}
op.Responses[code] = &ResponseOrRef{Response: r}
return nil
}
// setOperationParams adds the fields of the struct type t
// to the given operation.
func (g *Generator) setOperationParams(op *Operation, t, parent reflect.Type, allowBody bool, path string) error {
if t.Kind() != reflect.Struct {
return errors.New("input type is not a struct")
}
if err := g.buildParamsRecursive(op, t, parent, allowBody); err != nil {
return err
}
// Input fields that are neither path- nor query-bound
// have been extracted into the operation's RequestBody
// If the RequestBody is not nil, give it a name and
// move it to the openapi spec's components/schemas section
// Replace the RequestBody's schema with a reference
// to the named schema in components/schemas
if op.RequestBody != nil {
mt := tonic.MediaType()
if mt == "" {
mt = anyMediaType
}
sch := op.RequestBody.Content[mt].Schema
if sch != nil {
name := strings.Title(op.ID) + "Input"
g.api.Components.Schemas[name] = sch
op.RequestBody.Content[mt].Schema = &SchemaOrRef{Reference: &Reference{
Ref: componentsSchemaPath + name,
}}
}
}
// Extract all the path parameter names.
matches := paramsInPathRe.FindAllStringSubmatch(path, -1)
var pathParams []string
for _, m := range matches {
pathParams = append(pathParams, m[1])
}
// Check that all declared path parameters are
// defined in the operation.
for _, pp := range pathParams {
has := false
for _, param := range op.Parameters {
if param.In == "path" && param.Name == pp {
has = true
break
}
}
if !has {
return fmt.Errorf("semantic error for path %s: declared path parameter %s needs to be defined at operation level", path, pp)
}
}
// Sort operations parameters by location and name
// in ascending order.
if g.sortParams {
paramsOrderedBy(
g.paramyByLocation,
g.paramyByName,
).Sort(op.Parameters)
}
return nil
}
func (g *Generator) buildParamsRecursive(op *Operation, t, parent reflect.Type, allowBody bool) error {
for i := 0; i < t.NumField(); i++ {
sf := t.Field(i)
sft := sf.Type
// Dereference pointer.
if sft.Kind() == reflect.Ptr {
sft = sft.Elem()
}
isUnexported := sf.PkgPath != ""
if sf.Anonymous {
if isUnexported && sft.Kind() != reflect.Struct {
// Ignore embedded fields of unexported non-struct types.
continue
}
// Do not ignore embedded fields of unexported struct
// types since they may have exported fields, and recursively
// use its fields as operations params. This allow developers
// to reuse input models using type composition.
if sft.Kind() == reflect.Struct {
// If the type of the embedded struct is the same as
// the topmost parent, skip it to avoid an infinite
// recursive loop.
if sft == parent {
g.error(&FieldError{
Message: "recursive embedding",
Name: sf.Name,
TypeName: g.typeName(parent),
Type: parent,
})
} else if err := g.buildParamsRecursive(op, sft, parent, allowBody); err != nil {
return err
}
}
continue
} else if isUnexported {
// Ignore unexported non-embedded fields.
continue
}
if err := g.addStructFieldToOperation(op, t, i, allowBody); err != nil {
return err
}
}
return nil
}
func (g *Generator) paramyByName(p1, p2 *ParameterOrRef) bool {
return g.resolveParameter(p1).Name < g.resolveParameter(p2).Name
}
func (g *Generator) paramyByLocation(p1, p2 *ParameterOrRef) bool {
return locationsOrder[g.resolveParameter(p1).In] < locationsOrder[g.resolveParameter(p2).In]
}
// addStructFieldToOperation add the struct field of the type
// t at index idx to the operation op. A field will be considered
// as a parameter if it has a valid location tag key, or it will
// be treated as part of the request body.
func (g *Generator) addStructFieldToOperation(op *Operation, t reflect.Type, idx int, allowBody bool) error {
sf := t.Field(idx)
param, err := g.newParameterFromField(idx, t)
if err != nil {
return err
}
if param != nil {
// Check if a parameter with same name/location
// already exists.
for _, p := range op.Parameters {
if p != nil && (p.Name == param.Name) && (p.In == param.In) {
g.error(&FieldError{
Message: "duplicate parameter",
Name: param.Name,
TypeName: g.typeName(t),
Type: t,
ParameterLocation: param.In,
})
return nil
}
}
op.Parameters = append(op.Parameters, &ParameterOrRef{
Parameter: param,
})
} else {
if !allowBody {
return nil
}
// If binding is disabled for this field, don't
// add it to the request body. This allow using
// a model type as an operation input while also
// omitting some fields that are computed by the
// server.
if sf.Tag.Get("binding") == "-" {
return nil
}
// The field is not a parameter, add it to
// the request body.
if op.RequestBody == nil {
op.RequestBody = &RequestBody{
Content: make(map[string]*MediaType),
}
}
// Select the corresponding media type for the
// given field tag, or default to any type.
mt := tonic.MediaType()
if mt == "" {
mt = anyMediaType
}
var schema *Schema
// Create the media type if no fields
// have been added yet.
if _, ok := op.RequestBody.Content[mt]; !ok {
schema = &Schema{
Type: "object",
Properties: make(map[string]*SchemaOrRef),
}
op.RequestBody.Content[mt] = &MediaType{
Schema: &SchemaOrRef{Schema: schema},
}
} else {
schema = op.RequestBody.Content[mt].Schema.Schema
}
fname := fieldNameFromTag(sf, mediaTags[tonic.MediaType()])
// Check if a field with the same name already exists.
if _, ok := schema.Properties[fname]; ok {
g.error(&FieldError{
Message: "duplicate request body parameter",
Name: fname,
TypeName: g.typeName(t),
Type: t,
ParameterLocation: "body",
})
return nil
}
var required bool
// The required property of a field is not part of its
// own schema but specified in the parent schema.
if fname != "" && g.isStructFieldRequired(sf) {
required = true
schema.Required = append(schema.Required, fname)
sort.Strings(schema.Required)
}
sfs := g.newSchemaFromStructField(sf, required, fname, t)
if schema != nil {
schema.Properties[fname] = sfs
}
}
return nil
}
// newParameterFromField create a new operation parameter
// from the struct field at index idx in type in. Only the
// parameters of type path, query, header or cookie are concerned.
func (g *Generator) newParameterFromField(idx int, t reflect.Type) (*Parameter, error) {
field := t.Field(idx)
location, err := g.paramLocation(field, t)
if err != nil {
return nil, err
}
// The parameter location is empty, return nil
// to indicate that the field is not a parameter.
if location == "" {
return nil, nil
}
name, err := tonic.ParseTagKey(field.Tag.Get(location))
if err != nil {
return nil, err
}
required := g.isStructFieldRequired(field)
// Path parameters are always required.
if location == g.config.PathLocationTag {
required = true
}
// Consider invalid values as false.
deprecated, _ := strconv.ParseBool(field.Tag.Get(deprecatedTag))
p := &Parameter{
Name: name,
In: location,
Description: field.Tag.Get(descriptionTag),
Required: required,
Deprecated: deprecated,
Schema: g.newSchemaFromStructField(field, required, name, t),
}
if field.Type.Kind() == reflect.Bool && location == g.config.QueryLocationTag {
p.AllowEmptyValue = true
}
// Style.
if location == g.config.QueryLocationTag {
if field.Type.Kind() == reflect.Slice || field.Type.Kind() == reflect.Array {
p.Explode = true // default
p.Style = "form" // default in spec, but make it obvious
if t := field.Tag.Get(tonic.ExplodeTag); t != "" {
if explode, err := strconv.ParseBool(t); err == nil && !explode { // ignore invalid values
p.Explode = explode
}
}
}
}
return p, nil
}
// paramLocation parses the tags of the struct field to extract
// the location of an operation parameter.
func (g *Generator) paramLocation(f reflect.StructField, in reflect.Type) (string, error) {
var c, p int
has := func(name string, tag reflect.StructTag, i int) {
if _, ok := tag.Lookup(name); ok {
c++
// save name position to extract
// the value of the unique key.
p = i
}
}
// Count the number of keys that represents
// a parameter location from the tag of the
// struct field.
parameterLocations := []string{
g.config.PathLocationTag,
g.config.QueryLocationTag,
g.config.HeaderLocationTag,
}
for i, n := range parameterLocations {
has(n, f.Tag, i)
}
if c == 0 {
// This will be considered to be part
// of the request body.
return "", nil
}
if c > 1 {
return "", &FieldError{
Message: "conflicting parameter location",
Name: f.Name,
TypeName: g.typeName(in),
Type: in,
}
}
return parameterLocations[p], nil
}
// newSchemaFromStructField returns a new Schema builded
// from the field's type and its tags.
func (g *Generator) newSchemaFromStructField(sf reflect.StructField, required bool, fname string, parent reflect.Type) *SchemaOrRef {
sor := g.newSchemaFromType(sf.Type)
if sor == nil {
return nil
}
// Get the underlying schema, it may be a reference
// to a component, and update its fields using the
// informations in the struct field tags.
schema := g.resolveSchema(sor)
if schema == nil {
return sor
}
// Default value.
// See section 'Common Mistakes' at
// https://swagger.io/docs/specification/describing-parameters/
if d := sf.Tag.Get(g.config.DefaultTag); d != "" {
if required {
g.error(&FieldError{
Message: "field cannot be required and have a default value",
Name: fname,
Type: sf.Type,
TypeName: g.typeName(sf.Type),
Parent: parent,
})
} else {
if v, err := stringToType(d, sf.Type); err != nil {
g.error(&FieldError{
Message: fmt.Sprintf("default value %s cannot be converted to field type: %s", d, err),
Name: fname,
Type: sf.Type,
TypeName: g.typeName(sf.Type),
Parent: parent,
})
} else {
schema.Default = v
}
}
}
// Enum.
// Must be applied to underlying items schema if the
// parameter is an array, instead of the parameter schema.
enum := g.enumFromStructField(sf, fname, parent)
if schema.Type == "array" && schema.Items != nil {
itemsSchema := g.resolveSchema(schema.Items)
if itemsSchema != nil {
itemsSchema.Enum = enum
}
} else {
schema.Enum = enum
}
// Field description.
if desc, ok := sf.Tag.Lookup(descriptionTag); ok {
schema.Description = desc
}
// Deprecated.
// Consider invalid values as false.
schema.Deprecated, _ = strconv.ParseBool(sf.Tag.Get(deprecatedTag))
// Update schema fields related to the JSON Validation
// spec based on the content of the validator tag.
schema = g.updateSchemaValidation(schema, sf)
// Allow overidding schema properties that were
// auto inferred manually via tags.
if t, ok := sf.Tag.Lookup(formatTag); ok {
schema.Format = t
}
// Set example value from tag to schema
if e := strings.TrimSpace(sf.Tag.Get("example")); e != "" {
if parsed, err := parseExampleValue(sf.Type, e); err != nil {
g.error(&FieldError{
Message: fmt.Sprintf("could not parse the example value %q of field %q: %s", e, fname, err),
Name: fname,
Type: sf.Type,
TypeName: g.typeName(sf.Type),
Parent: parent,
})
} else {
schema.Example = parsed
}
}
return sor
}
func (g *Generator) enumFromStructField(sf reflect.StructField, fname string, parent reflect.Type) []interface{} {
var enum []interface{}
etag := sf.Tag.Get(g.config.EnumTag)
if etag != "" {
values := strings.Split(etag, ",")
sftype := sf.Type
// Use underlying element type if it's an array/slice/pointer
for sftype.Kind() == reflect.Ptr || sftype.Kind() == reflect.Slice || sftype.Kind() == reflect.Array {
sftype = sftype.Elem()
}
for _, val := range values {
if v, err := stringToType(val, sftype); err != nil {
g.error(&FieldError{
Message: fmt.Sprintf("enum value %s cannot be converted to field type: %s", val, err),
Name: fname,
Type: sf.Type,
TypeName: g.typeName(sf.Type),
Parent: parent,
})
} else {
enum = append(enum, v)
}
}
}
return enum
}
// newSchemaFromType creates a new OpenAPI schema from
// the given reflect type.
func (g *Generator) newSchemaFromType(t reflect.Type) *SchemaOrRef {
if t == nil {
return nil
}
var nullable bool
// Dereference pointer.
if t.Kind() == reflect.Ptr {
t = t.Elem()
nullable = true
} else if t.Implements(tofNullable) {
i, ok := reflect.New(t).Interface().(Nullable)
if ok {
nullable = i.Nullable()
}
}
dt := g.datatype(t)
if dt == TypeUnsupported {
g.error(&TypeError{
Message: "unsupported type",
Type: t,
})
return nil
}
if dt == TypeComplex {
switch t.Kind() {
case reflect.Slice, reflect.Array, reflect.Map:
return g.buildSchemaRecursive(t)
case reflect.Struct:
return g.newSchemaFromStruct(t)
}
}
if dt == TypeAny {
return &SchemaOrRef{
Schema: &Schema{
Nullable: true,
Description: "Value of any type, including null",
},
}
}
schema := &Schema{
Type: dt.Type(),
Format: dt.Format(),
Nullable: nullable,
}
return &SchemaOrRef{Schema: schema}
}
// buildSchemaRecursive recursively decomposes the complex
// type t into subsequent schemas.
func (g *Generator) buildSchemaRecursive(t reflect.Type) *SchemaOrRef {
schema := &Schema{}
switch t.Kind() {
case reflect.Ptr:
return g.buildSchemaRecursive(t.Elem())
case reflect.Struct:
return g.newSchemaFromStruct(t)
case reflect.Map:
// Map type is considered as a type "object"
// and should declare underlying items type
// in additional properties field.
schema.Type = "object"
// JSON Schema allow only strings as object key.
if t.Key().Kind() != reflect.String {
g.error(&TypeError{
Message: "encountered type Map with keys of unsupported type",
Type: t,
})
return nil
}
schema.AdditionalProperties = g.buildSchemaRecursive(t.Elem())
case reflect.Slice, reflect.Array:
// Slice/Array types are considered as a type
// "array" and should declare underlying items
// type in items field.
schema.Type = "array"
// Go arrays have fixed size.
if t.Kind() == reflect.Array {
schema.MinItems = t.Len()
schema.MaxItems = t.Len()
}
schema.Items = g.buildSchemaRecursive(t.Elem())
default:
dt := g.datatype(t)
schema.Type, schema.Format = dt.Type(), dt.Format()
}
return &SchemaOrRef{Schema: schema}
}
// structSchema returns an OpenAPI schema that describe
// the Go struct represented by the type t.
func (g *Generator) newSchemaFromStruct(t reflect.Type) *SchemaOrRef {
if t.Kind() != reflect.Struct {
return nil
}
name := g.typeName(t)
// If the type of the field has already been registered,
// skip the schema generation to avoid a recursive loop.
// We're not returning directly a reference from the components,
// because there is no guarantee the generation is complete yet.
if _, ok := g.schemaTypes[t]; ok {
return &SchemaOrRef{Reference: &Reference{
Ref: componentsSchemaPath + name,
}}
}
schema := &Schema{
Type: "object",
Properties: make(map[string]*SchemaOrRef),
}
// Register the type once before diving into
// the recursive hole if it has a name. Anonymous
// struct are all considered unique.
if name != "" {
g.schemaTypes[t] = struct{}{}
}
schema = g.flattenStructSchema(t, t, schema)
sor := &SchemaOrRef{Schema: schema}
// Register the schema within the speccomponents and return a
// relative reference. Unnamed types, like anonymous structs,
// will always be inlined in the specification.
if name != "" {
g.api.Components.Schemas[name] = sor
return &SchemaOrRef{Reference: &Reference{
Ref: componentsSchemaPath + name,
}}