git.iko.soy/typeable/oauth2-proxy
on master help sign in
Allow embedded structs in env_options
commit2da89f842569ee0cd631bbd006cfa511bc82e018 authorJoel Speed <Joel.speed@hotmail.co.uk> dateSun 5 May 2019, 19:12 (7 years ago) parent14d5599
2 files changed+41−8
env_options.go+15−2 env_options_test.go+26−6
env_options.go+15−2
@@ -15,14 +15,27 @@ type EnvOptions map[string]interface{}
1515// Fields in the options struct must have an `env` and `cfg` tag to be read
1616// from the environment
1717func (cfg EnvOptions) LoadEnvForStruct(options interface{}) {
18− val := reflect.ValueOf(options).Elem()
19− typ := val.Type()
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+ }
25+
2026 for i := 0; i < typ.NumField(); i++ {
2127 // pull out the struct tags:
2228 // flag - the name of the command line flag
2329 // deprecated - (optional) the name of the deprecated command line flag
2430 // cfg - (optional, defaults to underscored flag) the name of the config file option
2531 field := typ.Field(i)
32+ fieldV := reflect.Indirect(val).Field(i)
33+
34+ if field.Type.Kind() == reflect.Struct && field.Anonymous {
35+ cfg.LoadEnvForStruct(fieldV.Interface())
36+ continue
37+ }
38+
2639 flagName := field.Tag.Get("flag")
2740 envName := field.Tag.Get("env")
2841 cfgName := field.Tag.Get("cfg")
env_options_test.go+26−6
@@ -1,26 +1,46 @@
1−package main
1+package main_test
22
33import (
44 "os"
55 "testing"
66
7+ proxy "github.com/pusher/oauth2_proxy"
78 "github.com/stretchr/testify/assert"
89)
910
10−type envTest struct {
11− testField string `cfg:"target_field" env:"TEST_ENV_FIELD"`
11+type EnvTest struct {
12+ TestField string `cfg:"target_field" env:"TEST_ENV_FIELD"`
13+ EnvTestEmbed
14+}
15+
16+type EnvTestEmbed struct {
17+ TestFieldEmbed string `cfg:"target_field_embed" env:"TEST_ENV_FIELD_EMBED"`
1218}
1319
1420func TestLoadEnvForStruct(t *testing.T) {
1521
16− cfg := make(EnvOptions)
17− cfg.LoadEnvForStruct(&envTest{})
22+ cfg := make(proxy.EnvOptions)
23+ cfg.LoadEnvForStruct(&EnvTest{})
1824
1925 _, ok := cfg["target_field"]
2026 assert.Equal(t, ok, false)
2127
2228 os.Setenv("TEST_ENV_FIELD", "1234abcd")
23− cfg.LoadEnvForStruct(&envTest{})
29+ cfg.LoadEnvForStruct(&EnvTest{})
2430 v := cfg["target_field"]
2531 assert.Equal(t, v, "1234abcd")
2632}
33+
34+func TestLoadEnvForStructWithEmbeddedFields(t *testing.T) {
35+
36+ cfg := make(proxy.EnvOptions)
37+ cfg.LoadEnvForStruct(&EnvTest{})
38+
39+ _, ok := cfg["target_field_embed"]
40+ assert.Equal(t, ok, false)
41+
42+ os.Setenv("TEST_ENV_FIELD_EMBED", "1234abcd")
43+ cfg.LoadEnvForStruct(&EnvTest{})
44+ v := cfg["target_field_embed"]
45+ assert.Equal(t, v, "1234abcd")
46+}