forked from go-swagger/go-swagger
/
operation.go
1044 lines (923 loc) · 28.8 KB
/
operation.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
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package generator
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/go-swagger/go-swagger/httpkit"
"github.com/go-swagger/go-swagger/spec"
"github.com/go-swagger/go-swagger/swag"
)
// GenerateServerOperation generates a parameter model, parameter validator, http handler implementations for a given operation
// It also generates an operation handler interface that uses the parameter model for handling a valid request.
// Allows for specifying a list of tags to include only certain tags for the generation
func GenerateServerOperation(operationNames, tags []string, includeHandler, includeParameters, includeResponses bool, opts GenOpts) error {
// Load the spec
_, specDoc, err := loadSpec(opts.Spec)
if err != nil {
return err
}
ops := gatherOperations(specDoc, operationNames)
for operationName, opRef := range ops {
method, path, operation := opRef.Method, opRef.Path, opRef.Op
defaultScheme := opts.DefaultScheme
if defaultScheme == "" {
defaultScheme = "http"
}
apiPackage := mangleName(swag.ToFileName(opts.APIPackage), "api")
serverPackage := mangleName(swag.ToFileName(opts.ServerPackage), "server")
generator := operationGenerator{
Name: operationName,
Method: method,
Path: path,
APIPackage: apiPackage,
ModelsPackage: mangleName(swag.ToFileName(opts.ModelPackage), "definitions"),
ClientPackage: mangleName(swag.ToFileName(opts.ClientPackage), "client"),
ServerPackage: serverPackage,
Operation: operation,
SecurityRequirements: specDoc.SecurityRequirementsFor(&operation),
Principal: opts.Principal,
Target: filepath.Join(opts.Target, serverPackage),
Base: opts.Target,
Tags: tags,
IncludeHandler: includeHandler,
IncludeParameters: includeParameters,
IncludeResponses: includeResponses,
DumpData: opts.DumpData,
DefaultScheme: defaultScheme,
Doc: specDoc,
}
if err := generator.Generate(); err != nil {
return err
}
}
return nil
}
type operationGenerator struct {
Name string
Method string
Path string
Authorized bool
APIPackage string
ModelsPackage string
ServerPackage string
ClientPackage string
Operation spec.Operation
SecurityRequirements []spec.SecurityRequirement
Principal string
Target string
Base string
Tags []string
data interface{}
pkg string
cname string
IncludeHandler bool
IncludeParameters bool
IncludeResponses bool
DumpData bool
DefaultScheme string
Doc *spec.Document
}
func (o *operationGenerator) Generate() error {
// Build a list of codegen operations based on the tags,
// the tag decides the actual package for an operation
// the user specified package serves as root for generating the directory structure
var operations GenOperations
authed := len(o.SecurityRequirements) > 0
var bldr codeGenOpBuilder
bldr.Name = o.Name
bldr.Method = o.Method
bldr.Path = o.Path
bldr.ModelsPackage = o.ModelsPackage
bldr.Principal = o.Principal
bldr.Target = o.Target
bldr.Operation = o.Operation
bldr.Authed = authed
bldr.Doc = o.Doc
bldr.DefaultScheme = o.DefaultScheme
bldr.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(o.Base), o.ModelsPackage))}
bldr.RootAPIPackage = o.APIPackage
for _, tag := range o.Operation.Tags {
if len(o.Tags) == 0 {
bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
op, err := bldr.MakeOperation()
if err != nil {
return err
}
operations = append(operations, op)
continue
}
for _, ft := range o.Tags {
if ft == tag {
bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
op, err := bldr.MakeOperation()
if err != nil {
return err
}
operations = append(operations, op)
break
}
}
}
if len(operations) == 0 {
bldr.APIPackage = o.APIPackage
op, err := bldr.MakeOperation()
if err != nil {
return err
}
operations = append(operations, op)
}
sort.Sort(operations)
for _, op := range operations {
if o.DumpData {
bb, _ := json.MarshalIndent(swag.ToDynamicJSON(op), "", " ")
fmt.Fprintln(os.Stdout, string(bb))
continue
}
o.data = op
o.pkg = op.Package
o.cname = swag.ToGoName(op.Name)
if o.IncludeHandler {
if err := o.generateHandler(); err != nil {
return fmt.Errorf("handler: %s", err)
}
log.Println("generated handler", op.Package+"."+o.cname)
}
opParams := o.Doc.ParamsFor(o.Method, o.Path)
if o.IncludeParameters && len(opParams) > 0 {
if err := o.generateParameterModel(); err != nil {
return fmt.Errorf("parameters: %s", err)
}
log.Println("generated parameters", op.Package+"."+o.cname+"Parameters")
}
if o.IncludeResponses && len(op.Responses) > 0 {
if err := o.generateResponses(); err != nil {
return fmt.Errorf("responses: %s", err)
}
log.Println("generated responses", op.Package+"."+o.cname+"Responses")
}
if len(opParams) == 0 {
log.Println("no parameters for operation", op.Package+"."+o.cname)
}
}
return nil
}
func (o *operationGenerator) generateHandler() error {
buf := bytes.NewBuffer(nil)
if err := operationTemplate.Execute(buf, o.data); err != nil {
return err
}
log.Println("rendered handler template:", o.pkg+"."+o.cname)
fp := filepath.Join(o.Target, o.pkg)
if o.pkg != o.APIPackage {
fp = filepath.Join(o.Target, o.APIPackage, o.pkg)
}
return writeToFile(fp, o.Name, buf.Bytes())
}
func (o *operationGenerator) generateParameterModel() error {
buf := bytes.NewBuffer(nil)
if err := parameterTemplate.Execute(buf, o.data); err != nil {
return err
}
log.Println("rendered parameters template:", o.pkg+"."+o.cname+"Parameters")
fp := filepath.Join(o.Target, o.pkg)
if o.pkg != o.APIPackage {
fp = filepath.Join(o.Target, o.APIPackage, o.pkg)
}
return writeToFile(fp, o.Name+"Parameters", buf.Bytes())
}
func (o *operationGenerator) generateResponses() error {
buf := bytes.NewBuffer(nil)
if err := responsesTemplate.Execute(buf, o.data); err != nil {
return err
}
log.Println("rendered responses template:", o.pkg+"."+o.cname+"Responses")
fp := filepath.Join(o.Target, o.pkg)
if o.pkg != o.APIPackage {
fp = filepath.Join(o.Target, o.APIPackage, o.pkg)
}
return writeToFile(fp, o.Name+"Responses", buf.Bytes())
}
type codeGenOpBuilder struct {
Name string
Method string
Path string
APIPackage string
RootAPIPackage string
ModelsPackage string
Principal string
Target string
Operation spec.Operation
Doc *spec.Document
Authed bool
DefaultImports []string
DefaultScheme string
ExtraSchemas map[string]GenSchema
}
func (b *codeGenOpBuilder) MakeOperation() (GenOperation, error) {
resolver := newTypeResolver(b.ModelsPackage, b.Doc.Pristine())
receiver := "o"
operation := b.Operation
var params, qp, pp, hp, fp GenParameters
var hasQueryParams, hasFormParams, hasFileParams bool
for _, p := range b.Doc.ParamsFor(b.Method, b.Path) {
cp, err := b.MakeParameter(receiver, resolver, p)
if err != nil {
return GenOperation{}, err
}
if cp.IsQueryParam() {
hasQueryParams = true
qp = append(qp, cp)
}
if cp.IsFormParam() {
if p.Type == "file" {
hasFileParams = true
}
hasFormParams = true
fp = append(fp, cp)
}
if cp.IsPathParam() {
pp = append(pp, cp)
}
if cp.IsHeaderParam() {
hp = append(hp, cp)
}
params = append(params, cp)
}
sort.Sort(params)
sort.Sort(qp)
sort.Sort(pp)
sort.Sort(hp)
sort.Sort(fp)
var responses map[int]GenResponse
var defaultResponse *GenResponse
var successResponse *GenResponse
if operation.Responses != nil {
for k, v := range operation.Responses.StatusCodeResponses {
isSuccess := k/100 == 2
gr, err := b.MakeResponse(receiver, swag.ToJSONName(b.Name+" "+httpkit.Statuses[k]), isSuccess, resolver, k, v)
if err != nil {
return GenOperation{}, err
}
if isSuccess {
successResponse = &gr
}
if responses == nil {
responses = make(map[int]GenResponse)
}
responses[k] = gr
}
if operation.Responses.Default != nil {
gr, err := b.MakeResponse(receiver, b.Name+" default", false, resolver, -1, *operation.Responses.Default)
if err != nil {
return GenOperation{}, err
}
defaultResponse = &gr
}
}
prin := b.Principal
if prin == "" {
prin = "interface{}"
}
var extra []GenSchema
for _, sch := range b.ExtraSchemas {
extra = append(extra, sch)
}
schemes := concatUnique(resolver.Doc.Spec().Schemes, operation.Schemes)
return GenOperation{
Package: b.APIPackage,
RootPackage: b.RootAPIPackage,
Name: b.Name,
Method: b.Method,
Path: b.Path,
Tags: operation.Tags[:],
Description: operation.Description,
ReceiverName: receiver,
DefaultImports: b.DefaultImports,
Params: params,
Summary: operation.Summary,
QueryParams: qp,
PathParams: pp,
HeaderParams: hp,
FormParams: fp,
HasQueryParams: hasQueryParams,
HasFormParams: hasFormParams,
HasFileParams: hasFileParams,
Authorized: b.Authed,
Principal: prin,
Responses: responses,
DefaultResponse: defaultResponse,
SuccessResponse: successResponse,
ExtraSchemas: extra,
Schemes: schemeOrDefault(schemes, b.DefaultScheme),
}, nil
}
func schemeOrDefault(schemes []string, defaultScheme string) []string {
if len(schemes) == 0 {
return []string{defaultScheme}
}
return schemes
}
func concatUnique(collections ...[]string) []string {
resultSet := make(map[string]struct{})
for _, c := range collections {
for _, i := range c {
if _, ok := resultSet[i]; !ok {
resultSet[i] = struct{}{}
}
}
}
var result []string
for k := range resultSet {
result = append(result, k)
}
return result
}
func (b *codeGenOpBuilder) MakeResponse(receiver, name string, isSuccess bool, resolver *typeResolver, code int, resp spec.Response) (GenResponse, error) {
res := GenResponse{
Package: b.APIPackage,
ModelsPackage: b.ModelsPackage,
ReceiverName: receiver,
Name: name,
Description: resp.Description,
DefaultImports: nil,
Imports: nil,
IsSuccess: isSuccess,
Code: code,
Method: b.Method,
Path: b.Path,
}
for hName, header := range resp.Headers {
res.Headers = append(res.Headers, b.MakeHeader(receiver, hName, header))
}
sort.Sort(res.Headers)
if resp.Schema != nil {
sc := schemaGenContext{
Path: fmt.Sprintf("%q", name),
Name: name + "Body",
Receiver: receiver,
ValueExpr: receiver,
IndexVar: "i",
Schema: *resp.Schema,
Required: true,
TypeResolver: resolver,
Named: false,
ExtraSchemas: make(map[string]GenSchema),
}
if err := sc.makeGenSchema(); err != nil {
return GenResponse{}, err
}
for k, v := range sc.ExtraSchemas {
if b.ExtraSchemas == nil {
b.ExtraSchemas = make(map[string]GenSchema)
}
b.ExtraSchemas[k] = v
}
schema := sc.GenSchema
if schema.IsAnonymous {
schema.Name = swag.ToGoName(sc.Name + " Body")
nm := schema.Name
if b.ExtraSchemas == nil {
b.ExtraSchemas = make(map[string]GenSchema)
}
b.ExtraSchemas[schema.Name] = schema
schema = GenSchema{}
schema.IsAnonymous = false
schema.GoType = resolver.goTypeName(nm)
schema.SwaggerType = nm
}
res.Schema = &schema
}
return res, nil
}
func (b *codeGenOpBuilder) MakeHeader(receiver, name string, hdr spec.Header) GenHeader {
hasNumberValidation := hdr.Maximum != nil || hdr.Minimum != nil || hdr.MultipleOf != nil
hasStringValidation := hdr.MaxLength != nil || hdr.MinLength != nil || hdr.Pattern != ""
hasSliceValidations := hdr.MaxItems != nil || hdr.MinItems != nil || hdr.UniqueItems
hasValidations := hasNumberValidation || hasStringValidation || hasSliceValidations || len(hdr.Enum) > 0
tpe := simpleResolvedType(hdr.Type, hdr.Format, hdr.Items)
return GenHeader{
sharedValidations: sharedValidations{
Required: true,
Maximum: hdr.Maximum,
ExclusiveMaximum: hdr.ExclusiveMaximum,
Minimum: hdr.Minimum,
ExclusiveMinimum: hdr.ExclusiveMinimum,
MaxLength: hdr.MaxLength,
MinLength: hdr.MinLength,
Pattern: hdr.Pattern,
MaxItems: hdr.MaxItems,
MinItems: hdr.MinItems,
UniqueItems: hdr.UniqueItems,
MultipleOf: hdr.MultipleOf,
Enum: hdr.Enum,
HasValidations: hasValidations,
HasSliceValidations: hasSliceValidations,
},
resolvedType: tpe,
Package: b.APIPackage,
ReceiverName: receiver,
Name: name,
Path: name,
Description: hdr.Description,
Default: hdr.Default,
Converter: stringConverters[tpe.GoType],
Formatter: stringFormatters[tpe.GoType],
}
}
func (b *codeGenOpBuilder) MakeParameterItem(receiver, paramName, indexVar, path, valueExpression, location string, resolver *typeResolver, items, parent *spec.Items) (GenItems, error) {
var res GenItems
res.resolvedType = simpleResolvedType(items.Type, items.Format, items.Items)
res.sharedValidations = sharedValidations{
Maximum: items.Maximum,
ExclusiveMaximum: items.ExclusiveMaximum,
Minimum: items.Minimum,
ExclusiveMinimum: items.ExclusiveMinimum,
MaxLength: items.MaxLength,
MinLength: items.MinLength,
Pattern: items.Pattern,
MaxItems: items.MaxItems,
MinItems: items.MinItems,
UniqueItems: items.UniqueItems,
MultipleOf: items.MultipleOf,
Enum: items.Enum,
}
res.Name = paramName
res.Path = path
res.Location = location
res.ValueExpression = valueExpression
res.CollectionFormat = items.CollectionFormat
res.Converter = stringConverters[res.GoType]
res.Formatter = stringFormatters[res.GoType]
if items.Items != nil {
pi, err := b.MakeParameterItem(receiver, paramName+" "+indexVar, indexVar+"[i]", "fmt.Sprintf(\"%s.%v\", "+path+", "+indexVar+")", valueExpression+"["+indexVar+"]", location, resolver, items.Items, items)
if err != nil {
return GenItems{}, err
}
res.Child = &pi
pi.Parent = &res
}
return res, nil
}
func (b *codeGenOpBuilder) MakeParameter(receiver string, resolver *typeResolver, param spec.Parameter) (GenParameter, error) {
var child *GenItems
res := GenParameter{
Name: param.Name,
ModelsPackage: b.ModelsPackage,
Path: fmt.Sprintf("%q", param.Name),
ValueExpression: fmt.Sprintf("%s.%s", receiver, swag.ToGoName(param.Name)),
IndexVar: "i",
BodyParam: nil,
Default: param.Default,
Enum: param.Enum,
Description: param.Description,
ReceiverName: receiver,
CollectionFormat: param.CollectionFormat,
Child: child,
Location: param.In,
AllowEmptyValue: (param.In == "query" || param.In == "formData") && param.AllowEmptyValue,
}
if param.In == "body" {
sc := schemaGenContext{
Path: res.Path,
Name: res.Name,
Receiver: res.ReceiverName,
ValueExpr: res.ReceiverName,
IndexVar: res.IndexVar,
Schema: *param.Schema,
Required: param.Required,
TypeResolver: resolver,
Named: false,
ExtraSchemas: make(map[string]GenSchema),
}
if err := sc.makeGenSchema(); err != nil {
return GenParameter{}, err
}
schema := sc.GenSchema
if schema.IsAnonymous {
schema.Name = swag.ToGoName(b.Operation.ID + " Body")
nm := schema.Name
schema.GoType = nm
schema.IsAnonymous = false
if len(schema.Properties) > 0 {
if b.ExtraSchemas == nil {
b.ExtraSchemas = make(map[string]GenSchema)
}
b.ExtraSchemas[nm] = schema
}
prevSchema := schema
schema = GenSchema{}
schema.IsAnonymous = false
schema.GoType = nm
schema.SwaggerType = nm
if len(prevSchema.Properties) == 0 {
schema.GoType = "interface{}"
}
schema.IsComplexObject = true
schema.IsInterface = len(schema.Properties) == 0
}
res.Schema = &schema
res.resolvedType = schema.resolvedType
res.sharedValidations = schema.sharedValidations
res.ZeroValue = schema.Zero()
} else {
res.resolvedType = simpleResolvedType(param.Type, param.Format, param.Items)
res.sharedValidations = sharedValidations{
Required: param.Required,
Maximum: param.Maximum,
ExclusiveMaximum: param.ExclusiveMaximum,
Minimum: param.Minimum,
ExclusiveMinimum: param.ExclusiveMinimum,
MaxLength: param.MaxLength,
MinLength: param.MinLength,
Pattern: param.Pattern,
MaxItems: param.MaxItems,
MinItems: param.MinItems,
UniqueItems: param.UniqueItems,
MultipleOf: param.MultipleOf,
Enum: param.Enum,
}
if param.Items != nil {
pi, err := b.MakeParameterItem(receiver, param.Name+" "+res.IndexVar, res.IndexVar+"i", "fmt.Sprintf(\"%s.%v\", "+res.Path+", "+res.IndexVar+")", res.ValueExpression+"["+res.IndexVar+"]", param.In, resolver, param.Items, nil)
if err != nil {
return GenParameter{}, err
}
res.Child = &pi
}
res.IsNullable = !param.Required && param.AllowEmptyValue
}
hasNumberValidation := param.Maximum != nil || param.Minimum != nil || param.MultipleOf != nil
hasStringValidation := param.MaxLength != nil || param.MinLength != nil || param.Pattern != ""
hasSliceValidations := param.MaxItems != nil || param.MinItems != nil || param.UniqueItems
hasValidations := hasNumberValidation || hasStringValidation || hasSliceValidations || len(param.Enum) > 0
res.Converter = stringConverters[res.GoType]
res.Formatter = stringFormatters[res.GoType]
res.HasValidations = hasValidations
res.HasSliceValidations = hasSliceValidations
return res, nil
}
func modelValidations(gs GenSchema) commonValidations {
return commonValidations{
propertyDescriptor: propertyDescriptor{
PropertyName: swag.ToGoName(gs.Name),
ParamName: gs.Name,
ValueExpression: gs.ValueExpression,
IndexVar: gs.IndexVar,
Path: gs.Path,
IsContainer: gs.IsArray,
IsPrimitive: gs.IsPrimitive,
IsCustomFormatter: gs.IsCustomFormatter,
IsMap: gs.IsMap,
},
sharedValidations: sharedValidations{
Required: gs.Required,
Maximum: gs.Maximum,
ExclusiveMaximum: gs.ExclusiveMaximum,
Minimum: gs.Minimum,
ExclusiveMinimum: gs.ExclusiveMinimum,
MaxLength: gs.MaxLength,
MinLength: gs.MinLength,
Pattern: gs.Pattern,
MaxItems: gs.MaxItems,
MinItems: gs.MinItems,
UniqueItems: gs.UniqueItems,
MultipleOf: gs.MultipleOf,
Enum: gs.Enum,
},
Type: gs.GoType,
Format: gs.SwaggerFormat,
//Default: model.Default,
}
}
func paramValidations(receiver string, param spec.Parameter) commonValidations {
accessor := swag.ToGoName(param.Name)
paramName := swag.ToJSONName(param.Name)
tpe := typeForParameter(param)
_, isPrimitive := primitives[tpe]
_, isCustomFormatter := customFormatters[tpe]
return commonValidations{
propertyDescriptor: propertyDescriptor{
PropertyName: accessor,
ParamName: paramName,
ValueExpression: fmt.Sprintf("%s.%s", receiver, accessor),
IndexVar: "i",
Path: "\"" + paramName + "\"",
IsContainer: param.Items != nil || tpe == "array",
IsPrimitive: isPrimitive,
IsCustomFormatter: isCustomFormatter,
IsMap: strings.HasPrefix(tpe, "map"),
},
sharedValidations: sharedValidations{
Required: param.Required,
Maximum: param.Maximum,
ExclusiveMaximum: param.ExclusiveMaximum,
Minimum: param.Minimum,
ExclusiveMinimum: param.ExclusiveMinimum,
MaxLength: param.MaxLength,
MinLength: param.MinLength,
Pattern: param.Pattern,
MaxItems: param.MaxItems,
MinItems: param.MinItems,
UniqueItems: param.UniqueItems,
MultipleOf: param.MultipleOf,
Enum: param.Enum,
},
Type: tpe,
Format: param.Format,
Items: param.Items,
Default: param.Default,
}
}
type sharedParam struct {
genValidations
propertyDescriptor
}
func paramItemValidations(path, paramName, accessor, indexVar, valueExpression string, items spec.Items) commonValidations {
tpe := resolveSimpleType(items.Type, items.Format, items.Items)
_, isPrimitive := primitives[tpe]
_, isCustomFormatter := customFormatters[tpe]
shv := sharedValidations{
Maximum: items.Maximum,
ExclusiveMaximum: items.ExclusiveMaximum,
Minimum: items.Minimum,
ExclusiveMinimum: items.ExclusiveMinimum,
MaxLength: items.MaxLength,
MinLength: items.MinLength,
Pattern: items.Pattern,
MaxItems: items.MaxItems,
MinItems: items.MinItems,
UniqueItems: items.UniqueItems,
MultipleOf: items.MultipleOf,
Enum: items.Enum,
}
return commonValidations{
propertyDescriptor: propertyDescriptor{
PropertyName: accessor,
ParamName: paramName,
ValueExpression: valueExpression,
IndexVar: indexVar,
Path: path,
IsContainer: items.Items != nil || tpe == "array",
IsPrimitive: isPrimitive,
IsCustomFormatter: isCustomFormatter,
IsMap: strings.HasPrefix(tpe, "map"),
},
sharedValidations: shv,
Type: tpe,
Format: items.Format,
Items: items.Items,
Default: items.Default,
}
}
func makeGenValidations(s commonValidations) sharedParam {
hasValidations := s.Required
var defVal string
if s.Default != nil {
hasValidations = false
defVal = fmt.Sprintf("%#v", s.Default)
}
var format string
if s.IsCustomFormatter {
hasValidations = true
format = s.Format
}
var maxLength int64
if s.MaxLength != nil {
hasValidations = true
maxLength = *s.MaxLength
}
var minLength int64
if s.MinLength != nil {
hasValidations = true
minLength = *s.MinLength
}
var minimum float64
if s.Minimum != nil {
hasValidations = true
minimum = *s.Minimum
}
var maximum float64
if s.Maximum != nil {
hasValidations = true
maximum = *s.Maximum
}
var multipleOf float64
if s.MultipleOf != nil {
hasValidations = true
multipleOf = *s.MultipleOf
}
var needsSize bool
hasSliceValidations := s.UniqueItems
var maxItems int64
if s.MaxItems != nil {
hasSliceValidations = true
needsSize = true
maxItems = *s.MaxItems
}
var minItems int64
if s.MinItems != nil {
hasSliceValidations = true
needsSize = true
minItems = *s.MinItems
}
var enum string
if len(s.Enum) > 0 {
hasValidations = true
enum = fmt.Sprintf("%#v", s.Enum)
}
return sharedParam{
propertyDescriptor: s.propertyDescriptor,
genValidations: genValidations{
Type: s.Type,
Required: s.Required,
DefaultValue: defVal,
MaxLength: maxLength,
MinLength: minLength,
Pattern: s.Pattern,
MultipleOf: multipleOf,
Minimum: minimum,
Maximum: maximum,
ExclusiveMinimum: s.ExclusiveMinimum,
ExclusiveMaximum: s.ExclusiveMaximum,
Enum: enum,
HasValidations: hasValidations,
Format: format,
MinItems: minItems,
MaxItems: maxItems,
UniqueItems: s.UniqueItems,
HasSliceValidations: hasSliceValidations,
NeedsSize: needsSize,
},
}
}
// GenResponse represents a response object for code generation
type GenResponse struct {
Package string
ModelsPackage string
ReceiverName string
Name string
Description string
IsSuccess bool
Code int
Method string
Path string
Headers GenHeaders
Schema *GenSchema
Imports map[string]string
DefaultImports []string
}
// GenHeader represents a header on a response for code generation
type GenHeader struct {
resolvedType
sharedValidations
Package string
ReceiverName string
Name string
Path string
Title string
Description string
Default interface{}
Converter string
Formatter string
}
// GenHeaders is a sorted collection of headers for codegen
type GenHeaders []GenHeader
func (g GenHeaders) Len() int { return len(g) }
func (g GenHeaders) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
func (g GenHeaders) Less(i, j int) bool { return g[i].Name < g[j].Name }
// GenParameter is used to represent
// a parameter or a header for code generation.
type GenParameter struct {
resolvedType
sharedValidations
Name string
ModelsPackage string
Path string
ValueExpression string
IndexVar string
ReceiverName string
Location string
Title string
Description string
Converter string
Formatter string
Schema *GenSchema
CollectionFormat string
Child *GenItems
Parent *GenItems
BodyParam *GenParameter
Default interface{}
Enum []interface{}
ZeroValue string
AllowEmptyValue bool
}
// IsQueryParam returns true when this parameter is a query param
func (g *GenParameter) IsQueryParam() bool {
return g.Location == "query"
}
// IsPathParam returns true when this parameter is a path param
func (g *GenParameter) IsPathParam() bool {
return g.Location == "path"
}
// IsFormParam returns true when this parameter is a form param
func (g *GenParameter) IsFormParam() bool {
return g.Location == "formData"
}
// IsHeaderParam returns true when this parameter is a header param
func (g *GenParameter) IsHeaderParam() bool {
return g.Location == "header"
}
// IsBodyParam returns true when this parameter is a body param
func (g *GenParameter) IsBodyParam() bool {
return g.Location == "body"
}
// IsFileParam returns true when this parameter is a file param
func (g *GenParameter) IsFileParam() bool {
return g.SwaggerType == "file"
}
// GenParameters represents a sorted parameter collection
type GenParameters []GenParameter
func (g GenParameters) Len() int { return len(g) }
func (g GenParameters) Less(i, j int) bool { return g[i].Name < g[j].Name }
func (g GenParameters) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
// GenItems represents the collection items for a collection parameter
type GenItems struct {
sharedValidations
resolvedType
Name string
Path string
ValueExpression string
CollectionFormat string
Child *GenItems
Parent *GenItems
Converter string
Formatter string
Location string
}
// GenOperationGroup represents a named (tagged) group of operations
type GenOperationGroup struct {
Name string
Operations GenOperations
Summary string
Description string
Imports map[string]string
DefaultImports []string
RootPackage string
}
// GenOperationGroups is a sorted collection of operation groups
type GenOperationGroups []GenOperationGroup
func (g GenOperationGroups) Len() int { return len(g) }
func (g GenOperationGroups) Swap(i, j int) { g[i], g[j] = g[j], g[i] }