Skip to content

Commit

Permalink
Fix default values filling.
Browse files Browse the repository at this point in the history
  • Loading branch information
onrik committed Jun 21, 2023
1 parent 7239e9c commit 79377ad
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
8 changes: 8 additions & 0 deletions default.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,18 @@ func setDefaultValue(v reflect.Value) error {
}
defaultValue := parts[1]

if f.Type.Kind() == reflect.Ptr {
if f.Type.Elem().Kind() == reflect.String {
v.Field(i).Set(reflect.ValueOf(&defaultValue))
continue
}
}

if f.Type.Kind() == reflect.String {
v.Field(i).Set(reflect.ValueOf(defaultValue))
continue
}

if f.Type.Kind() == reflect.Bool {
value, err := strconv.ParseBool(defaultValue)
if err != nil {
Expand Down
9 changes: 7 additions & 2 deletions default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import (

func TestFillDefaultValues(t *testing.T) {
config := &struct {
PID uint `yaconf:"default=90"`
LogLevel string `yaconf:"default=debug"`
PID uint `yaconf:"default=90"`
LogLevel string `yaconf:"default=debug"`
Str string `yaconf:"default=111"`
StrPtr *string `yaconf:"default=222"`
DB struct {
Host string `yaconf:"default=localhost"`
Port int `yaconf:"default=5432"`
Expand All @@ -28,6 +30,9 @@ func TestFillDefaultValues(t *testing.T) {
require.Equal(t, 5432, config.DB.Port)
require.Equal(t, 2*time.Second, config.DB.Timeout)
require.Equal(t, true, config.DB.Debug)
require.NotNil(t, config.StrPtr)
require.Equal(t, "222", *config.StrPtr)
require.Equal(t, "111", config.Str)

// Test empty
config2 := &struct {
Expand Down
4 changes: 2 additions & 2 deletions yaconf.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ func Read(filename string, config interface{}) error {
return err
}

err = yaml.Unmarshal(data, config)
err = fillDefaultValues(config)
if err != nil {
return err
}

err = fillDefaultValues(config)
err = yaml.Unmarshal(data, config)
if err != nil {
return err
}
Expand Down

0 comments on commit 79377ad

Please sign in to comment.