oauth2_proxy/env_options.go

55 lines
1.4 KiB
Go
Raw Permalink Normal View History

2014-11-10 02:07:02 +00:00
package main
import (
"os"
"reflect"
"strings"
)
// EnvOptions holds program options loaded from the process environment
2014-11-15 04:06:07 +00:00
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
2014-11-15 04:06:07 +00:00
func (cfg EnvOptions) LoadEnvForStruct(options interface{}) {
2019-05-05 18:12:36 +00:00
val := reflect.ValueOf(options)
var typ reflect.Type
if val.Kind() == reflect.Ptr {
typ = val.Elem().Type()
} else {
typ = val.Type()
}
2014-11-10 02:07:02 +00:00
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)
2019-05-05 18:12:36 +00:00
fieldV := reflect.Indirect(val).Field(i)
if field.Type.Kind() == reflect.Struct && field.Anonymous {
cfg.LoadEnvForStruct(fieldV.Interface())
continue
}
2014-11-10 02:07:02 +00:00
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
}
}
}