...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package validate
16
17 import (
18 "reflect"
19
20 "github.com/go-openapi/spec"
21 "github.com/go-openapi/strfmt"
22 )
23
24 type formatValidator struct {
25 Path string
26 In string
27 Format string
28 KnownFormats strfmt.Registry
29 Options *SchemaValidatorOptions
30 }
31
32 func newFormatValidator(path, in, format string, formats strfmt.Registry, opts *SchemaValidatorOptions) *formatValidator {
33 if opts == nil {
34 opts = new(SchemaValidatorOptions)
35 }
36
37 var f *formatValidator
38 if opts.recycleValidators {
39 f = pools.poolOfFormatValidators.BorrowValidator()
40 } else {
41 f = new(formatValidator)
42 }
43
44 f.Path = path
45 f.In = in
46 f.Format = format
47 f.KnownFormats = formats
48 f.Options = opts
49
50 return f
51 }
52
53 func (f *formatValidator) SetPath(path string) {
54 f.Path = path
55 }
56
57 func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool {
58 if source == nil || f.KnownFormats == nil {
59 return false
60 }
61
62 switch source := source.(type) {
63 case *spec.Items:
64 return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
65 case *spec.Parameter:
66 return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
67 case *spec.Schema:
68 return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
69 case *spec.Header:
70 return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
71 default:
72 return false
73 }
74 }
75
76 func (f *formatValidator) Validate(val interface{}) *Result {
77 if f.Options.recycleValidators {
78 defer func() {
79 f.redeem()
80 }()
81 }
82
83 var result *Result
84 if f.Options.recycleResult {
85 result = pools.poolOfResults.BorrowResult()
86 } else {
87 result = new(Result)
88 }
89
90 if err := FormatOf(f.Path, f.In, f.Format, val.(string), f.KnownFormats); err != nil {
91 result.AddErrors(err)
92 }
93
94 return result
95 }
96
97 func (f *formatValidator) redeem() {
98 pools.poolOfFormatValidators.RedeemValidator(f)
99 }
100
View as plain text