-
Notifications
You must be signed in to change notification settings - Fork 0
/
env-tag.go
45 lines (39 loc) · 944 Bytes
/
env-tag.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
package cidsdk
import (
"os"
"reflect"
"strconv"
)
const envVarTag = "env"
// OverwriteFromEnv will overwrite values with the given env values if present
func OverwriteFromEnv(data interface{}) {
val := reflect.ValueOf(data).Elem()
t := val.Type()
// check if the type passed in is a struct
if t.Kind() != reflect.Struct {
return
}
// iterate over all fields of the struct
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
tag := field.Tag.Get(envVarTag)
if tag == "" {
continue
}
if envVal, isSet := os.LookupEnv(tag); isSet {
fieldVal := val.Field(i)
switch fieldVal.Kind() {
case reflect.String:
fieldVal.SetString(envVal)
case reflect.Int:
valAsInt, _ := strconv.Atoi(envVal)
fieldVal.Set(reflect.ValueOf(valAsInt))
case reflect.Bool:
valAsBool, _ := strconv.ParseBool(envVal)
fieldVal.Set(reflect.ValueOf(valAsBool))
default:
// unsupported type
}
}
}
}