Skip to content

Commit

Permalink
Fix read config from env
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Jun 12, 2019
1 parent 6c4ae88 commit 68b90fa
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
28 changes: 28 additions & 0 deletions configor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,31 @@ func TestSliceFromEnv(t *testing.T) {
t.Fatalf("unexpected result:%+v", result)
}
}

func TestConfigFromEnv(t *testing.T) {
type config struct {
LineBreakString string `required:"true"`
Count int64
Slient bool
}

cfg := &config{}

os.Setenv("CONFIGOR_ENV_PREFIX", "CONFIGOR")
os.Setenv("CONFIGOR_LineBreakString", "Line one\nLine two\nLine three\nAnd more lines")
os.Setenv("CONFIGOR_Slient", "1")
os.Setenv("CONFIGOR_Count", "10")
Load(cfg)

if os.Getenv("CONFIGOR_LineBreakString") != cfg.LineBreakString {
t.Error("Failed to load value has line break from env")
}

if !cfg.Slient {
t.Error("Failed to load bool from env")
}

if cfg.Count != 10 {
t.Error("Failed to load number from env")
}
}
17 changes: 15 additions & 2 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,21 @@ func (configor *Configor) processTags(config interface{}, prefixes ...string) er
if configor.Config.Debug || configor.Config.Verbose {
fmt.Printf("Loading configuration for struct `%v`'s field `%v` from env %v...\n", configType.Name(), fieldStruct.Name, env)
}
if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil {
return err

switch reflect.Indirect(field).Kind() {
case reflect.Bool:
switch strings.ToLower(value) {
case "", "0", "f", "false":
field.Set(reflect.ValueOf(false))
default:
field.Set(reflect.ValueOf(true))
}
case reflect.String:
field.Set(reflect.ValueOf(value))
default:
if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil {
return err
}
}
break
}
Expand Down

0 comments on commit 68b90fa

Please sign in to comment.