-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
64 lines (53 loc) · 1.28 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
package yaconf
import (
"fmt"
"reflect"
"strings"
)
type validator interface {
Validate() error
}
func addPrefix(prefix, name string) string {
if prefix == "" {
return name
}
return fmt.Sprintf("%s.%s", prefix, name)
}
func validate(config interface{}, prefix string) []string {
t := reflect.TypeOf(config)
v := reflect.ValueOf(config)
if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}
errors := []string{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
}
name := f.Tag.Get("yaml")
if name == "" {
name = f.Name
}
if strings.Contains(f.Tag.Get("yaconf"), "required") && v.Field(i).IsZero() {
errors = append(errors, fmt.Sprintf("%s is required", addPrefix(prefix, name)))
continue
}
if f.Type.Kind() == reflect.Struct {
errors = append(errors, validate(v.Field(i).Interface(), addPrefix(prefix, name))...)
continue
}
if f.Type.Kind() == reflect.Ptr {
if f.Type.Elem().Kind() != reflect.Struct {
continue
}
if v.Field(i).IsNil() {
errors = append(errors, validate(reflect.New(v.Field(i).Type().Elem()).Interface(), addPrefix(prefix, name))...)
} else {
errors = append(errors, validate(v.Field(i).Elem().Interface(), addPrefix(prefix, name))...)
}
}
}
return errors
}