-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
48 lines (42 loc) · 1.03 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
package common
import (
"fmt"
"strings"
)
func MapGetKV(v map[string]interface{}, key string) (interface{}, error) {
var ok bool
var cursor interface{} = v
parts := strings.Split(key, ".")
for i, part := range parts {
cursor, ok = cursor.(map[string]interface{})[part]
if !ok {
sofar := strings.Join(parts[:i], ".")
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 { // create map if this is empty
mcursor[part] = map[string]interface{}{}
cursor = mcursor[part]
}
}
return nil
}