-
Notifications
You must be signed in to change notification settings - Fork 33
/
reqValidator.go
168 lines (155 loc) · 4.62 KB
/
reqValidator.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
// Copyright 2017 MSolution.IO
//
// 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 req
import (
"errors"
"reflect"
"strings"
)
// internalValidator validates a value, returning nil in case of success.
type internalValidator func(reflect.Value) error
// Validator validates a value, returning nil in case of success.
type Validator func(interface{}) error
const (
// StructTagName is the name of the tags package req bases its behavior
// on.
StructTagName = "req"
// StructTagNonZero indicates that a field with a zero value shall fail
// validation.
StructTagNonZero = "nonzero"
)
var (
ErrUnsupportedType = errors.New("unsupported type")
ErrUnknownDirective = errors.New("unknown directive")
ErrTestNonZeroIsZero = errors.New("value is zero")
ErrCannotValidateType = errors.New("cannot validate type")
)
// CreateValidator creates a validator for the type of its argument.
func CreateValidator(example interface{}) (Validator, error) {
typ := reflect.TypeOf(example)
switch typ.Kind() {
case reflect.Struct:
iv, err := createValidatorForStruct(typ)
if err == nil {
return exposedValidator(iv, typ), nil
} else {
return nil, err
}
default:
return nil, ErrUnsupportedType
}
}
// exposedValidator wraps an internalValidator into a Validator suitable to
// being exported.
func exposedValidator(iv internalValidator, typ reflect.Type) Validator {
if iv == nil {
return nil
} else {
return func(in interface{}) error {
ityp := reflect.TypeOf(in)
ival := reflect.ValueOf(in)
if ityp != typ && ityp.Kind() == reflect.Ptr {
ityp = ityp.Elem()
ival = ival.Elem()
}
if ityp != typ && (ityp.Kind() != reflect.Ptr || ityp.Elem() != typ) {
return ErrCannotValidateType
} else {
return iv(ival)
}
}
}
}
// createValidatorForStruct builds a validator function for a given structure
// type.
func createValidatorForStruct(typ reflect.Type) (internalValidator, error) {
var vs []internalValidator
for i, fc := 0, typ.NumField(); i < fc; i++ {
f := typ.FieldByIndex([]int{i})
if v, err := createValidatorForField(typ, f); err != nil {
return nil, err
} else if v != nil {
vs = append(vs, v)
}
}
return aggregateValidators(vs), nil
}
// createValidatorForField creates a validator function for a given structure
// field.
func createValidatorForField(typ reflect.Type, fld reflect.StructField) (internalValidator, error) {
if tag := fld.Tag.Get(StructTagName); tag == "" {
return nil, nil
} else {
var tags = strings.Split(tag, ",")
var tests []internalValidator
for _, tag := range tags {
if test, err := getTestFor(typ, fld, tag); err != nil {
return nil, err
} else if test != nil {
tests = append(tests, test)
}
}
av := aggregateValidators(tests)
return func(val reflect.Value) error {
val = val.FieldByIndex(fld.Index)
return av(val)
}, nil
}
}
// aggregateValidators creates a single validator from a collection of
// validators. When called it will allways run all child validators, returning
// all errors.
func aggregateValidators(fvs []internalValidator) internalValidator {
if fvs == nil || len(fvs) == 0 {
return nil
} else {
return func(v reflect.Value) error {
var errs ValidationError
for _, fv := range fvs {
if err := fv(v); err != nil {
errs = append(errs, err)
}
}
if errs == nil { // Must return explicit nil to actually return nil
return nil
} else {
return errs
}
}
}
}
// getTestFor builds a validator for a given structure field and tag.
func getTestFor(typ reflect.Type, fld reflect.StructField, tag string) (internalValidator, error) {
switch tag {
case StructTagNonZero:
return testNonZero(fld), nil
default:
return nil, ErrUnknownDirective
}
}
// testNonZero builds a field validator which ensures the field's value is not
// the zero value for its type.
func testNonZero(fld reflect.StructField) internalValidator {
zero := reflect.Zero(fld.Type).Interface()
return func(val reflect.Value) error {
if reflect.DeepEqual(val.Interface(), zero) {
return FieldValidationError{
Field: fld,
Err: ErrTestNonZeroIsZero,
}
} else {
return nil
}
}
}