-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
80 lines (65 loc) · 1.77 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package config
import (
"fmt"
"os"
"strings"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
type flagOpt struct {
optName string
optDefaultValue interface{}
optUsage string
}
var c Config
func init() {
// flag priority: cli > envvars > config > defaults
for _, opt := range flagsOpts {
viper.SetDefault(opt.optName, opt.optDefaultValue)
}
viper.SetConfigType("yaml")
viper.SetConfigName(SERVICE_NAME)
viper.AddConfigPath(fmt.Sprintf("/etc/%s/", SERVICE_NAME)) // path to look for the config file in
viper.AddConfigPath(fmt.Sprintf("$HOME/.%s/", SERVICE_NAME)) // call multiple times to add many search paths
viper.AddConfigPath("./etc/")
viper.AddConfigPath(".")
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
fmt.Fprintf(os.Stderr, "Fatal error config file: %s \n", err)
}
viper.SetEnvPrefix(SERVICE_NAME)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
for _, opt := range flagsOpts {
switch opt.optDefaultValue.(type) {
case int:
pflag.Int(opt.optName, opt.optDefaultValue.(int), opt.optUsage)
case string:
pflag.String(opt.optName, opt.optDefaultValue.(string), opt.optUsage)
case bool:
pflag.Bool(opt.optName, opt.optDefaultValue.(bool), opt.optUsage)
case []interface{}:
continue
default:
continue
}
}
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
err = viper.Unmarshal(&c)
if err != nil {
fmt.Fprintf(os.Stderr, "unable to decode into struct, %v\n", err)
}
}
func GetString(key string) string {
return viper.GetString(key)
}
func GetInt(key string) int {
return viper.GetInt(key)
}
func GetBool(key string) bool {
return viper.GetBool(key)
}
func GetConfig() *Config {
return &c
}