-
Notifications
You must be signed in to change notification settings - Fork 15
/
env_layer.go
68 lines (60 loc) · 1.87 KB
/
env_layer.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
package onion
import (
"os"
"strings"
)
func buildMap(m map[string]interface{}, v interface{}, k ...string) map[string]interface{} {
if m == nil {
m = make(map[string]interface{})
}
switch len(k) {
case 0:
return m
case 1:
m[k[0]] = v
return m
}
d, _ := m[k[0]].(map[string]interface{})
m[k[0]] = buildMap(d, v, k[1:]...)
return m
}
// NewEnvLayer create new layer using the whitelist of environment values.
func NewEnvLayer(separator string, whiteList ...string) Layer {
var data map[string]interface{}
for i := range whiteList {
if v, ok := os.LookupEnv(whiteList[i]); ok {
keys := strings.Split(strings.ToLower(whiteList[i]), separator)
data = buildMap(data, v, keys...)
}
}
return NewMapLayer(data)
}
// NewEnvLayerPrefix create new env layer, with all values with the same prefix
// TODO: No prefix loading
func NewEnvLayerPrefix(separator string, prefix string) Layer {
var data map[string]interface{}
pf := strings.ToUpper(prefix) + separator
for _, env := range os.Environ() {
if strings.HasPrefix(env, pf) {
k := strings.Trim(strings.Split(env, "=")[0], "\t\n ")
ck := strings.ToLower(strings.TrimPrefix(k, pf))
data = buildMap(data, os.Getenv(k), strings.Split(ck, separator)...)
}
}
return NewMapLayer(data)
}
// NewFlatEnvLayerPrefix create new env layer, with all values with the same prefix however
// this does not seperate the value hierarchically. This can be used for layered configurations
// such as csv or ini instead of json or yaml.
func NewFlatEnvLayerPrefix(separator string, prefix string) Layer {
var data map[string]interface{}
pf := strings.ToUpper(prefix) + separator
for _, env := range os.Environ() {
if strings.HasPrefix(env, pf) {
k := strings.Trim(strings.Split(env, "=")[0], "\t\n ")
ck := strings.ToLower(strings.TrimPrefix(k, pf))
data = buildMap(data, os.Getenv(k), ck)
}
}
return NewMapLayer(data)
}