-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate.go
86 lines (73 loc) · 1.94 KB
/
validate.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
package gbind
import (
"fmt"
"reflect"
"strings"
"sync"
"github.com/go-playground/validator/v10"
)
// StructValidator StructValidator
type StructValidator interface {
ValidateStruct(interface{}) error
}
// Validator Validator
var Validator StructValidator = &defaultValidator{}
type defaultValidator struct {
once sync.Once
validate *validator.Validate
}
func (v *defaultValidator) lazyinit() {
v.once.Do(func() {
v.validate = validator.New()
v.validate.SetTagName("validate")
})
}
type sliceValidateError []error
func (err sliceValidateError) Error() string {
var errMsgs []string
for i, e := range err {
if e == nil {
continue
}
errMsgs = append(errMsgs, fmt.Sprintf("[%d]: %s", i, e.Error()))
}
return strings.Join(errMsgs, "\n")
}
var _ StructValidator = &defaultValidator{}
// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
func (v *defaultValidator) ValidateStruct(obj interface{}) error {
if obj == nil {
return nil
}
value := reflect.ValueOf(obj)
switch value.Kind() {
case reflect.Ptr:
return v.ValidateStruct(value.Elem().Interface())
case reflect.Struct:
return v.validateStruct(obj)
// case reflect.Slice, reflect.Array:
// count := value.Len()
// validateRet := make(sliceValidateError, 0)
// for i := 0; i < count; i++ {
// if err := v.ValidateStruct(value.Index(i).Interface()); err != nil {
// validateRet = append(validateRet, err)
// }
// }
// if len(validateRet) == 0 {
// return nil
// }
// return validateRet
default:
return nil
}
}
// ValidateStruct receives struct type
func (v *defaultValidator) validateStruct(obj interface{}) error {
v.lazyinit()
// v.validate.RegisterValidation()
return v.validate.Struct(obj)
}
func (v *defaultValidator) registerCustomValidation(tag string, fn validator.Func, callValidationEvenIfNull ...bool) error {
v.lazyinit()
return v.validate.RegisterValidation(tag, fn, callValidationEvenIfNull...)
}