2016-05-23 62 views
0

我正在尝试使用viper读取yaml配置文件(see viper docs)。但我看不到一种方法来读取问题类型下的地图值序列。我试过了各种Get_方法 ,但似乎没有人支持这一点。viper yaml配置序列

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 

我希望能够遍历地图的序列。[字符串]

回答

1

如果您在不同Get方法可仔细一看,你会看到,返回类型为string[]string,map[string]interface{}map[string]stringmap[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]] 

请注意,我没有做任何安全检查,以使代码更小。然而,正确的断言类型是:

var i interface{} = "42" 
str, ok := i.(string) 
if !ok { 
    // A problem occurred, do something 
}