-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct_validaktor.go
More file actions
64 lines (50 loc) · 1.23 KB
/
struct_validaktor.go
File metadata and controls
64 lines (50 loc) · 1.23 KB
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
package validaktor
import (
"fmt"
"reflect"
"unsafe"
)
type (
structValidator struct{
v *validaktor
}
structError struct {
message string
}
)
func newStructValidatorError(message string) *structError {
return &structError{message: message}
}
func (e *structError) Error() string {
return e.message
}
func (v *structValidator) applyValidatorOptions(_ ...string) error {
return nil
}
func (v *structValidator) validate(data interface{}) (bool, error) {
dv := reflect.ValueOf(data)
if dv.Kind() == reflect.Ptr {
dv = dv.Elem()
}
for i := 0; i < dv.NumField(); i++ {
tag := dv.Type().Field(i).Tag.Get(tagName)
if tag == "" || tag == "-" {
continue
}
if v.v == nil {
v.v = NewValidaktor()
}
validator, err := v.v.getValidator(tag)
if err != nil {
return false, newStructValidatorError(fmt.Sprintf("struct validation: error getting validator: %s", err))
}
ifdata := dv.Field(i).Interface()
if (*[2]uintptr)(unsafe.Pointer(&ifdata))[1] == 0 {
return false, newStructValidatorError("the struct is empty or nil")
}
if _, err := validator.validate(ifdata); err != nil {
return false, newStructValidatorError(fmt.Sprintf("struct validation: error validating: %s", err))
}
}
return true, nil
}