I have this method that I feel has code repetition that can be improved but since I am new to Go, I am not quite sure how to improve it. I would appreciate if anyone can give me their opinion.
func (c *Configuration) loadFromEnvVars(key string, target interface{}, optional bool, defaultValue interface{}) error {
err := c.configReader.BindEnv(key)
if err != nil {
if optional {
switch target := target.(type) {
case *string:
*target = defaultValue.(string)
case *bool:
*target = defaultValue.(bool)
default:
return fmt.Errorf("default value type provided is not supported")
}
return nil
}
return fmt.Errorf("%s could not be loaded: %v", key, err)
}
switch target := target.(type) {
case *string:
*target = c.configReader.GetString(key)
case *bool:
*target = c.configReader.GetBool(key)
default:
return fmt.Errorf("configuration value type provided is not supported")
}
return nil
}
The two switch statements seems like code repetition but I couldn't figure out how to refactor it.