【问题标题】:viper yaml config sequenceviper yaml 配置序列
【发布时间】:2016-05-23 21:25:54
【问题描述】:

我正在尝试使用 viper (see viper docs) 读取 yaml 配置文件。但是我看不到在问题类型下读取地图值序列的方法。我尝试了各种 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] 的序列

【问题讨论】:

    标签: go yaml viper-go


    【解决方案1】:

    如果您仔细查看可用的不同Get 方法,您会发现返回类型为string[]stringmap[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
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 2017-05-25
      • 2022-01-09
      • 2016-02-05
      • 2017-07-24
      • 2018-04-21
      相关资源
      最近更新 更多