0

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.

CCH
  • 1
  • 1
  • 1
    What happens when you change `key string` to `Key string`? Struct fields cannot be set using reflection when they are unexported. If the first letter is uppercase, the field is [exported](https://golang.org/ref/spec#Exported_identifiers) (public) and should work – xarantolus Mar 14 '20 at 07:38
  • 1
    The Key field in the conf struct must have an upper case letter. – chmike Mar 14 '20 at 07:41
  • You guys are right, problem fixed after I capitalized the field. Guess I depends on golint to find this kind of error for too long time. Thank you guys!! – CCH Mar 15 '20 at 05:50

0 Answers0