-
Notifications
You must be signed in to change notification settings - Fork 2
/
env_options.go
41 lines (38 loc) · 1.16 KB
/
env_options.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
package main
import (
"os"
"reflect"
"strings"
)
// EnvOptions holds program options loaded from the process environment
type EnvOptions map[string]interface{}
// LoadEnvForStruct loads environment variables for each field in an options
// struct passed into it.
//
// Fields in the options struct must have an `env` and `cfg` tag to be read
// from the environment
func (cfg EnvOptions) LoadEnvForStruct(options interface{}) {
val := reflect.ValueOf(options).Elem()
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
// pull out the struct tags:
// flag - the name of the command line flag
// deprecated - (optional) the name of the deprecated command line flag
// cfg - (optional, defaults to underscored flag) the name of the config file option
field := typ.Field(i)
flagName := field.Tag.Get("flag")
envName := field.Tag.Get("env")
cfgName := field.Tag.Get("cfg")
if cfgName == "" && flagName != "" {
cfgName = strings.Replace(flagName, "-", "_", -1)
}
if envName == "" || cfgName == "" {
// resolvable fields must have the `env` and `cfg` struct tag
continue
}
v := os.Getenv(envName)
if v != "" {
cfg[cfgName] = v
}
}
}