-
Notifications
You must be signed in to change notification settings - Fork 62
/
common.go
56 lines (47 loc) · 1.19 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
package common
import (
"fmt"
"strings"
)
func MapGetKV(v map[string]interface{}, key string) (interface{}, error) {
var ok bool
var mcursor map[string]interface{}
var cursor interface{} = v
parts := strings.Split(key, ".")
for i, part := range parts {
sofar := strings.Join(parts[:i], ".")
mcursor, ok = cursor.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%s key is not a map", sofar)
}
cursor, ok = mcursor[part]
if !ok {
return nil, fmt.Errorf("%s key has no attributes", sofar)
}
}
return cursor, nil
}
func MapSetKV(v map[string]interface{}, key string, value interface{}) error {
var ok bool
var mcursor map[string]interface{}
var cursor interface{} = v
parts := strings.Split(key, ".")
for i, part := range parts {
mcursor, ok = cursor.(map[string]interface{})
if !ok {
sofar := strings.Join(parts[:i], ".")
return fmt.Errorf("%s key is not a map", sofar)
}
// last part? set here
if i == (len(parts) - 1) {
mcursor[part] = value
break
}
cursor, ok = mcursor[part]
if !ok || cursor == nil { // create map if this is empty or is null
mcursor[part] = map[string]interface{}{}
cursor = mcursor[part]
}
}
return nil
}