I have a function (Load) that creates a map of maps with config for different environments and returns YamlConfig type.
var config = make(map[string]interface{})
type YamlConfig map[string]map[string]interface{}
type environments struct {
Test map[string]interface{}
Development map[string]interface{}
Qa map[string]interface{}
Staging map[string]interface{}
Production map[string]interface{}
Brandconsol map[string]interface{}
}
func Load(path string) YamlConfig {
var config = YamlConfig{}
var env = environments{}
data, err := ioutil.ReadFile(path)
if err != nil {
errors.Annotate(err, "error reading yaml file")
}
err = yaml.Unmarshal(data, &env)
if err != nil {
errors.Annotate(err, "error unmarshaling yaml data")
}
config = make(map[string]interface{})
assignToMultiMap(config, env.Production)
config["production"] = config
...
return config
}
func assignToMultiMap(config map[string]interface{}, converted map[string]interface{}) {
fmt.Println("converted", converted)
for k, v := range converted {
if reflect.TypeOf(v).Kind() == reflect.Map {
m := make(map[string]string)
v := v.(map[interface{}]interface{})
for kk, vv := range v {
m[kk.(string)] = vv.(string)
}
config[strings.ToLower(k)] = m
continue
}
config[strings.ToLower(k)] = parseErb(fmt.Sprintf("%v", v))
}
}
func parseErb(value string) string {
if len(value) > 0 {
re := regexp.MustCompile("<%=\\s+ENV\\['(.+)']\\s+%>")
match := re.FindStringSubmatch(value)
if len(match) == 2 {
value = os.Getenv(match[1])
}
}
return value
}
When I try to use this, however I'm getting the error: invalid operation: host["reader"] (type interface {} does not support indexing)
But host is of type map[string]string
c := config.Load("config/database.yml")
host := c["production"]["host"]
fmt.Printf("host: %+v: %T
", host["reader"], host)
fmt.Printf("%T ", host) gives me map[string]string