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

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

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)
    
    点赞 评论

相关推荐 更多相似问题