git.iko.soy/typeable/oauth2-proxy
on v3.2.0 help sign in
typeable/oauth2-proxy/env_options.go
41 lines 1.2 kB history raw
1package main
3import (
4 "os"
5 "reflect"
6 "strings"
7)
9// EnvOptions holds program options loaded from the process environment
10type EnvOptions map[string]interface{}
12// LoadEnvForStruct loads environment variables for each field in an options
13// struct passed into it.
14//
15// Fields in the options struct must have an `env` and `cfg` tag to be read
16// from the environment
17func (cfg EnvOptions) LoadEnvForStruct(options interface{}) {
18 val := reflect.ValueOf(options).Elem()
19 typ := val.Type()
20 for i := 0; i < typ.NumField(); i++ {
21 // pull out the struct tags:
22 // flag - the name of the command line flag
23 // deprecated - (optional) the name of the deprecated command line flag
24 // cfg - (optional, defaults to underscored flag) the name of the config file option
25 field := typ.Field(i)
26 flagName := field.Tag.Get("flag")
27 envName := field.Tag.Get("env")
28 cfgName := field.Tag.Get("cfg")
29 if cfgName == "" && flagName != "" {
30 cfgName = strings.Replace(flagName, "-", "_", -1)
31 }
32 if envName == "" || cfgName == "" {
33 // resolvable fields must have the `env` and `cfg` struct tag
34 continue
35 }
36 v := os.Getenv(envName)
37 if v != "" {
38 cfg[cfgName] = v
39 }
40 }