2016-05-23 63 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 
}