-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsetting.go
60 lines (49 loc) · 1.05 KB
/
setting.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
package setting
import (
"log"
"os"
"reflect"
)
// Load ...
func Load(config interface{}) {
// TODO, ensure config is struct
v := reflect.ValueOf(config).Elem()
t := v.Type()
loadStruct(t, v)
}
func loadStruct(t reflect.Type, v reflect.Value) {
for i := 0; i < v.NumField(); i++ {
tt := t.Field(i)
vv := v.Field(i)
if vv.Kind() == reflect.Struct {
loadStruct(tt.Type, vv)
} else {
set(tt, vv)
}
}
}
func set(field reflect.StructField, value reflect.Value) {
// TODO, ensure value is set-able
s := getString(field)
// Set value based on type
// TODO, handle more than strings!
switch value.Kind() {
case reflect.String:
value.SetString(s)
default:
// TODO, error instead of logging
log.Printf("%v field of type '%v' cannot be set. Defaulting to zero value",
field.Name, field.Type)
}
}
func getString(field reflect.StructField) string {
if envKey := field.Tag.Get("env"); envKey != "" {
if env := os.Getenv(envKey); env != "" {
return env
}
}
if d := field.Tag.Get("default"); d != "" {
return d
}
return ""
}