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

时间:2017-07-15 17:27:01

标签: go viper-go

我想要使用viper加载以下配置:

artist:
  name: The Beatles
  albums:
  - name: The White Album
    year: 1968
  - name: Abbey Road
    year: 1969

我无法解决如何加载地图列表的问题。我想我需要解密这个密钥,但这段代码不起作用:

type Album struct {
    Name string
    Year int
}

type Artist struct {
    Name string
    Albums []Album
}

var artist Artist
viper.UnmarshalKey("artists", &artist)

我错过了什么?

1 个答案:

答案 0 :(得分:5)

你确定yaml中的密钥是artists吗?您的意思是提供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)

输出:

<nil>, main.Artist{Name:"The Beatles", Albums:[]main.Album{main.Album{Name:"The White Album", Year:1968}, main.Album{Name:"Abbey Road", Year:1969}}}