diff --git a/default.go b/default.go index 1edb260..c55f95a 100644 --- a/default.go +++ b/default.go @@ -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 { diff --git a/default_test.go b/default_test.go index 9f90838..9d0b856 100644 --- a/default_test.go +++ b/default_test.go @@ -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"` @@ -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 { diff --git a/yaconf.go b/yaconf.go index c4ba006..613d110 100644 --- a/yaconf.go +++ b/yaconf.go @@ -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 }