-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaps.go
48 lines (38 loc) · 1.08 KB
/
maps.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 xload
import (
"context"
"github.com/spf13/cast"
)
// MapLoader loads values from a map.
//
// Can be used with xload.FlattenMap as an intermediate format
// when loading from various sources.
type MapLoader map[string]string
// Load fetches the value from the map.
func (m MapLoader) Load(_ context.Context, key string) (string, error) {
value, ok := m[key]
if !ok {
return "", nil
}
return value, nil
}
// FlattenMap flattens a map[string]interface{} into a map[string]string.
// Nested maps are flattened using given separator.
func FlattenMap(m map[string]interface{}, sep string) map[string]string {
return flatten(m, "", sep)
}
func (m MapLoader) apply(opts *options) { opts.loader = m }
func flatten(m map[string]interface{}, prefix string, sep string) map[string]string {
flattened := make(map[string]string)
for key, value := range m {
switch value := value.(type) {
case map[string]interface{}:
for k, v := range flatten(value, key+sep, sep) {
flattened[prefix+k] = v
}
default:
flattened[prefix+key] = cast.ToString(value)
}
}
return flattened
}