-
Notifications
You must be signed in to change notification settings - Fork 0
/
envparse.go
347 lines (303 loc) · 8.26 KB
/
envparse.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
335
336
337
338
339
340
341
342
343
344
345
346
347
package envparse
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
)
var (
defaultPrefix = "APP"
defaultMaxDepth = 100
unsetEnv = false
)
// Parse scans through environment variables using mapping provided in interface
func Parse(ptr interface{}, envs []string) error {
env := newEnvMap(defaultPrefix, envs)
// Verify that ptr is a pointer to a struct
interfaceValue := reflect.ValueOf(ptr)
if ptr == nil || interfaceValue.Kind() != reflect.Ptr || interfaceValue.Elem().Kind() != reflect.Struct {
return fmt.Errorf("interface must be a pointer to a struct")
}
structValue := interfaceValue.Elem()
errorList := newErrorList()
structValue.Set(parseStruct(structValue.Type(), env.GetPrefix(defaultPrefix), 0, errorList))
if unsetEnv {
for k := range env {
if strings.HasPrefix(k, defaultPrefix) {
_ = os.Unsetenv(k)
}
}
}
if !errorList.IsEmpty() {
return errorList
}
return nil
}
func parseStruct(structType reflect.Type, env envMap, depth int, errorList *ErrorList) reflect.Value {
result := reflect.New(structType).Elem()
depth++
if depth >= defaultMaxDepth {
errorList.Append(fmt.Errorf("too many levels of embedded structs, currently at depth '%d'", depth))
return result
}
for i := 0; i < result.NumField(); i++ {
fieldValue := result.Field(i)
fieldType := structType.Field(i)
if tagString, ok := fieldType.Tag.Lookup("env"); ok {
if !fieldType.IsExported() {
errorList.Append(fmt.Errorf("field '%s' is not exported, but contains 'env' tag", fieldType.Name))
continue
}
tag, err := parseTag(tagString, fieldType.Name)
if err != nil {
errorList.Append(err)
continue
}
fieldKind := fieldType.Type.Kind()
if fieldKind == reflect.Ptr {
if fieldValue.IsNil() {
fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
}
fieldValue = fieldValue.Elem()
}
if tag.required {
if fieldValue.Type().Kind() == reflect.Struct || fieldValue.Type().Kind() == reflect.Slice {
if !env.PrefixExists(tag.name) {
// if field marked as required, but relevant environment variable is not provided,
// that is parsing error and can skip further processing of this field.
errorList.Append(fmt.Errorf("envvars under '%s' are required, but none provided", fmt.Sprintf("%s", tag.name)))
continue
}
} else {
if !env.Exists(tag.name) {
// if field marked as required, but relevant environment variable is not provided,
// that is parsing error and can skip further processing of this field.
errorList.Append(fmt.Errorf("envvar '%s' is required, but not provided", fmt.Sprintf("%s", tag.name)))
continue
}
}
}
fieldValueString := tag.defaultValue
if env.Exists(tag.name) {
fieldValueString = env.Get(tag.name)
}
err = switchFunc(fieldValue, env.GetPrefix(tag.name), fieldValueString, depth, errorList)
if err != nil {
errorList.Append(fmt.Errorf("error parsing field '%s': %w", fieldType.Name, err))
}
}
}
return result
}
func parseSlice(sliceType reflect.Type, env envMap, depth int, errorList *ErrorList) reflect.Value {
result := reflect.MakeSlice(sliceType, 0, 0)
depth++
if depth >= defaultMaxDepth {
errorList.Append(fmt.Errorf("too many levels of embedded structs, currently at depth '%d'", depth))
return result
}
slicePrefixes := env.GetSlicePrefixes()
if len(slicePrefixes) == 0 {
return result
}
isPtr := false
if sliceType.Elem().Kind() == reflect.Ptr {
isPtr = true
}
makeType := sliceType.Elem()
if isPtr {
makeType = makeType.Elem()
}
var item, assignableItem reflect.Value
for _, slicePrefix := range slicePrefixes {
if isPtr {
item = reflect.New(makeType)
assignableItem = item.Elem()
} else {
item = reflect.New(makeType).Elem()
assignableItem = item
}
valueString := ""
if env.Exists(slicePrefix) {
valueString = env.Get(slicePrefix)
}
err := switchFunc(assignableItem, env.GetPrefix(slicePrefix), valueString, depth, errorList)
if err != nil {
errorList.Append(fmt.Errorf("error parsing slice: %w", err))
break
}
result = reflect.Append(result, item)
}
return result
}
func parseInt(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseInt(val, 10, 64)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(int(i))
}
func parseInt8(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseInt(val, 10, 8)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(int8(i))
}
func parseInt16(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseInt(val, 10, 16)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(int16(i))
}
func parseInt32(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseInt(val, 10, 32)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(int32(i))
}
func parseInt64(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseInt(val, 10, 64)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(i)
}
func parseUint(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseUint(val, 10, 64)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(uint(i))
}
func parseUint8(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseUint(val, 10, 8)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(uint8(i))
}
func parseUint16(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseUint(val, 10, 16)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(uint16(i))
}
func parseUint32(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseUint(val, 10, 32)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(uint32(i))
}
func parseUint64(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseUint(val, 10, 64)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(i)
}
func parseFloat32(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseFloat(val, 32)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(float32(i))
}
func parseFloat64(val string, errorList *ErrorList) reflect.Value {
if val == "" {
val = "0"
}
i, err := strconv.ParseFloat(val, 64)
if err != nil {
errorList.Append(err)
}
return reflect.ValueOf(i)
}
func parseBool(val string, _ *ErrorList) reflect.Value {
switch strings.ToLower(val) {
case "false", "0", "f", "":
return reflect.ValueOf(false)
default:
return reflect.ValueOf(true)
}
}
func parseString(val string, _ *ErrorList) reflect.Value {
return reflect.ValueOf(val)
}
func switchFunc(value reflect.Value, env envMap, valueString string, depth int, errorList *ErrorList) error {
switch value.Kind() {
case reflect.Int:
value.Set(parseInt(valueString, errorList))
case reflect.Int8:
value.Set(parseInt8(valueString, errorList))
case reflect.Int16:
value.Set(parseInt16(valueString, errorList))
case reflect.Int32:
value.Set(parseInt32(valueString, errorList))
case reflect.Int64:
value.Set(parseInt64(valueString, errorList))
case reflect.Uint:
value.Set(parseUint(valueString, errorList))
case reflect.Uint8:
value.Set(parseUint8(valueString, errorList))
case reflect.Uint16:
value.Set(parseUint16(valueString, errorList))
case reflect.Uint32:
value.Set(parseUint32(valueString, errorList))
case reflect.Uint64:
value.Set(parseUint64(valueString, errorList))
case reflect.Float32:
value.Set(parseFloat32(valueString, errorList))
case reflect.Float64:
value.Set(parseFloat64(valueString, errorList))
case reflect.Bool:
value.Set(parseBool(valueString, errorList))
case reflect.String:
value.Set(parseString(valueString, errorList))
case reflect.Slice:
value.Set(parseSlice(value.Type(), env, depth+1, errorList))
case reflect.Struct:
value.Set(parseStruct(value.Type(), env, depth+1, errorList))
default:
return fmt.Errorf("unsupported type '%s'", value.Kind().String())
}
return nil
}