-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
87 lines (74 loc) · 1.59 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
81
82
83
84
85
86
87
package config
/**
TODO: implement loading config from flags
*/
import (
"errors"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"os"
"reflect"
"strings"
)
var (
InvalidEnvPrefix = errors.New("invalid env prefix")
)
type AppConfig struct {
envPrefix string
defaults []DefaultValue
}
func NewAppConfig(envPrefix string, defaults []DefaultValue) *AppConfig {
return &AppConfig{
envPrefix: envPrefix,
defaults: defaults,
}
}
type DefaultValue struct {
Name string
Flag string
Value interface{}
}
func (r *AppConfig) InitializeAppConfig() error {
if len(r.envPrefix) == 0 {
return InvalidEnvPrefix
}
viper.SetEnvPrefix(r.envPrefix)
viper.AutomaticEnv()
pflag.Parse()
if r.defaults != nil {
for _, value := range r.defaults {
viper.SetDefault(value.Name, value.Value)
}
}
return nil
}
func (r *AppConfig) GetConfigValues(s interface{}) error {
return viper.Unmarshal(s)
}
func ExtractConfigValues(config interface{}) ([]DefaultValue, error) {
confType := reflect.TypeOf(config).Elem()
numFields := confType.NumField()
res := make([]DefaultValue, 0, numFields)
for i := 0; i < numFields; i++ {
field := confType.Field(i)
if field.Anonymous {
continue
}
envVariableName := field.Tag.Get("mapstructure")
defaultValue := field.Tag.Get("default")
flagName := field.Tag.Get("flag")
res = append(res, DefaultValue{
Name: envVariableName,
Flag: flagName,
Value: defaultValue,
})
}
return res, nil
}
func IsDevelopment() bool {
de := os.Getenv("development")
if strings.Compare(strings.ToLower(de), "true") == 0 {
return true
}
return false
}