-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
65 lines (56 loc) · 1.34 KB
/
config.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
package copperhead
import (
"reflect"
"strings"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
type ConfigOptions struct {
EnvPrefix string
}
func Unmarshal(cfg interface{}, t reflect.Type, options ConfigOptions) (err error) {
var cfgPath string
pflag.StringVar(&cfgPath, "config", "config.yaml", "Path to config file")
initViper(t)
pflag.Parse()
viper.SetConfigFile(cfgPath)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "__"))
viper.SetEnvPrefix(options.EnvPrefix)
viper.AutomaticEnv()
err = viper.ReadInConfig()
err = viper.Unmarshal(&cfg)
return
}
func initViper(rt reflect.Type, parts ...string) {
for i := 0; i < rt.NumField(); i++ {
t := rt.Field(i)
tv, ok := t.Tag.Lookup("mapstructure")
if !ok {
continue
}
switch t.Type.Kind() {
case reflect.Struct: // Handle nested struct
if tv == ",squash" || tv == "" {
initViper(t.Type, parts...)
} else {
initViper(t.Type, append(parts, tv)...)
}
default: // Handle leaf field
keyPath := strings.Join(append(parts, tv), ".")
viper.SetDefault(keyPath, t.Tag.Get("default"))
cliFlag := t.Tag.Get("cli")
if cliFlag == "" {
cliFlag = strings.ReplaceAll(keyPath, "_", "-")
}
pflag.String(
cliFlag,
t.Tag.Get("default"),
t.Tag.Get("description"),
)
viper.BindPFlag(
keyPath,
pflag.Lookup(cliFlag),
)
}
}
}