From 1c5a01cb7bd851059456b0261d6ceafb0398768b Mon Sep 17 00:00:00 2001 From: Jehiah Czebotar Date: Fri, 14 Nov 2014 23:06:07 -0500 Subject: [PATCH] test/fix environment var parsing --- env_options.go | 4 +++- env_options_test.go | 26 ++++++++++++++++++++++++++ main.go | 4 ++-- 3 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 env_options_test.go diff --git a/env_options.go b/env_options.go index 2016ff8..b918428 100644 --- a/env_options.go +++ b/env_options.go @@ -6,7 +6,9 @@ import ( "strings" ) -func LoadOptionsFromEnv(options interface{}, cfg map[string]interface{}) { +type EnvOptions map[string]interface{} + +func (cfg EnvOptions) LoadEnvForStruct(options interface{}) { val := reflect.ValueOf(options).Elem() typ := val.Type() for i := 0; i < typ.NumField(); i++ { diff --git a/env_options_test.go b/env_options_test.go new file mode 100644 index 0000000..354dc42 --- /dev/null +++ b/env_options_test.go @@ -0,0 +1,26 @@ +package main + +import ( + "os" + "testing" + + "github.com/bmizerany/assert" +) + +type envTest struct { + testField string `cfg:"target_field" env:"TEST_ENV_FIELD"` +} + +func TestLoadEnvForStruct(t *testing.T) { + + cfg := make(EnvOptions) + cfg.LoadEnvForStruct(&envTest{}) + + _, ok := cfg["target_field"] + assert.Equal(t, ok, false) + + os.Setenv("TEST_ENV_FIELD", "1234abcd") + cfg.LoadEnvForStruct(&envTest{}) + v := cfg["target_field"] + assert.Equal(t, v, "1234abcd") +} diff --git a/main.go b/main.go index 3f91096..31accf6 100644 --- a/main.go +++ b/main.go @@ -48,14 +48,14 @@ func main() { opts := NewOptions() - var cfg map[string]interface{} + cfg := make(EnvOptions) if *config != "" { _, err := toml.DecodeFile(*config, &cfg) if err != nil { log.Fatalf("ERROR: failed to load config file %s - %s", *config, err) } } - LoadOptionsFromEnv(opts, cfg) + cfg.LoadEnvForStruct(opts) options.Resolve(opts, flagSet, cfg) err := opts.Validate()