-
Notifications
You must be signed in to change notification settings - Fork 0
/
chcker.go
104 lines (98 loc) · 2.24 KB
/
chcker.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
package vd
import (
"errors"
"reflect"
"strconv"
"strings"
)
type Checker struct {
Format Formatter
}
type Data interface {
VD(r *Rule) (err error)
}
type Report struct {
Fail bool
Message string
Path string
}
func (checker Checker) Check(data Data) (report Report, err error) {
rValue := reflect.ValueOf(data)
rType := rValue.Type()
if rType.Kind() == reflect.Ptr {
err = errors.New("goclub/validator: Check(data) data (" + rType.Name() + ") must be pointer")
return
}
return checker.reflectCheck(rValue, rType, []string{})
}
func (checker Checker) reflectCheck(rValue reflect.Value, rType reflect.Type, path []string) (report Report, err error) {
data := rValue.Interface()
switch v := data.(type) {
case Data:
rule := Rule{
Format: checker.Format,
Path: path,
}
err = v.VD(&rule)
if err != nil {
return
}
if rule.error != nil {
return
}
if rule.Fail {
report.Fail = true
report.Message = rule.Message
report.Path = strings.Join(rule.Path, ".")
return
}
}
for i := 0; i < rType.NumField(); i++ {
rValueItem := rValue.Field(i)
structField := rType.Field(i)
var oldPath []string
oldPath = append([]string{}, path...)
switch structField.Type.Kind() {
case reflect.Slice:
sliceLen := rValueItem.Len()
for i := 0; i < sliceLen; i++ {
sliceItem := rValueItem.Index(i)
sliceItemType := sliceItem.Type()
if sliceItemType.Kind() == reflect.Struct {
vdpath, hasVdpath := structField.Tag.Lookup("json")
if hasVdpath == false {
vdpath = strings.ToLower(structField.Name)
}
path = append(path, vdpath)
path = append(path, strconv.FormatInt(int64(i), 10))
report, err = checker.reflectCheck(sliceItem, sliceItemType, path)
if err != nil {
return
}
if report.Fail {
return
}
path = path[0 : len(path)-2]
}
}
case reflect.Struct:
vdpath, hasVdpath := structField.Tag.Lookup("json")
if hasVdpath {
path = append(path, vdpath)
} else {
vdpath = strings.ToLower(structField.Name)
}
report, err = checker.reflectCheck(rValueItem, structField.Type, path)
if err != nil {
return
}
if report.Fail {
return
}
default:
// 其他类型跳过
}
path = oldPath
}
return
}