-
Notifications
You must be signed in to change notification settings - Fork 38
/
accessor.go
76 lines (59 loc) · 1.77 KB
/
accessor.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
package utils
import (
"reflect"
"strconv"
"strings"
"github.com/pkg/errors"
)
// ValueAtPath will get struct attribute value by recursive
func ValueAtPath(v interface{}, path string) (interface{}, error) {
components := strings.Split(path, ".")
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return nil, errors.Errorf("object %#v is nil", v)
}
rv = rv.Elem()
}
if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array {
i, err := strconv.Atoi(components[0])
if err != nil {
return nil, errors.Errorf("path %s is invalid at index of array", path)
}
length := rv.Len()
if i >= length {
return nil, errors.Errorf("path %s is invalid, array has length %v, but got %v", path, length, i)
}
itemV := rv.Index(i)
if !itemV.IsValid() {
return nil, errors.Errorf("path %s is invalid for map", path)
}
if len(components) > 1 {
return ValueAtPath(itemV.Interface(), strings.Join(components[1:], "."))
}
return itemV.Interface(), nil
}
if rv.Kind() == reflect.Map && !rv.IsNil() {
itemV := rv.MapIndex(reflect.ValueOf(components[0]))
if !itemV.IsValid() {
return nil, errors.Errorf("path %s is invalid for map", path)
}
if len(components) > 1 {
return ValueAtPath(itemV.Interface(), strings.Join(components[1:], "."))
}
return itemV.Interface(), nil
}
if rv.Kind() == reflect.Struct {
itemV := rv.FieldByNameFunc(func(s string) bool {
return strings.EqualFold(s, components[0])
})
if !itemV.IsValid() {
return nil, errors.Errorf("path %s is invalid for struct", path)
}
if len(components) > 1 {
return ValueAtPath(itemV.Interface(), strings.Join(components[1:], "."))
}
return itemV.Interface(), nil
}
return nil, errors.Errorf("object %#v is invalid, need map or struct", v)
}