-
Notifications
You must be signed in to change notification settings - Fork 11
/
dotaccess.go
86 lines (67 loc) · 1.65 KB
/
dotaccess.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
package dotaccess
import (
"errors"
"fmt"
"reflect"
"strings"
)
func Get(obj interface{}, prop string) (interface{}, error) {
// Get the array access
arr := strings.Split(prop, ".")
var err error
for _, key := range arr {
obj, err = getProperty(obj, key)
if err != nil {
return nil, err
}
if obj == nil {
return nil, nil
}
}
return obj, nil
}
// Loop through this to get properties via dot notation
func getProperty(obj interface{}, prop string) (interface{}, error) {
if reflect.TypeOf(obj).Kind() == reflect.Map {
val := reflect.ValueOf(obj)
valueOf := val.MapIndex(reflect.ValueOf(prop))
if valueOf == reflect.Zero(reflect.ValueOf(prop).Type()) {
return nil, nil
}
idx := val.MapIndex(reflect.ValueOf(prop))
if !idx.IsValid() {
return nil, nil
}
return idx.Interface(), nil
}
prop = strings.Title(prop)
return getField(obj, prop)
}
func getField(obj interface{}, name string) (interface{}, error) {
if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) {
return nil, errors.New("cannot use GetField on a non-struct interface")
}
objValue := reflectValue(obj)
field := objValue.FieldByName(name)
if !field.IsValid() {
return nil, fmt.Errorf("no such field: %s in obj", name)
}
return field.Interface(), nil
}
func hasValidType(obj interface{}, types []reflect.Kind) bool {
for _, t := range types {
if reflect.TypeOf(obj).Kind() == t {
return true
}
}
return false
}
func reflectValue(obj interface{}) reflect.Value {
var val reflect.Value
if reflect.TypeOf(obj).Kind() == reflect.Ptr {
val = reflect.ValueOf(obj).Elem()
} else {
val = reflect.ValueOf(obj)
}
return val
}