viper yaml配置序列

时间:2016-05-23 21:25:54

标签: go yaml viper-go

我尝试使用viper(see viper docs)读取yaml配置文件。但我看不到在issue-types下读取map值序列的方法。我尝试了各种Get_方法 但似乎没有人支持这一点。

remote:
  host: http://localhost/
  user: admin
  password:  changeit

mapping:
    source-project-key: IT
    remote-project-key: SCRUM

issue-types:
  - source-type: Incident
    remote-type: Task
  - source-type: Service Request
    remote-type: Task
  - source-type: Change
    remote-type: Story
  - source-type: Problem
    remote-type: Task

我希望能够迭代map [strings]

的序列

1 个答案:

答案 0 :(得分:1)

如果仔细查看可用的不同Get方法,您会发现返回类型为string[]stringmap[string]interface{},{{1 }和map[string]string

然而,与" issue-types"相关联的值的类型;是map[string][]string。因此,获取此数据的唯一方法是通过[]map[string]string方法并使用类型断言。

现在,以下代码生成相应类型的Get,即issue_types

[]map[string]string

请注意,我没有进行任何安全检查以使代码更小。但是,执行类型断言的正确方法是:

issues_types := make([]map[string]string, 0)
var m map[string]string

issues_i := viper.Get("issue-types")
// issues_i is interface{}

issues_s := issues_i.([]interface{})
// issues_s is []interface{}

for _, issue := range issues_s {
    // issue is an interface{}

    issue_map := issue.(map[interface{}]interface{})
    // issue_map is a map[interface{}]interface{}

    m = make(map[string]string)
    for k, v := range issue_map {
        m[k.(string)] = v.(string)
    }
    issues_types = append(issues_types, m)
}

fmt.Println(reflect.TypeOf(issues_types))
# []map[string]string

fmt.Println(issues_types)
# [map[source-type:Incident remote-type:Task]
#  map[source-type:Service Request remote-type:Task]
#  map[source-type:Change remote-type:Story]
#  map[source-type:Problem remote-type:Task]]