Skip to content

Commit 1c5a01c

Browse files
committed
test/fix environment var parsing
1 parent d552eff commit 1c5a01c

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

env_options.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ import (
66
"strings"
77
)
88

9-
func LoadOptionsFromEnv(options interface{}, cfg map[string]interface{}) {
9+
type EnvOptions map[string]interface{}
10+
11+
func (cfg EnvOptions) LoadEnvForStruct(options interface{}) {
1012
val := reflect.ValueOf(options).Elem()
1113
typ := val.Type()
1214
for i := 0; i < typ.NumField(); i++ {

env_options_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package main
2+
3+
import (
4+
"os"
5+
"testing"
6+
7+
"github.com/bmizerany/assert"
8+
)
9+
10+
type envTest struct {
11+
testField string `cfg:"target_field" env:"TEST_ENV_FIELD"`
12+
}
13+
14+
func TestLoadEnvForStruct(t *testing.T) {
15+
16+
cfg := make(EnvOptions)
17+
cfg.LoadEnvForStruct(&envTest{})
18+
19+
_, ok := cfg["target_field"]
20+
assert.Equal(t, ok, false)
21+
22+
os.Setenv("TEST_ENV_FIELD", "1234abcd")
23+
cfg.LoadEnvForStruct(&envTest{})
24+
v := cfg["target_field"]
25+
assert.Equal(t, v, "1234abcd")
26+
}

main.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,14 @@ func main() {
4848

4949
opts := NewOptions()
5050

51-
var cfg map[string]interface{}
51+
cfg := make(EnvOptions)
5252
if *config != "" {
5353
_, err := toml.DecodeFile(*config, &cfg)
5454
if err != nil {
5555
log.Fatalf("ERROR: failed to load config file %s - %s", *config, err)
5656
}
5757
}
58-
LoadOptionsFromEnv(opts, cfg)
58+
cfg.LoadEnvForStruct(opts)
5959
options.Resolve(opts, flagSet, cfg)
6060

6161
err := opts.Validate()

0 commit comments

Comments
 (0)