-
Notifications
You must be signed in to change notification settings - Fork 2
/
validator.go
289 lines (256 loc) · 5.86 KB
/
validator.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
// Package validator provides validation for structs and fields.
package validator
import (
"bytes"
"fmt"
"reflect"
"strings"
"unicode"
)
const (
defaultTagName = "valid"
)
// UnsupportedError is a generic error returned when validation function
// is applied on fields it does not support or the function has not been
// registered to Validator.
type UnsupportedError string
func (e UnsupportedError) Error() string {
return "validator: unsupported: " + string(e)
}
// Errors is a list of error.
type Errors []error
// Error returns formatted string of all underlying errors.
func (e Errors) Error() string {
var buf bytes.Buffer
for i, err := range e {
if i > 0 {
buf.WriteString(",\n")
}
buf.WriteString(err.Error())
}
return buf.String()
}
// Func validates field with value v, field name and parameter p.
type Func func(v reflect.Value, name, param string) error
// Option sets options for the validator.
type Option func(v *Validator)
// Validatable is an interface implemented by types that can
// validate themselves.
type Validatable interface {
Validate() error
}
var validatableType = reflect.TypeOf(new(Validatable)).Elem()
// Validator implements value validation for structs and fields.
type Validator struct {
tagName string
funcs map[string]Func
fieldCache fieldCache
}
// New allocates and returns a new Validator with given options.
// To create a new Validator with default options, use Default instead.
func New(options ...Option) *Validator {
v := &Validator{
tagName: defaultTagName,
funcs: make(map[string]Func),
}
for _, opt := range options {
opt(v)
}
return v
}
// WithTagName returns an Option which sets tagName to the validator.
func WithTagName(tagName string) Option {
return func(v *Validator) {
v.tagName = tagName
}
}
// WithFunc returns an Option which adds a new function handler.
// If a function with same name existed, it will be overriden by the given one.
// It panics if name is empty or handler is nil.
func WithFunc(name string, fn Func) Option {
if name == "" || fn == nil {
panic("validator: invalid handler " + name)
}
return func(v *Validator) {
v.register(name, fn)
}
}
func (a *Validator) register(name string, fn Func) {
a.funcs[name] = fn
}
// Validate validates given value. Value v is usually a pointer to
// the struct to validate, but it can also be a struct, slice or array.
func (a *Validator) Validate(v interface{}) (err error) {
s := state{validator: a}
defer func() {
if r := recover(); r != nil {
if rerr, ok := r.(error); ok {
s.addError(rerr)
} else {
s.addError(fmt.Errorf("%v", r))
}
err = Errors(s.errors)
}
}()
s.validateInterface(v)
if len(s.errors) == 0 {
return nil
}
return Errors(s.errors)
}
func (a *Validator) getFields(rt reflect.Type) []field {
fields, ok := a.fieldCache.get(rt)
if ok {
return fields
}
fields = make([]field, 0, 10)
n := rt.NumField()
for i := 0; i < n; i++ {
ft := rt.Field(i)
if !ft.Anonymous {
// Ignore unexported but allow embedded fields
if unicode.IsLower([]rune(ft.Name)[0]) {
continue
}
}
// Explicitly ignored
tags := ft.Tag.Get(a.tagName)
if tags == "-" {
continue
}
if tags == "" {
if !supported(ft.Type) {
continue
}
}
fields = append(fields, field{
idx: i,
name: ft.Name,
tags: tags,
})
}
a.fieldCache.save(rt, fields)
return fields
}
func supported(rt reflect.Type) bool {
switch rt.Kind() {
case reflect.Struct, reflect.Slice, reflect.Array, reflect.Map, reflect.Ptr, reflect.Interface:
return true
}
return rt.Implements(validatableType)
}
type state struct {
validator *Validator
errors []error
}
func (s *state) validateValue(rv reflect.Value) {
// Call Validate method if this value implements Validatable
s.validateValidatable(rv)
// Resolve pointer
for rv.Kind() == reflect.Ptr && !rv.IsNil() {
rv = rv.Elem()
}
switch rv.Kind() {
case reflect.Struct:
s.validateStruct(rv)
case reflect.Slice, reflect.Array:
s.validateSlice(rv)
case reflect.Map:
s.validateMap(rv)
case reflect.Interface:
s.validateInterface(rv.Interface())
}
}
func (s *state) validateInterface(v interface{}) {
rv := reflect.ValueOf(v)
s.validateValue(rv)
}
func (s *state) validateStruct(rv reflect.Value) {
rt := rv.Type()
fields := s.validator.getFields(rt)
n := len(fields)
for i := 0; i < n; i++ {
ft := &fields[i]
fv := rv.Field(ft.idx)
if ft.tags != "" {
// Validate this field
s.validateField(fv, ft.name, ft.tags)
}
s.validateValue(fv)
}
}
func (s *state) validateSlice(rv reflect.Value) {
rt := rv.Type()
if !supported(rt.Elem()) {
return
}
n := rv.Len()
for i := 0; i < n; i++ {
fv := rv.Index(i)
s.validateValue(fv)
}
}
func (s *state) validateMap(rv reflect.Value) {
rt := rv.Type()
if !supported(rt.Elem()) {
return
}
if rv.Len() == 0 {
return
}
for _, k := range rv.MapKeys() {
fv := rv.MapIndex(k)
s.validateValue(fv)
}
}
func (s *state) validateField(fv reflect.Value, name, tags string) {
for tags != "" {
var tag string
i := strings.Index(tags, ",")
if i < 0 {
tag = tags
tags = ""
} else {
tag = tags[:i]
tags = tags[i+1:]
}
fn, param := parseTag(tag)
f, ok := s.validator.funcs[fn]
if ok {
err := f(fv, name, param)
if err != nil {
s.addError(err)
}
} else {
s.addError(UnsupportedError(fn))
}
}
}
func (s *state) validateValidatable(rv reflect.Value) {
if !rv.IsValid() || rv.Type().NumMethod() == 0 {
return
}
if rv.Kind() == reflect.Ptr && rv.IsNil() {
return
}
if f, ok := rv.Interface().(Validatable); ok {
err := f.Validate()
if err != nil {
s.addError(err)
}
}
}
func (s *state) addError(err error) {
s.errors = append(s.errors, err)
}
// parseTag returns function name and parameter.
func parseTag(tag string) (name, param string) {
i := strings.Index(tag, "=")
if i < 0 {
name = tag
} else {
name = tag[:i]
param = tag[i+1:]
}
return
}