configor
configor copied to clipboard
Bug: when struct has pointer to other struct, processDefaults is not working
Hot to Reproduce
Change the test case
func TestDefaultValue(t *testing.T) {
config := generateDefaultConfig()
config.APPName = ""
config.DB.Port = 0
config.DB.SSL = false
if bytes, err := json.Marshal(config); err == nil {
if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
defer file.Close()
defer os.Remove(file.Name())
file.Write(bytes)
var result testConfig
Load(&result, file.Name())
if !reflect.DeepEqual(result, generateDefaultConfig()) {
t.Errorf("result should be set default value correctly")
}
}
} else {
t.Errorf("failed to marshal config")
}
}
** using a pointer to Database**
type Anonymous struct {
Description string
}
type Database struct {
Name string
User string `yaml:",omitempty" default:"root"`
Password string `required:"true" env:"DBPassword"`
Port uint `default:"3306" yaml:",omitempty" json:",omitempty"`
SSL bool `default:"true" yaml:",omitempty" json:",omitempty"`
}
type Contact struct {
Name string
Email string `required:"true"`
}
type testConfig struct {
APPName string `default:"configor" yaml:",omitempty" json:",omitempty"`
Hosts []string
DB *Database
Contacts []Contact
Anonymous `anonymous:"true"`
private string
}
func generateDefaultConfig() testConfig {
return testConfig{
APPName: "configor",
Hosts: []string{"http://example.org", "http://jinzhu.me"},
DB: &Database{
Name: "configor",
User: "configor",
Password: "configor",
Port: 3306,
SSL: true,
},
Contacts: []Contact{
{
Name: "Jinzhu",
Email: "[email protected]",
},
},
Anonymous: Anonymous{
Description: "This is an anonymous embedded struct whose environment variables should NOT include 'ANONYMOUS'",
},
}
}
Root cause
Problem is at https://github.com/jinzhu/configor/blob/master/utils.go#L217
for field.Kind() == reflect.Ptr {
field = field.Elem()
}
after this statement, field.Kind()
becomes invalid.