doujiao1538 2018-04-06 21:56
浏览 346
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dongzhina7098 2018-04-06 22:04
    关注

    Use a type assertion to get the map[string]string value:

    host, ok := c["production"]["host"].(map[string]string)
    if !ok {
       // handle error
    }
    fmt.Printf("host: %+v: %T
    ", host["reader"], host)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 Java中import为灰色
    • ¥15 手机等其他智能设备被监听
    • ¥15 在win10 64位的vs打包MSI文件,放到win7 64位上安装成可执行exe文件后,点击程序不运行。
    • ¥50 大众点评用户浏览/消费记录爬虫
    • ¥15 求制作一个个人网页,
    • ¥15 寻涂色内存脚本作者有项目有市场有资源.却技术
    • ¥15 蓝桥杯c51单片机问题
    • ¥15 ajax跨域问题请求修改代码
    • ¥15 python matplotlib
    • ¥15 短信测压+语音,有偿,必须用Python