-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
85 lines (72 loc) · 1.69 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
package main
import (
"reflect"
"strconv"
"strings"
)
// ValidateAllFields validates whether all fields of a struct are valid
func ValidateAllFields(item interface{}) (bool, error) {
v := reflect.ValueOf(item)
for i := 0; i < v.NumField(); i++ {
validator := getValidatorFromValue(v.Field(i))
if validator != nil {
res, err := validator.validate(v.Type().Field(i), v.Field(i))
if err != nil || res == false {
return res, err
}
}
}
return true, nil
}
func getValidatorFromValue(fv reflect.Value) validator {
switch fv.Interface().(type) {
case int:
return createIntValidator("validate")
default:
return nil
}
}
// validator validates a struct field
type validator interface {
validate(f reflect.StructField, fv reflect.Value) (bool, error)
}
// intValidator validates int fields of a strcut
type intValidator struct {
tagName string
}
func createIntValidator(tag string) intValidator {
return intValidator{
tagName: tag,
}
}
// validate validates whether an integer is valid
func (v intValidator) validate(f reflect.StructField, fv reflect.Value) (bool, error) {
tag := f.Tag.Get(v.tagName)
args := strings.Split(tag, ";")
for _, arg := range args {
keyValue := strings.Split(arg, ":")
key := keyValue[0]
valueString := strings.Join(keyValue[1:], ":")
if key == "min" {
minValue, err := strconv.Atoi(valueString)
if err != nil {
return false, err
}
val := fv.Interface().(int)
if val < minValue {
return false, nil
}
}
if key == "max" {
maxValue, err := strconv.Atoi(valueString)
if err != nil {
return false, err
}
val := fv.Interface().(int)
if val > maxValue {
return false, nil
}
}
}
return true, nil
}