-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
334 lines (280 loc) · 7.31 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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package config
import (
"encoding/json"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
)
var (
ErrNotPointer = errors.New("should be a pointer")
ErrNotStruct = errors.New("should be a structure")
)
var (
unixEpochTime = time.Unix(0, 0)
timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
durationType = reflect.TypeOf((*time.Duration)(nil)).Elem()
durationCustomType = reflect.TypeOf((*Duration)(nil)).Elem()
)
const (
envConfigTag = "envconfig"
envPrefixTag = "envprefix"
defaultTag = "default"
)
// Init reads and init configuration to `config` variable, which must be a reference of struct
func Init(config interface{}, filename string) error {
v := reflect.ValueOf(config)
if v.Kind() != reflect.Ptr {
return ErrNotPointer
}
v = reflect.Indirect(v)
if v.Kind() != reflect.Struct {
return ErrNotStruct
}
if err := applyDefault(reflect.StructField{}, v); err != nil {
return fmt.Errorf("init config with default values: %s", err)
}
if err := applyJSONConfig(config, filename); err != nil {
return err
}
if err := applyEnv(v); err != nil {
return err
}
return validate(v)
}
func validate(v reflect.Value) error {
t := v.Type()
var invalidFields []string
for i := 0; i < v.NumField(); i++ {
invalidFields = append(invalidFields, validateField(t.Field(i), v.Field(i))...)
}
if len(invalidFields) > 0 {
return fmt.Errorf("required fields: %v are not filled up. Please check configuration", invalidFields)
}
return nil
}
func validateField(t reflect.StructField, v reflect.Value) (invalidFields []string) {
if v.Kind() == reflect.Struct && !isTime(v.Type()) {
for i := 0; i < v.NumField(); i++ {
invalidFields = append(invalidFields, validateField(v.Type().Field(i), v.Field(i))...)
}
return invalidFields
}
value, ok := t.Tag.Lookup("required")
if !ok || !isTrue(value) {
return invalidFields
}
if isZero(v) {
invalidFields = append(invalidFields, t.Name)
}
return invalidFields
}
// applyDefault recursively sets values to default
func applyDefault(t reflect.StructField, v reflect.Value) error {
if v.Kind() == reflect.Struct && !isTime(v.Type()) {
for i := 0; i < v.NumField(); i++ {
if err := applyDefault(v.Type().Field(i), v.Field(i)); err != nil {
return err
}
}
return nil
}
value, ok := t.Tag.Lookup(defaultTag)
if !ok {
return nil
}
return setValue(v, value)
}
// setValue sets value depend on type
func setValue(v reflect.Value, value string) error {
switch indirectType(v.Type()) {
case timeType:
return setTime(&v, value)
case durationType:
return setTimeDuration(&v, value)
case durationCustomType:
return setDuration(&v, value)
}
switch v.Kind() {
case reflect.String:
v.SetString(value)
case reflect.Slice:
setSlice(&v, value)
case reflect.Int, reflect.Int32, reflect.Int64:
return setInt(&v, value)
case reflect.Uint, reflect.Uint32, reflect.Uint64:
return setUint(&v, value)
case reflect.Bool:
setBool(&v, value)
}
return nil
}
func applyJSONConfig(config interface{}, filename string) error {
if len(filename) == 0 {
return nil
}
file, err := os.Open(filepath.Clean(filename))
if err != nil {
return err
}
defer file.Close()
return json.NewDecoder(file).Decode(config)
}
func applyEnv(v reflect.Value) error {
for i := 0; i < v.NumField(); i++ {
err := applyEnvValue(v.Type().Field(i), v.Field(i))
if err != nil {
return err
}
}
return nil
}
func applyEnvValue(t reflect.StructField, v reflect.Value) error {
switch indirectType(v.Type()).Kind() {
case reflect.Slice:
if value, ok := t.Tag.Lookup(envPrefixTag); ok {
return applyEnvOverridesToSlice(value, v)
}
}
if v.Kind() == reflect.Struct && !isTime(v.Type()) {
for i := 0; i < v.NumField(); i++ {
err := applyEnvValue(v.Type().Field(i), v.Field(i))
if err != nil {
return err
}
}
return nil
}
value, ok := t.Tag.Lookup(envConfigTag)
if !ok {
return nil
}
value, found := lookupEnv(value)
if !found {
return nil
}
return setValue(v, value)
}
func setTime(v *reflect.Value, value string) error {
date, err := time.Parse(time.RFC3339, value)
if err != nil {
return fmt.Errorf("failed to parse value %q as time.Time type", value)
}
if v.Kind() == reflect.Ptr {
v.Set(reflect.ValueOf(&date))
} else {
v.Set(reflect.ValueOf(date))
}
return nil
}
func setTimeDuration(v *reflect.Value, value string) error {
duration, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("failed to parse value %q as time.Duration type", value)
}
if v.Kind() == reflect.Ptr {
v.Set(reflect.ValueOf(&duration))
} else {
v.Set(reflect.ValueOf(duration))
}
return nil
}
func setDuration(v *reflect.Value, value string) error {
duration, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("failed to parse value %q as Duration type", value)
}
if v.Kind() == reflect.Ptr {
d := Duration(duration)
v.Set(reflect.ValueOf(&d))
} else {
v.Set(reflect.ValueOf(Duration(duration)))
}
return nil
}
func setInt(v *reflect.Value, value string) error {
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse value %q as Int64 type", value)
}
v.SetInt(intValue)
return nil
}
func setUint(v *reflect.Value, value string) error {
uintValue, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse value %q as Uint64 type", value)
}
v.SetUint(uintValue)
return nil
}
func setBool(v *reflect.Value, value string) {
v.SetBool(isTrue(value))
}
func setSlice(v *reflect.Value, value string) {
if _, ok := v.Interface().([]string); !ok {
return
}
values := strings.Split(value, ",")
slice := reflect.MakeSlice(reflect.TypeOf([]string{}), len(values), len(values))
for i, value := range values {
slice.Index(i).SetString(value)
}
v.Set(slice)
}
func isTrue(value string) bool {
return value == "1" || strings.ToLower(value) == "true"
}
func isTime(t reflect.Type) bool {
return indirectType(t) == timeType
}
func isZeroTime(date time.Time) bool {
return date.IsZero() || date.Equal(unixEpochTime)
}
func isZero(v reflect.Value) bool {
switch v.Type() {
case timeType:
return isZeroTime(v.Interface().(time.Time))
case durationType:
return v.Interface().(time.Duration).Nanoseconds() == 0
case durationCustomType:
return time.Duration(v.Interface().(Duration)).Nanoseconds() == 0
}
switch v.Kind() {
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return math.Float64bits(v.Float()) == 0
case reflect.Interface, reflect.Ptr, reflect.Slice:
return v.IsNil()
case reflect.String:
return v.Len() == 0
}
zero := reflect.Zero(v.Type())
return reflect.DeepEqual(v.Interface(), zero.Interface())
}
// indirectWalk walks through Value to the last Value in chain
func indirectWalk(v reflect.Value) (rv reflect.Value) {
for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
if v.IsNil() {
return v
}
}
return v
}
// indirectType as reflect.Indirect but for Type
func indirectType(v reflect.Type) reflect.Type {
for v.Kind() != reflect.Ptr {
return v
}
return v.Elem()
}