-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
58 lines (53 loc) · 1.27 KB
/
util.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
package config
import (
"os"
"reflect"
"regexp"
"strings"
)
func ReadEnv(value string) string {
path := "\\${(.*?)}"
exp := regexp.MustCompile(path)
result := exp.FindAllStringSubmatch(value, -1)
if len(result) > 0 {
for _, v := range result {
if env := os.Getenv(v[1]); env != "" {
value = strings.Replace(value, v[0], env, 1)
}
}
return value
}
return ""
}
func ReplaceEnv(s interface{}) {
if reflect.TypeOf(s).Kind() != reflect.Ptr {
panic("s must be a pointer")
}
v := reflect.ValueOf(s).Elem()
t := v.Type()
for k := 0; k < t.NumField(); k++ {
if t.Field(k).Type.Kind() == reflect.Struct {
ReplaceEnv(v.Field(k).Addr().Interface())
} else {
if t.Field(k).Type.Kind() == reflect.String {
value := v.Field(k).Interface().(string)
env := ReadEnv(value)
if env != "" {
v.Field(k).Set(reflect.ValueOf(env))
}
}
if t.Field(k).Type.Kind() == reflect.Map {
mv := reflect.ValueOf(v.Field(k).Interface())
keys := mv.MapKeys()
for _, mk := range keys {
value := mv.MapIndex(mk)
env := ReadEnv(value.Interface().(string))
if env != "" {
mv.SetMapIndex(mk, reflect.ValueOf(env))
}
}
}
//fmt.Printf("[%s]%s:%v\n", t.Field(k).Type.Kind(), t.Field(k).Name, v.Field(k).Interface())
}
}
}