github.com/pusher/oauth2_proxy@v3.2.0+incompatible/env_options.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  	"reflect"
     6  	"strings"
     7  )
     8  
     9  // EnvOptions holds program options loaded from the process environment
    10  type EnvOptions map[string]interface{}
    11  
    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
    17  func (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  	}
    41  }