-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstraint.go
More file actions
205 lines (184 loc) · 4.97 KB
/
constraint.go
File metadata and controls
205 lines (184 loc) · 4.97 KB
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
package api
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
)
// validateConstraints checks all constraint tags on the struct fields and
// returns a ValidationErrors slice containing every violation, or nil if
// the input is valid. The caller is responsible for routing the result
// through the router's ValidationErrorBuilder.
func validateConstraints(v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return nil
}
var errs []ValidationError
collectConstraintErrors(rv, "", &errs)
if len(errs) > 0 {
return ValidationErrors(errs)
}
return nil
}
func collectConstraintErrors(rv reflect.Value, prefix string, errs *[]ValidationError) {
t := rv.Type()
for i := range t.NumField() {
f := t.Field(i)
if !f.IsExported() {
continue
}
fv := rv.Field(i)
// Determine field path.
name := jsonFieldName(f)
if name == "-" {
continue
}
path := name
if prefix != "" {
path = prefix + "." + name
}
// If this is the Body field, recurse into it.
if f.Name == "Body" && f.Type.Kind() == reflect.Struct {
collectConstraintErrors(fv, "body", errs)
continue
}
// Skip RawRequest.
if f.Type == reflect.TypeFor[RawRequest]() {
continue
}
// Skip FileUpload — it's a multipart file, not a scalar.
if f.Type == reflect.TypeFor[FileUpload]() {
continue
}
checkFieldConstraints(f, fv, path, errs)
// Recurse into nested structs.
if fv.Kind() == reflect.Struct && f.Type != reflect.TypeFor[RawRequest]() && !isParamField(f) {
collectConstraintErrors(fv, path, errs)
}
}
}
func checkFieldConstraints(f reflect.StructField, fv reflect.Value, path string, errs *[]ValidationError) {
// minLength / maxLength — strings.
if fv.Kind() == reflect.String {
val := fv.String()
if tag := f.Tag.Get("minLength"); tag != "" {
if n, err := strconv.Atoi(tag); err == nil && len(val) < n {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must be at least %d characters", n),
Value: val,
})
}
}
if tag := f.Tag.Get("maxLength"); tag != "" {
if n, err := strconv.Atoi(tag); err == nil && len(val) > n {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must be at most %d characters", n),
Value: val,
})
}
}
if tag := f.Tag.Get("pattern"); tag != "" {
if matched, err := regexp.MatchString(tag, val); err == nil && !matched {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must match pattern %s", tag),
Value: val,
})
}
}
}
// minimum / maximum — numeric types.
if isNumericKind(fv.Kind()) {
floatVal := toFloat64(fv)
if tag := f.Tag.Get("minimum"); tag != "" {
if lower, err := strconv.ParseFloat(tag, 64); err == nil && floatVal < lower {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must be at least %s", tag),
Value: floatVal,
})
}
}
if tag := f.Tag.Get("maximum"); tag != "" {
if upper, err := strconv.ParseFloat(tag, 64); err == nil && floatVal > upper {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must be at most %s", tag),
Value: floatVal,
})
}
}
}
// enum — strings.
if fv.Kind() == reflect.String {
if tag := f.Tag.Get("enum"); tag != "" {
val := fv.String()
allowed := strings.Split(tag, ",")
found := false
for _, a := range allowed {
if a == val {
found = true
break
}
}
if !found {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must be one of [%s]", tag),
Value: val,
})
}
}
}
// minItems / maxItems — slices.
if fv.Kind() == reflect.Slice {
length := fv.Len()
if tag := f.Tag.Get("minItems"); tag != "" {
if n, err := strconv.Atoi(tag); err == nil && length < n {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must have at least %d items", n),
Value: length,
})
}
}
if tag := f.Tag.Get("maxItems"); tag != "" {
if n, err := strconv.Atoi(tag); err == nil && length > n {
*errs = append(*errs, ValidationError{
Field: path,
Message: fmt.Sprintf("must have at most %d items", n),
Value: length,
})
}
}
}
}
func isNumericKind(k reflect.Kind) bool {
//exhaustive:ignore
switch k {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
return true
default:
return false
}
}
func toFloat64(v reflect.Value) float64 {
//exhaustive:ignore
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(v.Uint())
default: // float32, float64
return v.Float()
}
}