操作无效:(类型interface {}不支持索引)

时间:2018-04-06 21:56:13

标签: go

我有一个函数(Load),它创建一个包含不同环境配置的地图,并返回YamlConfig类型。

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
}

当我尝试使用它时,但是我收到错误:无效操作:host [“reader”](类型interface {}不支持索引)

但主机属于map[string]string

类型
c := config.Load("config/database.yml")
host := c["production"]["host"]
fmt.Printf("host: %+v: %T\n", host["reader"], host)

fmt.Printf(“%T \ n”,主持人)给我map [string] string

1 个答案:

答案 0 :(得分:1)

使用type assertion获取map[string]string值:

host, ok := c["production"]["host"].(map[string]string)
if !ok {
   // handle error
}
fmt.Printf("host: %+v: %T\n", host["reader"], host)