如何使用viper加载地图列表?

jbr*_*own 4 go viper-go

我有以下配置我想用viper加载:

artist:
  name: The Beatles
  albums:
  - name: The White Album
    year: 1968
  - name: Abbey Road
    year: 1969
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何加载地图列表.我想我需要解组这个密钥,但是这段代码不起作用:

type Album struct {
    Name string
    Year int
}

type Artist struct {
    Name string
    Albums []Album
}

var artist Artist
viper.UnmarshalKey("artists", &artist)
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

jee*_*tkm 6

你确定钥匙artists在yaml?你的意思是供应artist吗?

工作范例:

str := []byte(`artist:
  name: The Beatles
  albums:
  - name: The White Album
    year: 1968
  - name: Abbey Road
    year: 1969
`)

    viper.SetConfigType("yaml")
    viper.ReadConfig(bytes.NewBuffer(str))

    var artist Artist
    err := viper.UnmarshalKey("artist", &artist)

    fmt.Printf("%v, %#v\n", err, artist)
Run Code Online (Sandbox Code Playgroud)

输出:

<nil>, main.Artist{Name:"The Beatles", Albums:[]main.Album{main.Album{Name:"The White Album", Year:1968}, main.Album{Name:"Abbey Road", Year:1969}}}
Run Code Online (Sandbox Code Playgroud)

  • 我想是时候休息一下了 :-) 谢谢 (2认同)