-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathincludeif.go
107 lines (84 loc) · 2.36 KB
/
includeif.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package bytecodec
import (
"fmt"
"reflect"
"strconv"
)
func shouldIgnore(tags reflect.StructTag, root reflect.Value, parent reflect.Value) (bool, error) {
includeIf, err := tagIncludeIf(tags)
if err != nil {
return false, err
}
if includeIf.HasIncludeIf() {
includeBase := root
if includeIf.Relative {
includeBase = parent
}
i, err := findValue(includeBase, includeIf.FieldPath)
if err != nil {
return false, err
}
switch v := i.(type) {
case bool:
stringValue := includeIf.Value
if stringValue == "" {
stringValue = "true"
}
tagVal, err := strconv.ParseBool(stringValue)
switch includeIf.Operation {
case Equal:
return tagVal != v, err
case NotEqual:
return tagVal == v, err
default:
return false, fmt.Errorf("includeIf path could not be parsed: unable to compare end parameter (unknown comparison for bool)")
}
case uint8:
return compareUint(uint64(v), includeIf)
case uint16:
return compareUint(uint64(v), includeIf)
case uint32:
return compareUint(uint64(v), includeIf)
case uint64:
return compareUint(v, includeIf)
default:
return false, fmt.Errorf("includeIf path could not be parsed: unable to compare end parameter (unknown type)")
}
}
return false, nil
}
func compareUint(v uint64, includeIf IncludeIfTag) (bool, error) {
stringValue := includeIf.Value
if stringValue == "" {
stringValue = "0"
}
tagVal, err := strconv.ParseUint(stringValue, 10, 64)
switch includeIf.Operation {
case Equal:
return tagVal != v, err
case NotEqual:
return tagVal == v, err
default:
return false, fmt.Errorf("includeIf path could not be parsed: unable to compare end parameter (unknown comparison for bool)")
}
}
func findValue(structValue reflect.Value, path []string) (interface{}, error) {
structType := structValue.Type()
thisLevel := path[0]
remainingPath := path[1:]
for i := 0; i < structValue.NumField(); i++ {
value := structValue.Field(i)
field := structType.Field(i)
name := field.Name
if name == thisLevel {
if len(remainingPath) >= 1 {
if value.Kind() != reflect.Struct {
return false, fmt.Errorf("includeIf path could not be parsed: %s is not a struct", name)
}
return findValue(value, remainingPath)
}
return value.Interface(), nil
}
}
return false, fmt.Errorf("includeIf path could not be parsed: %s not found", thisLevel)
}