forked from wacul/valval
-
Notifications
You must be signed in to change notification settings - Fork 0
/
values.go
112 lines (98 loc) · 1.91 KB
/
values.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
package valval
import (
"reflect"
)
type valType int
const (
t_any valType = iota
t_number
t_string
t_bool
)
var vtStrings = map[valType]string{
t_number: "number",
t_string: "string",
t_bool: "bool",
}
func (vt *valType) isKindOfType(val interface{}) bool {
if *vt == t_any {
return true
}
uvt := unwrapPtr(val)
if uvt == nil {
return false
}
rv := reflect.ValueOf(val)
kind := rv.Kind()
switch *vt {
case t_number:
switch kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Uintptr, reflect.Float32, reflect.Float64:
return true
}
case t_string:
return kind == reflect.String
case t_bool:
return kind == reflect.Bool
}
return false
}
type ValueValidator struct {
vt valType
vfuncs []ValidatorFunc
}
func validateByFuncs(vfs []ValidatorFunc, val interface{}) error {
errs := []error{}
for _, vf := range vfs {
err := vf(val)
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
ret := valueError(errs)
return &ret
}
return nil
}
func (v *ValueValidator) Validate(val interface{}) error {
if val == nil {
return nil
}
if v.vt.isKindOfType(val) {
return validateByFuncs(v.vfuncs, val)
}
return typeMissmatchError(vtStrings[v.vt])
}
func Number(vfuncs ...ValidatorFunc) *ValueValidator {
return &ValueValidator{
vt: t_number,
vfuncs: vfuncs,
}
}
func String(vfuncs ...ValidatorFunc) *ValueValidator {
return &ValueValidator{
vt: t_string,
vfuncs: vfuncs,
}
}
func Bool(vfuncs ...ValidatorFunc) *ValueValidator {
return &ValueValidator{
vt: t_bool,
vfuncs: vfuncs,
}
}
func Any(vfuncs ...ValidatorFunc) *ValueValidator {
return &ValueValidator{
vt: t_any,
vfuncs: vfuncs,
}
}
func NullString(vfuncs ...ValidatorFunc) *ValueValidator {
return &ValueValidator{
vt: t_any,
vfuncs: vfuncs,
}
}