-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdotaccess.go
91 lines (71 loc) · 1.83 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
87
88
89
90
91
package dotaccess
import (
"errors"
"github.com/oleiade/reflections"
"reflect"
"strings"
)
func Get(obj interface{}, prop string) (interface{}, error) {
// fmt.Println("getting property")
// fmt.Println(args)
// Get the array access
arr := strings.Split(prop, ".")
// fmt.Println(arr)
var err error
// last, arr := arr[len(arr)-1], arr[:len(arr)-1]
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 reflections.GetField(obj, prop)
}
func Set(obj interface{}, prop string, value interface{}) error {
// Get the array access
arr := strings.Split(prop, ".")
// fmt.Println(arr)
var err error
var key string
last, arr := arr[len(arr)-1], arr[:len(arr)-1]
for _, key = range arr {
obj, err = getProperty(obj, key)
if err != nil {
return err
}
}
return setProperty(obj, last, value)
return err
}
func setProperty(obj interface{}, prop string, val interface{}) error {
if reflect.TypeOf(obj).Kind() == reflect.Map {
value := reflect.ValueOf(obj)
value.SetMapIndex(reflect.ValueOf(prop), reflect.ValueOf(val))
return nil
}
if reflect.TypeOf(obj).Kind() != reflect.Ptr {
return errors.New("Object must be a pointer to a struct")
}
prop = strings.Title(prop)
return reflections.SetField(obj, prop, val)
}