Skip to content
This repository has been archived by the owner on Jan 24, 2019. It is now read-only.

Commit

Permalink
test/fix environment var parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
jehiah committed Nov 15, 2014
1 parent d552eff commit 1c5a01c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
4 changes: 3 additions & 1 deletion env_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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++ {
Expand Down
26 changes: 26 additions & 0 deletions env_options_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 1c5a01c

Please sign in to comment.