git.iko.soy/typeable/oauth2-proxy
on v5.0.0 help sign in
typeable/oauth2-proxy/env_options.go
54 lines 1.4 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)
19 var typ reflect.Type
20 if val.Kind() == reflect.Ptr {
21 typ = val.Elem().Type()
22 } else {
23 typ = val.Type()
24 }
26 for i := 0; i < typ.NumField(); i++ {
27 // pull out the struct tags:
28 // flag - the name of the command line flag
29 // deprecated - (optional) the name of the deprecated command line flag
30 // cfg - (optional, defaults to underscored flag) the name of the config file option
31 field := typ.Field(i)
32 fieldV := reflect.Indirect(val).Field(i)
34 if field.Type.Kind() == reflect.Struct && field.Anonymous {
35 cfg.LoadEnvForStruct(fieldV.Interface())
36 continue
37 }
39 flagName := field.Tag.Get("flag")
40 envName := field.Tag.Get("env")
41 cfgName := field.Tag.Get("cfg")
42 if cfgName == "" && flagName != "" {
43 cfgName = strings.ReplaceAll(flagName, "-", "_")
44 }
45 if envName == "" || cfgName == "" {
46 // resolvable fields must have the `env` and `cfg` struct tag
47 continue
48 }
49 v := os.Getenv(envName)
50 if v != "" {
51 cfg[cfgName] = v
52 }
53 }