-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.go
115 lines (98 loc) · 2.02 KB
/
common.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
108
109
110
111
112
113
114
115
package valval
import (
"errors"
"reflect"
)
type Validator interface {
Validate(val interface{}) error
}
type objField struct {
value interface{}
tag reflect.StructTag
}
type ValidatorFunc func(val interface{}) error
func isNilValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr,
reflect.Interface, reflect.Slice:
if v.IsNil() {
return true
}
}
return false
}
func unwrapPtr(val interface{}) interface{} {
if val == nil {
return nil
}
v := reflect.ValueOf(val)
if isNilValue(v) {
return nil
}
if v.Kind() == reflect.Ptr {
elm := v.Elem()
return unwrapPtr(elm.Interface())
}
return val
}
func obj2Map(val interface{}) (map[string]objField, error) {
if val == nil {
return nil, nil
}
if m, ok := val.(map[string]interface{}); ok {
return flattenMap(m), nil
}
uv := unwrapPtr(val)
rv := reflect.ValueOf(uv)
if rv.Kind() == reflect.Struct {
return struct2Map(val), nil
}
return nil, errors.New("invalid type")
}
func fieldMap2objMap(in map[string]objField) map[string]interface{} {
ret := map[string]interface{}{}
for k, v := range in {
ret[k] = v.value
}
return ret
}
func flattenMap(m map[string]interface{}) map[string]objField {
ret := map[string]objField{}
for k, v := range m {
ret[k] = objField{
value: unwrapPtr(v),
}
}
return ret
}
func struct2Map(val interface{}) map[string]objField {
rv := reflect.ValueOf(val)
sv := reflect.TypeOf(val)
ret := map[string]objField{}
for i := 0; i < rv.NumField(); i++ {
f := sv.Field(i)
fv := rv.Field(i)
ret[f.Name] = objField{
value: unwrapPtr(fv.Interface()),
tag: f.Tag,
}
}
return ret
}
func interfaceSlice(s interface{}) []interface{} {
rv := reflect.ValueOf(s)
length := rv.Len()
ret := make([]interface{}, length)
for i := 0; i < length; i++ {
v := rv.Index(i)
if isNilValue(v) {
ret[i] = nil
continue
}
ret[i] = unwrapPtr(v.Interface())
}
return ret
}
func typeMissmatchError(ts string) error {
return errors.New("type missmatch " + ts)
}