-
Notifications
You must be signed in to change notification settings - Fork 12
/
load.go
201 lines (174 loc) · 4.79 KB
/
load.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package configuro
import (
"encoding/json"
"fmt"
"os"
"reflect"
"regexp"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
)
// Load load config into supported struct.
func (c *Config) Load(configStruct interface{}) error {
return c.loadInternal("", configStruct)
}
// Load load config with key into supported struct.
func (c *Config) LoadKey(key string, configStruct interface{}) error {
return c.loadInternal(key, configStruct)
}
func (c *Config) loadInternal(key string, configStruct interface{}) error {
var err error
// Bind Env Vars
if c.envLoad {
c.bindAllEnvsWithPrefix()
}
if c.configFileLoad {
err := c.viper.ReadInConfig()
if err != nil {
pathErr, ok := err.(*os.PathError)
if !ok {
return fmt.Errorf("error reading config data: %v", err)
}
if c.configFileErrIfNotFound && pathErr.Op == "open" {
return fmt.Errorf("error config file not found. err: %v", err)
}
}
}
// Unmarshalling
if key == "" {
err = c.viper.Unmarshal(configStruct, c.decodeHook, setTagName(c.tag))
} else {
err = c.viper.UnmarshalKey(key, configStruct, c.decodeHook, setTagName(c.tag))
}
if err != nil {
return fmt.Errorf("error unmarshalling config: %v", err)
}
return nil
}
func (c *Config) bindAllEnvsWithPrefix() {
envKVRegex := regexp.MustCompile("^" + c.envPrefix + "_" + "(.*)=.*$")
Envvars := os.Environ()
for _, env := range Envvars {
match := envKVRegex.FindSubmatch([]byte(env))
if match != nil {
matchUnescaper := strings.NewReplacer("__", "_", "_", ".")
matchUnescaped := matchUnescaper.Replace(string(match[1]))
err := c.viper.BindEnv(matchUnescaped)
if err != nil {
//Should never happen tho.
panic(err)
}
}
}
}
func setTagName(hook string) viper.DecoderConfigOption {
return func(c *mapstructure.DecoderConfig) {
c.TagName = hook
}
}
// StringJSONArrayOrSlicesToConfig will convert Json Encoded Strings to Maps or Slices, Used Primarily to support Slices and Maps in Environment variables
func stringJSONArrayToSlice() func(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) {
return func(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
if f != reflect.String || t != reflect.Slice {
return data, nil
}
raw := data.(string)
if raw == "" {
return []string{}, nil
}
var ret interface{}
if t == reflect.Slice {
jsonArray := make([]interface{}, 0)
err := json.Unmarshal([]byte(raw), &jsonArray)
if err != nil {
// Try comma separated format too
val, err := mapstructure.StringToSliceHookFunc(",").(func(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error))(f, t, data)
if err != nil {
return val, err
}
ret = val
} else {
ret = jsonArray
}
}
return ret, nil
}
}
func stringJSONObjToMap() func(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) {
return func(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
if f != reflect.String || t != reflect.Map {
return data, nil
}
raw := data.(string)
if raw == "" {
return []string{}, nil
}
var ret interface{}
jsonMap := make(map[string]interface{})
err := json.Unmarshal([]byte(raw), &jsonMap)
if err != nil {
return raw, fmt.Errorf("couldn't map string-ifed Json to Map: %s", err.Error())
}
ret = jsonMap
return ret, nil
}
}
func stringJSONObjToStruct() func(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) {
return func(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
if f != reflect.String || t != reflect.Struct {
return data, nil
}
raw := data.(string)
if raw == "" {
return []string{}, nil
}
var ret interface{}
err := json.Unmarshal([]byte(raw), &data)
if err != nil {
return raw, fmt.Errorf("couldn't map string-ifed Json to Object: %s", err.Error())
}
ret = data
return ret, nil
}
}
func expandEnvVariablesWithDefaults() func(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) {
var configWithEnvExpand = regexp.MustCompile(`(\${([\w@.]+)(\|([\w@.:,]+)?)?})`)
var exactMatchEnvExpand = regexp.MustCompile(`^` + configWithEnvExpand.String() + `$`)
return func(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
if f != reflect.String {
return data, nil
}
raw := data.(string)
ret := configWithEnvExpand.ReplaceAllStringFunc(raw, func(s string) string {
matches := exactMatchEnvExpand.FindAllStringSubmatch(s, -1)
if matches == nil {
return s
}
envKey := matches[0][2]
isEnvDefaultSet := matches[0][3] != ""
envDefault := matches[0][4]
envValue, found := os.LookupEnv(envKey)
if !found {
if isEnvDefaultSet {
return envDefault
}
return s
}
return envValue
})
return ret, nil
}
}