test/fix environment var parsing

This commit is contained in:
Jehiah Czebotar 2014-11-14 23:06:07 -05:00
parent d552effc1e
commit 1c5a01cb7b
3 changed files with 31 additions and 3 deletions

View File

@ -6,7 +6,9 @@ import (
"strings" "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() val := reflect.ValueOf(options).Elem()
typ := val.Type() typ := val.Type()
for i := 0; i < typ.NumField(); i++ { for i := 0; i < typ.NumField(); i++ {

26
env_options_test.go Normal file
View File

@ -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")
}

View File

@ -48,14 +48,14 @@ func main() {
opts := NewOptions() opts := NewOptions()
var cfg map[string]interface{} cfg := make(EnvOptions)
if *config != "" { if *config != "" {
_, err := toml.DecodeFile(*config, &cfg) _, err := toml.DecodeFile(*config, &cfg)
if err != nil { if err != nil {
log.Fatalf("ERROR: failed to load config file %s - %s", *config, err) log.Fatalf("ERROR: failed to load config file %s - %s", *config, err)
} }
} }
LoadOptionsFromEnv(opts, cfg) cfg.LoadEnvForStruct(opts)
options.Resolve(opts, flagSet, cfg) options.Resolve(opts, flagSet, cfg)
err := opts.Validate() err := opts.Validate()