-
Notifications
You must be signed in to change notification settings - Fork 3
/
custom.go
75 lines (64 loc) · 1.9 KB
/
custom.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
package enforcer
import (
"fmt"
"reflect"
"strconv"
"strings"
)
type CustomEnforcements []map[string]func(string) string
func CustomValidator(req interface{}, customEnforcements CustomEnforcements) []string {
errors := Validate(req)
v := reflect.ValueOf(req)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
enforceTag := field.Tag.Get("enforce")
if enforceTag != "" {
fieldValue := v.Field(i)
fieldString := ""
fieldType := fieldValue.Type()
switch fieldType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fieldString = strconv.Itoa(int(fieldValue.Int()))
default:
fieldString = fieldValue.String()
}
enforceOpts := strings.Split(enforceTag, " ")
for _, opt := range enforceOpts {
if strings.HasPrefix(opt, "custom") {
enforcementNames := getCustomEnforcementNames(opt)
for _, enforcementName := range enforcementNames {
if enforcementFunc, ok := getCustomEnforcementFunc(customEnforcements, enforcementName); ok {
// There's probably a better way to do all this
err := enforcementFunc(fieldString)
if err != "" {
errors = append(errors, err)
}
} else {
errors = append(errors, fmt.Sprintf("Custom enforcement '%s' not found for field '%s'", enforcementName, field.Name))
}
}
}
}
}
}
return errors
}
func getCustomEnforcementFunc(
customEnforcements CustomEnforcements, enforcementName string,
) (func(string) string, bool) {
for _, enforcementMap := range customEnforcements {
if enforcementFunc, ok := enforcementMap[enforcementName]; ok {
return enforcementFunc, true
}
}
return nil, false
}
func getCustomEnforcementNames(opt string) []string {
prefix := "custom:"
enforcementNamesStr := strings.TrimPrefix(opt, prefix)
return strings.Split(enforcementNamesStr, ",")
}