I am trying to read slice of maps with golang viper with the following code (suggested by: Reading a slice of maps with Golang Viper)
package main
import (
"bytes"
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/spf13/viper"
)
type conf struct {
key string `mapstructure:"key"`
}
func main() {
viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")
// any approach to require this configuration into your program.
var yamlExample = []byte(`
list:
- key: 'value_string1'
- key: 'value_string1'
`)
viper.ReadConfig(bytes.NewBuffer(yamlExample))
var confSlice []conf
err := viper.UnmarshalKey("list", &confSlice)
if err != nil {
fmt.Println("unmarshal failed, malformat?", err)
return
}
spew.Dump(confSlice)
}
The output is a slice of 2 empty struct, like
([]main.conf) (len=2 cap=2) {
(main.conf) {
key: (string) ""
},
(main.conf) {
key: (string) ""
}
}
Tried several different ways but still not found one worked. Anyone who can provide me a hint? Thanks.
PS: It is a slice of map with some kv pairs, not just with 1 kv pair. I cut it for brevity.