-
Notifications
You must be signed in to change notification settings - Fork 0
/
viper.go
67 lines (55 loc) · 1.31 KB
/
viper.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
package viper
import (
"reflect"
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
func Load(confPath string, receiver interface{}) {
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AddConfigPath(".")
viper.SetConfigName("config")
viper.SetConfigType("yml")
configType := "default"
if confPath != "" {
viper.SetConfigFile(confPath)
configType = "supplied"
}
err := viper.ReadInConfig()
if err != nil {
log.WithError(err).Fatalf("Read %s config", configType)
}
log.WithFields(log.Fields{"config": viper.ConfigFileUsed()}).Infof("Viper using %s config", configType)
bindEnvs(reflect.ValueOf(receiver))
if err := viper.Unmarshal(receiver); err != nil {
log.Panic(err, "Error Unmarshal Viper Config File")
}
}
//nolint:exhaustive
func bindEnvs(v reflect.Value, parts ...string) {
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return
}
bindEnvs(v.Elem(), parts...)
return
}
ift := v.Type()
for i := 0; i < ift.NumField(); i++ {
val := v.Field(i)
t := ift.Field(i)
tv, ok := t.Tag.Lookup("mapstructure")
if !ok {
continue
}
switch val.Kind() {
case reflect.Struct:
bindEnvs(val, append(parts, tv)...)
default:
if err := viper.BindEnv(strings.Join(append(parts, tv), ".")); err != nil {
log.Fatal(err)
}
}
}
}