forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
109 lines (91 loc) · 2.11 KB
/
map.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package maputil
import (
"reflect"
"strings"
)
// MergeStringMap simple merge two string map. merge src to dst map
func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]string {
for k, v := range src {
if ignoreCase {
k = strings.ToLower(k)
}
dst[k] = v
}
return dst
}
// KeyToLower convert keys to lower case.
func KeyToLower(src map[string]string) map[string]string {
newMp := make(map[string]string, len(src))
for k, v := range src {
k = strings.ToLower(k)
newMp[k] = v
}
return newMp
}
// GetByPath get value from a map[string]interface{}. eg "top" "top.sub"
func GetByPath(key string, mp map[string]interface{}) (val interface{}, ok bool) {
if val, ok := mp[key]; ok {
return val, true
}
// has sub key? eg. "top.sub"
if !strings.ContainsRune(key, '.') {
return nil, false
}
keys := strings.Split(key, ".")
topK := keys[0]
// find top item data based on top key
var item interface{}
if item, ok = mp[topK]; !ok {
return
}
for _, k := range keys[1:] {
switch tData := item.(type) {
case map[string]string: // is simple map
item, ok = tData[k]
if !ok {
return
}
case map[string]interface{}: // is map(decode from toml/json)
if item, ok = tData[k]; !ok {
return
}
case map[interface{}]interface{}: // is map(decode from yaml)
if item, ok = tData[k]; !ok {
return
}
default: // error
ok = false
return
}
}
return item, true
}
// Keys get all keys of the given map.
func Keys(mp interface{}) (keys []string) {
rftVal := reflect.ValueOf(mp)
if rftVal.Type().Kind() == reflect.Ptr {
rftVal = rftVal.Elem()
}
if rftVal.Kind() != reflect.Map {
return
}
for _, key := range rftVal.MapKeys() {
keys = append(keys, key.String())
}
return
}
// Values get all values from the given map.
func Values(mp interface{}) (values []interface{}) {
rftTyp := reflect.TypeOf(mp)
if rftTyp.Kind() == reflect.Ptr {
rftTyp = rftTyp.Elem()
}
if rftTyp.Kind() != reflect.Map {
return
}
rftVal := reflect.ValueOf(mp)
for _, key := range rftVal.MapKeys() {
values = append(values, rftVal.MapIndex(key).Interface())
}
return
}