forked from getkin/kin-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
1595 lines (1438 loc) · 38.2 KB
/
schema.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 openapi3
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"regexp"
"strconv"
"strings"
"unicode/utf16"
"github.com/getkin/kin-openapi/jsoninfo"
"github.com/go-openapi/jsonpointer"
)
var (
// SchemaErrorDetailsDisabled disables printing of details about schema errors.
SchemaErrorDetailsDisabled = false
//SchemaFormatValidationDisabled disables validation of schema type formats.
SchemaFormatValidationDisabled = false
errSchema = errors.New("input does not match the schema")
// ErrOneOfConflict is the SchemaError Origin when data matches more than one oneOf schema
ErrOneOfConflict = errors.New("input matches more than one oneOf schemas")
// ErrSchemaInputNaN may be returned when validating a number
ErrSchemaInputNaN = errors.New("floating point NaN is not allowed")
// ErrSchemaInputInf may be returned when validating a number
ErrSchemaInputInf = errors.New("floating point Inf is not allowed")
)
// Float64Ptr is a helper for defining OpenAPI schemas.
func Float64Ptr(value float64) *float64 {
return &value
}
// BoolPtr is a helper for defining OpenAPI schemas.
func BoolPtr(value bool) *bool {
return &value
}
// Int64Ptr is a helper for defining OpenAPI schemas.
func Int64Ptr(value int64) *int64 {
return &value
}
// Uint64Ptr is a helper for defining OpenAPI schemas.
func Uint64Ptr(value uint64) *uint64 {
return &value
}
type Schemas map[string]*SchemaRef
var _ jsonpointer.JSONPointable = (*Schemas)(nil)
func (s Schemas) JSONLookup(token string) (interface{}, error) {
ref, ok := s[token]
if ref == nil || ok == false {
return nil, fmt.Errorf("object has no field %q", token)
}
if ref.Ref != "" {
return &Ref{Ref: ref.Ref}, nil
}
return ref.Value, nil
}
type SchemaRefs []*SchemaRef
var _ jsonpointer.JSONPointable = (*SchemaRefs)(nil)
func (s SchemaRefs) JSONLookup(token string) (interface{}, error) {
i, err := strconv.ParseUint(token, 10, 64)
if err != nil {
return nil, err
}
if i >= uint64(len(s)) {
return nil, fmt.Errorf("index out of range: %d", i)
}
ref := s[i]
if ref == nil || ref.Ref != "" {
return &Ref{Ref: ref.Ref}, nil
}
return ref.Value, nil
}
// Schema is specified by OpenAPI/Swagger 3.0 standard.
type Schema struct {
ExtensionProps
OneOf SchemaRefs `json:"oneOf,omitempty" yaml:"oneOf,omitempty"`
AnyOf SchemaRefs `json:"anyOf,omitempty" yaml:"anyOf,omitempty"`
AllOf SchemaRefs `json:"allOf,omitempty" yaml:"allOf,omitempty"`
Not *SchemaRef `json:"not,omitempty" yaml:"not,omitempty"`
Type string `json:"type,omitempty" yaml:"type,omitempty"`
Title string `json:"title,omitempty" yaml:"title,omitempty"`
Format string `json:"format,omitempty" yaml:"format,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Enum []interface{} `json:"enum,omitempty" yaml:"enum,omitempty"`
Default interface{} `json:"default,omitempty" yaml:"default,omitempty"`
Example interface{} `json:"example,omitempty" yaml:"example,omitempty"`
ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
// Object-related, here for struct compactness
AdditionalPropertiesAllowed *bool `json:"-" multijson:"additionalProperties,omitempty" yaml:"-"`
// Array-related, here for struct compactness
UniqueItems bool `json:"uniqueItems,omitempty" yaml:"uniqueItems,omitempty"`
// Number-related, here for struct compactness
ExclusiveMin bool `json:"exclusiveMinimum,omitempty" yaml:"exclusiveMinimum,omitempty"`
ExclusiveMax bool `json:"exclusiveMaximum,omitempty" yaml:"exclusiveMaximum,omitempty"`
// Properties
Nullable bool `json:"nullable,omitempty" yaml:"nullable,omitempty"`
ReadOnly bool `json:"readOnly,omitempty" yaml:"readOnly,omitempty"`
WriteOnly bool `json:"writeOnly,omitempty" yaml:"writeOnly,omitempty"`
AllowEmptyValue bool `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"`
XML interface{} `json:"xml,omitempty" yaml:"xml,omitempty"`
Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
// Number
Min *float64 `json:"minimum,omitempty" yaml:"minimum,omitempty"`
Max *float64 `json:"maximum,omitempty" yaml:"maximum,omitempty"`
MultipleOf *float64 `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"`
// String
MinLength uint64 `json:"minLength,omitempty" yaml:"minLength,omitempty"`
MaxLength *uint64 `json:"maxLength,omitempty" yaml:"maxLength,omitempty"`
Pattern string `json:"pattern,omitempty" yaml:"pattern,omitempty"`
compiledPattern *regexp.Regexp
// Array
MinItems uint64 `json:"minItems,omitempty" yaml:"minItems,omitempty"`
MaxItems *uint64 `json:"maxItems,omitempty" yaml:"maxItems,omitempty"`
Items *SchemaRef `json:"items,omitempty" yaml:"items,omitempty"`
// Object
Required []string `json:"required,omitempty" yaml:"required,omitempty"`
Properties Schemas `json:"properties,omitempty" yaml:"properties,omitempty"`
MinProps uint64 `json:"minProperties,omitempty" yaml:"minProperties,omitempty"`
MaxProps *uint64 `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"`
AdditionalProperties *SchemaRef `json:"-" multijson:"additionalProperties,omitempty" yaml:"-"`
Discriminator *Discriminator `json:"discriminator,omitempty" yaml:"discriminator,omitempty"`
}
var _ jsonpointer.JSONPointable = (*Schema)(nil)
func NewSchema() *Schema {
return &Schema{}
}
func (schema *Schema) MarshalJSON() ([]byte, error) {
return jsoninfo.MarshalStrictStruct(schema)
}
func (schema *Schema) UnmarshalJSON(data []byte) error {
return jsoninfo.UnmarshalStrictStruct(data, schema)
}
func (schema Schema) JSONLookup(token string) (interface{}, error) {
switch token {
case "additionalProperties":
if schema.AdditionalProperties != nil {
if schema.AdditionalProperties.Ref != "" {
return &Ref{Ref: schema.AdditionalProperties.Ref}, nil
}
return schema.AdditionalProperties.Value, nil
}
case "not":
if schema.Not != nil {
if schema.Not.Ref != "" {
return &Ref{Ref: schema.Not.Ref}, nil
}
return schema.Not.Value, nil
}
case "items":
if schema.Items != nil {
if schema.Items.Ref != "" {
return &Ref{Ref: schema.Items.Ref}, nil
}
return schema.Items.Value, nil
}
case "oneOf":
return schema.OneOf, nil
case "anyOf":
return schema.AnyOf, nil
case "allOf":
return schema.AllOf, nil
case "type":
return schema.Type, nil
case "title":
return schema.Title, nil
case "format":
return schema.Format, nil
case "description":
return schema.Description, nil
case "enum":
return schema.Enum, nil
case "default":
return schema.Default, nil
case "example":
return schema.Example, nil
case "externalDocs":
return schema.ExternalDocs, nil
case "additionalPropertiesAllowed":
return schema.AdditionalPropertiesAllowed, nil
case "uniqueItems":
return schema.UniqueItems, nil
case "exclusiveMin":
return schema.ExclusiveMin, nil
case "exclusiveMax":
return schema.ExclusiveMax, nil
case "nullable":
return schema.Nullable, nil
case "readOnly":
return schema.ReadOnly, nil
case "writeOnly":
return schema.WriteOnly, nil
case "allowEmptyValue":
return schema.AllowEmptyValue, nil
case "xml":
return schema.XML, nil
case "deprecated":
return schema.Deprecated, nil
case "min":
return schema.Min, nil
case "max":
return schema.Max, nil
case "multipleOf":
return schema.MultipleOf, nil
case "minLength":
return schema.MinLength, nil
case "maxLength":
return schema.MaxLength, nil
case "pattern":
return schema.Pattern, nil
case "minItems":
return schema.MinItems, nil
case "maxItems":
return schema.MaxItems, nil
case "required":
return schema.Required, nil
case "properties":
return schema.Properties, nil
case "minProps":
return schema.MinProps, nil
case "maxProps":
return schema.MaxProps, nil
case "discriminator":
return schema.Discriminator, nil
}
v, _, err := jsonpointer.GetForToken(schema.ExtensionProps, token)
return v, err
}
func (schema *Schema) NewRef() *SchemaRef {
return &SchemaRef{
Value: schema,
}
}
func NewOneOfSchema(schemas ...*Schema) *Schema {
refs := make([]*SchemaRef, 0, len(schemas))
for _, schema := range schemas {
refs = append(refs, &SchemaRef{Value: schema})
}
return &Schema{
OneOf: refs,
}
}
func NewAnyOfSchema(schemas ...*Schema) *Schema {
refs := make([]*SchemaRef, 0, len(schemas))
for _, schema := range schemas {
refs = append(refs, &SchemaRef{Value: schema})
}
return &Schema{
AnyOf: refs,
}
}
func NewAllOfSchema(schemas ...*Schema) *Schema {
refs := make([]*SchemaRef, 0, len(schemas))
for _, schema := range schemas {
refs = append(refs, &SchemaRef{Value: schema})
}
return &Schema{
AllOf: refs,
}
}
func NewBoolSchema() *Schema {
return &Schema{
Type: "boolean",
}
}
func NewFloat64Schema() *Schema {
return &Schema{
Type: "number",
}
}
func NewIntegerSchema() *Schema {
return &Schema{
Type: "integer",
}
}
func NewInt32Schema() *Schema {
return &Schema{
Type: "integer",
Format: "int32",
}
}
func NewInt64Schema() *Schema {
return &Schema{
Type: "integer",
Format: "int64",
}
}
func NewStringSchema() *Schema {
return &Schema{
Type: "string",
}
}
func NewDateTimeSchema() *Schema {
return &Schema{
Type: "string",
Format: "date-time",
}
}
func NewUUIDSchema() *Schema {
return &Schema{
Type: "string",
Format: "uuid",
}
}
func NewBytesSchema() *Schema {
return &Schema{
Type: "string",
Format: "byte",
}
}
func NewArraySchema() *Schema {
return &Schema{
Type: "array",
}
}
func NewObjectSchema() *Schema {
return &Schema{
Type: "object",
Properties: make(map[string]*SchemaRef),
}
}
func (schema *Schema) WithNullable() *Schema {
schema.Nullable = true
return schema
}
func (schema *Schema) WithMin(value float64) *Schema {
schema.Min = &value
return schema
}
func (schema *Schema) WithMax(value float64) *Schema {
schema.Max = &value
return schema
}
func (schema *Schema) WithExclusiveMin(value bool) *Schema {
schema.ExclusiveMin = value
return schema
}
func (schema *Schema) WithExclusiveMax(value bool) *Schema {
schema.ExclusiveMax = value
return schema
}
func (schema *Schema) WithEnum(values ...interface{}) *Schema {
schema.Enum = values
return schema
}
func (schema *Schema) WithDefault(defaultValue interface{}) *Schema {
schema.Default = defaultValue
return schema
}
func (schema *Schema) WithFormat(value string) *Schema {
schema.Format = value
return schema
}
func (schema *Schema) WithLength(i int64) *Schema {
n := uint64(i)
schema.MinLength = n
schema.MaxLength = &n
return schema
}
func (schema *Schema) WithMinLength(i int64) *Schema {
n := uint64(i)
schema.MinLength = n
return schema
}
func (schema *Schema) WithMaxLength(i int64) *Schema {
n := uint64(i)
schema.MaxLength = &n
return schema
}
func (schema *Schema) WithLengthDecodedBase64(i int64) *Schema {
n := uint64(i)
v := (n*8 + 5) / 6
schema.MinLength = v
schema.MaxLength = &v
return schema
}
func (schema *Schema) WithMinLengthDecodedBase64(i int64) *Schema {
n := uint64(i)
schema.MinLength = (n*8 + 5) / 6
return schema
}
func (schema *Schema) WithMaxLengthDecodedBase64(i int64) *Schema {
n := uint64(i)
schema.MinLength = (n*8 + 5) / 6
return schema
}
func (schema *Schema) WithPattern(pattern string) *Schema {
schema.Pattern = pattern
schema.compiledPattern = nil
return schema
}
func (schema *Schema) WithItems(value *Schema) *Schema {
schema.Items = &SchemaRef{
Value: value,
}
return schema
}
func (schema *Schema) WithMinItems(i int64) *Schema {
n := uint64(i)
schema.MinItems = n
return schema
}
func (schema *Schema) WithMaxItems(i int64) *Schema {
n := uint64(i)
schema.MaxItems = &n
return schema
}
func (schema *Schema) WithUniqueItems(unique bool) *Schema {
schema.UniqueItems = unique
return schema
}
func (schema *Schema) WithProperty(name string, propertySchema *Schema) *Schema {
return schema.WithPropertyRef(name, &SchemaRef{
Value: propertySchema,
})
}
func (schema *Schema) WithPropertyRef(name string, ref *SchemaRef) *Schema {
properties := schema.Properties
if properties == nil {
properties = make(map[string]*SchemaRef)
schema.Properties = properties
}
properties[name] = ref
return schema
}
func (schema *Schema) WithProperties(properties map[string]*Schema) *Schema {
result := make(map[string]*SchemaRef, len(properties))
for k, v := range properties {
result[k] = &SchemaRef{
Value: v,
}
}
schema.Properties = result
return schema
}
func (schema *Schema) WithMinProperties(i int64) *Schema {
n := uint64(i)
schema.MinProps = n
return schema
}
func (schema *Schema) WithMaxProperties(i int64) *Schema {
n := uint64(i)
schema.MaxProps = &n
return schema
}
func (schema *Schema) WithAnyAdditionalProperties() *Schema {
schema.AdditionalProperties = nil
t := true
schema.AdditionalPropertiesAllowed = &t
return schema
}
func (schema *Schema) WithAdditionalProperties(v *Schema) *Schema {
if v == nil {
schema.AdditionalProperties = nil
} else {
schema.AdditionalProperties = &SchemaRef{
Value: v,
}
}
return schema
}
func (schema *Schema) IsEmpty() bool {
if schema.Type != "" || schema.Format != "" || len(schema.Enum) != 0 ||
schema.UniqueItems || schema.ExclusiveMin || schema.ExclusiveMax ||
schema.Nullable || schema.ReadOnly || schema.WriteOnly || schema.AllowEmptyValue ||
schema.Min != nil || schema.Max != nil || schema.MultipleOf != nil ||
schema.MinLength != 0 || schema.MaxLength != nil || schema.Pattern != "" ||
schema.MinItems != 0 || schema.MaxItems != nil ||
len(schema.Required) != 0 ||
schema.MinProps != 0 || schema.MaxProps != nil {
return false
}
if n := schema.Not; n != nil && !n.Value.IsEmpty() {
return false
}
if ap := schema.AdditionalProperties; ap != nil && !ap.Value.IsEmpty() {
return false
}
if apa := schema.AdditionalPropertiesAllowed; apa != nil && !*apa {
return false
}
if items := schema.Items; items != nil && !items.Value.IsEmpty() {
return false
}
for _, s := range schema.Properties {
if !s.Value.IsEmpty() {
return false
}
}
for _, s := range schema.OneOf {
if !s.Value.IsEmpty() {
return false
}
}
for _, s := range schema.AnyOf {
if !s.Value.IsEmpty() {
return false
}
}
for _, s := range schema.AllOf {
if !s.Value.IsEmpty() {
return false
}
}
return true
}
func (schema *Schema) Validate(c context.Context) error {
return schema.validate(c, []*Schema{})
}
func (schema *Schema) validate(c context.Context, stack []*Schema) (err error) {
for _, existing := range stack {
if existing == schema {
return
}
}
stack = append(stack, schema)
if schema.ReadOnly && schema.WriteOnly {
return errors.New("a property MUST NOT be marked as both readOnly and writeOnly being true")
}
for _, item := range schema.OneOf {
v := item.Value
if v == nil {
return foundUnresolvedRef(item.Ref)
}
if err = v.validate(c, stack); err == nil {
return
}
}
for _, item := range schema.AnyOf {
v := item.Value
if v == nil {
return foundUnresolvedRef(item.Ref)
}
if err = v.validate(c, stack); err != nil {
return
}
}
for _, item := range schema.AllOf {
v := item.Value
if v == nil {
return foundUnresolvedRef(item.Ref)
}
if err = v.validate(c, stack); err != nil {
return
}
}
if ref := schema.Not; ref != nil {
v := ref.Value
if v == nil {
return foundUnresolvedRef(ref.Ref)
}
if err = v.validate(c, stack); err != nil {
return
}
}
schemaType := schema.Type
switch schemaType {
case "":
case "boolean":
case "number":
if format := schema.Format; len(format) > 0 {
switch format {
case "float", "double":
default:
if !SchemaFormatValidationDisabled {
return unsupportedFormat(format)
}
}
}
case "integer":
if format := schema.Format; len(format) > 0 {
switch format {
case "int32", "int64":
default:
if !SchemaFormatValidationDisabled {
return unsupportedFormat(format)
}
}
}
case "string":
if format := schema.Format; len(format) > 0 {
switch format {
// Supported by OpenAPIv3.0.1:
case "byte", "binary", "date", "date-time", "password":
// In JSON Draft-07 (not validated yet though):
case "regex":
case "time", "email", "idn-email":
case "hostname", "idn-hostname", "ipv4", "ipv6":
case "uri", "uri-reference", "iri", "iri-reference", "uri-template":
case "json-pointer", "relative-json-pointer":
default:
// Try to check for custom defined formats
if _, ok := SchemaStringFormats[format]; !ok && !SchemaFormatValidationDisabled {
return unsupportedFormat(format)
}
}
}
case "array":
if schema.Items == nil {
return errors.New("when schema type is 'array', schema 'items' must be non-null")
}
case "object":
default:
return fmt.Errorf("unsupported 'type' value %q", schemaType)
}
if ref := schema.Items; ref != nil {
v := ref.Value
if v == nil {
return foundUnresolvedRef(ref.Ref)
}
if err = v.validate(c, stack); err != nil {
return
}
}
for _, ref := range schema.Properties {
v := ref.Value
if v == nil {
return foundUnresolvedRef(ref.Ref)
}
if err = v.validate(c, stack); err != nil {
return
}
}
if ref := schema.AdditionalProperties; ref != nil {
v := ref.Value
if v == nil {
return foundUnresolvedRef(ref.Ref)
}
if err = v.validate(c, stack); err != nil {
return
}
}
return
}
func (schema *Schema) IsMatching(value interface{}) bool {
settings := newSchemaValidationSettings(FailFast())
return schema.visitJSON(settings, value) == nil
}
func (schema *Schema) IsMatchingJSONBoolean(value bool) bool {
settings := newSchemaValidationSettings(FailFast())
return schema.visitJSON(settings, value) == nil
}
func (schema *Schema) IsMatchingJSONNumber(value float64) bool {
settings := newSchemaValidationSettings(FailFast())
return schema.visitJSON(settings, value) == nil
}
func (schema *Schema) IsMatchingJSONString(value string) bool {
settings := newSchemaValidationSettings(FailFast())
return schema.visitJSON(settings, value) == nil
}
func (schema *Schema) IsMatchingJSONArray(value []interface{}) bool {
settings := newSchemaValidationSettings(FailFast())
return schema.visitJSON(settings, value) == nil
}
func (schema *Schema) IsMatchingJSONObject(value map[string]interface{}) bool {
settings := newSchemaValidationSettings(FailFast())
return schema.visitJSON(settings, value) == nil
}
func (schema *Schema) VisitJSON(value interface{}, opts ...SchemaValidationOption) error {
settings := newSchemaValidationSettings(opts...)
return schema.visitJSON(settings, value)
}
func (schema *Schema) visitJSON(settings *schemaValidationSettings, value interface{}) (err error) {
switch value := value.(type) {
case nil:
return schema.visitJSONNull(settings)
case float64:
if math.IsNaN(value) {
return ErrSchemaInputNaN
}
if math.IsInf(value, 0) {
return ErrSchemaInputInf
}
}
if schema.IsEmpty() {
return
}
if err = schema.visitSetOperations(settings, value); err != nil {
return
}
switch value := value.(type) {
case nil:
return schema.visitJSONNull(settings)
case bool:
return schema.visitJSONBoolean(settings, value)
case float64:
return schema.visitJSONNumber(settings, value)
case string:
return schema.visitJSONString(settings, value)
case []interface{}:
return schema.visitJSONArray(settings, value)
case map[string]interface{}:
return schema.visitJSONObject(settings, value)
default:
return &SchemaError{
Value: value,
Schema: schema,
SchemaField: "type",
Reason: fmt.Sprintf("unhandled value of type %T", value),
}
}
}
func (schema *Schema) visitSetOperations(settings *schemaValidationSettings, value interface{}) (err error) {
if enum := schema.Enum; len(enum) != 0 {
for _, v := range enum {
if value == v {
return
}
}
if settings.failfast {
return errSchema
}
return &SchemaError{
Value: value,
Schema: schema,
SchemaField: "enum",
Reason: "value is not one of the allowed values",
}
}
if ref := schema.Not; ref != nil {
v := ref.Value
if v == nil {
return foundUnresolvedRef(ref.Ref)
}
var oldfailfast bool
oldfailfast, settings.failfast = settings.failfast, true
err := v.visitJSON(settings, value)
settings.failfast = oldfailfast
if err == nil {
if settings.failfast {
return errSchema
}
return &SchemaError{
Value: value,
Schema: schema,
SchemaField: "not",
}
}
}
if v := schema.OneOf; len(v) > 0 {
if schema.Discriminator != nil {
/* Find mapped object by ref */
if valuemap, okcheck := value.(map[string]interface{}); okcheck {
pn := schema.Discriminator.PropertyName
if discriminatorVal, okcheck := valuemap[pn]; okcheck {
if len(schema.Discriminator.Mapping) > 0 {
if mapref, okcheck := schema.Discriminator.Mapping[discriminatorVal.(string)]; okcheck {
for _, oneof := range v {
if oneof.Ref == mapref {
return oneof.Value.visitJSON(settings, value)
}
}
}
} else {
/* Assume implicit mapping on objectType as stated in Mapping Type Names section:
``It is implied, that the property to which discriminator refers, contains the
name of the target schema. In the example above, the objectType property should
contain either simpleObject, or complexObject string.''*/
for _, v := range schema.OneOf {
if strings.HasSuffix(v.Ref, discriminatorVal.(string)) {
return v.Value.visitJSON(settings, value)
}
}
}
}
}
}
ok := 0
for _, item := range v {
v := item.Value
if v == nil {
return foundUnresolvedRef(item.Ref)
}
var oldfailfast bool
oldfailfast, settings.failfast = settings.failfast, true
err := v.visitJSON(settings, value)
settings.failfast = oldfailfast
if err == nil {
ok++
}
}
if ok != 1 {
if settings.failfast {
return errSchema
}
e := &SchemaError{
Value: value,
Schema: schema,
SchemaField: "oneOf",
}
if ok > 1 {
e.Origin = ErrOneOfConflict
}
return e
}
}
if v := schema.AnyOf; len(v) > 0 {
ok := false
for _, item := range v {
v := item.Value
if v == nil {
return foundUnresolvedRef(item.Ref)
}
var oldfailfast bool
oldfailfast, settings.failfast = settings.failfast, true
err := v.visitJSON(settings, value)
settings.failfast = oldfailfast
if err == nil {
ok = true
break
}
}
if !ok {
if settings.failfast {
return errSchema
}
return &SchemaError{
Value: value,
Schema: schema,
SchemaField: "anyOf",
}
}
}
for _, item := range schema.AllOf {
v := item.Value
if v == nil {
return foundUnresolvedRef(item.Ref)
}
var oldfailfast bool
oldfailfast, settings.failfast = settings.failfast, false
err := v.visitJSON(settings, value)
settings.failfast = oldfailfast
if err != nil {
if settings.failfast {
return errSchema
}
return &SchemaError{
Value: value,
Schema: schema,
SchemaField: "allOf",
Origin: err,
}
}
}
return
}
func (schema *Schema) visitJSONNull(settings *schemaValidationSettings) (err error) {
if schema.Nullable {
return
}
if settings.failfast {
return errSchema
}
return &SchemaError{
Value: nil,
Schema: schema,
SchemaField: "nullable",
Reason: "Value is not nullable",
}
}
func (schema *Schema) VisitJSONBoolean(value bool) error {
settings := newSchemaValidationSettings()
return schema.visitJSONBoolean(settings, value)
}
func (schema *Schema) visitJSONBoolean(settings *schemaValidationSettings, value bool) (err error) {
if schemaType := schema.Type; schemaType != "" && schemaType != "boolean" {
return schema.expectedType(settings, "boolean")
}
return
}
func (schema *Schema) VisitJSONNumber(value float64) error {
settings := newSchemaValidationSettings()
return schema.visitJSONNumber(settings, value)
}
func (schema *Schema) visitJSONNumber(settings *schemaValidationSettings, value float64) error {
var me MultiError
schemaType := schema.Type
if schemaType == "integer" {
if bigFloat := big.NewFloat(value); !bigFloat.IsInt() {
if settings.failfast {
return errSchema
}
err := &SchemaError{
Value: value,
Schema: schema,
SchemaField: "type",
Reason: "Value must be an integer",
}
if !settings.multiError {
return err
}