forked from matryer/m
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget.go
76 lines (69 loc) · 1.76 KB
/
get.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 m
import (
"reflect"
"strconv"
"strings"
)
const (
dot = "."
openingBracket = "["
)
var closingBracket = "]"[0]
// Get gets the value from the map by the given dot-notation
// keypath. Returns nil if any of the value is missing.
// Supported keypaths:
// key
// key.subkey
// key[i].subkey
// key[i].subkey.subkey2.forever...
func Get(m map[string]interface{}, keypath string) interface{} {
value, _ := GetOK(m, keypath)
return value
}
// GetOK gets the value from the map by the given dot-notation
// keypath, or returns the second argument false if any of the data
// is missing.
// For more information on supported keypaths, see Get.
func GetOK(m map[string]interface{}, keypath string) (interface{}, bool) {
return getOK(m, strings.Split(keypath, dot))
}
// getOK gets the value specified by the keys array from the
// map.
func getOK(m map[string]interface{}, keys []string) (interface{}, bool) {
k := keys[0]
if len(keys) > 1 {
var sub interface{}
var ok bool
if sub, ok = get(m, k); !ok {
return nil, false
}
var submap map[string]interface{}
if submap, ok = sub.(map[string]interface{}); !ok {
return nil, false
}
return getOK(submap, keys[1:])
}
value, ok := get(m, k)
if value == nil {
return nil, false
}
return value, ok
}
// get gets the key from the map.
// Supports array notation for slices.
func get(m map[string]interface{}, k string) (interface{}, bool) {
if k[len(k)-1] == closingBracket {
segs := strings.Split(k, openingBracket)
i, err := strconv.ParseInt(segs[1][0:len(segs[1])-1], 10, 64)
if err != nil {
return nil, false
}
sub, ok := get(m, segs[0])
if !ok {
return nil, false
}
return reflect.ValueOf(sub).Index(int(i)).Interface(), true
}
v, ok := m[k]
return v, ok
}