-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
48 lines (40 loc) · 1002 Bytes
/
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
package ddtags
import (
"fmt"
"reflect"
"strings"
)
// Returns an error if any fields in the struct (tagged with ddtag) are invalid and will be ignored
// You can use this inside your test suite
func Validate(struc any) error {
v := reflect.ValueOf(struc).Elem()
sType := v.Type()
for i := 0; i < v.NumField(); i++ {
ddTagVal, hasTag := sType.Field(i).Tag.Lookup(tagKey)
if !hasTag || ddTagVal == "" {
continue
}
ddTag, _, _ := strings.Cut(ddTagVal, ",")
if ddTag == "" || ddTag == "-" {
continue
}
field := v.Field(i)
switch f := field.Interface().(type) {
case string:
case bool:
case int, int8, int16, int32, int64:
case uint, uint8, uint16, uint32, uint64:
case float32:
case float64:
case *string:
case *bool:
case *float32:
case *float64:
case *int, *int8, *int16, *int32, *int64:
case *uint, *uint8, *uint16, *uint32, *uint64:
default:
return fmt.Errorf("invalid field type: %s (%T)", sType.Field(i).Name, f)
}
}
return nil
}