Golang Viper GetSliceString not parsing yml file

821 views Asked by At

I am using GoLang and Viper as inferred from the questions title. My element.yml file which is in the same directory as the file trying to parse it is able to get Strings and Integers but for whatever reason cannot get a Slice of Strings with the method GetStringSlice(). Does anybody know what I'm doing wrong? I ran my yml in a validator which confirmed everything was fine. Code is as follows :

func GetElementString(s string) string {  //works
    vi := viper.New()
    vi.SetConfigFile("element.yml")
    vi.ReadInConfig()
    return vi.GetString(s)
}

func GetElementInt(s string) int {  //works
    vi := viper.New()
    vi.SetConfigFile("element.yml")
    vi.ReadInConfig()
    return vi.GetInt(s)
}

func GetElementSliceString(s string) []string { //does not work
    vi := viper.New()
    vi.SetConfigFile("element.yml")
    vi.ReadInConfig()
    return vi.GetStringSlice(s)
}

element.yml

key: "value"
urls: 
  - "https://twitter.com/elonmusk"
  - "https://twitter.com/elonmusk/with_replies"
  - "https://twitter.com/elonmusk/likes"

The tests I write to drive the methods work for the integer and the strings but not the slice of strings. What am I doing wrong ??

1

There are 1 answers

1
advay rajhansa On BEST ANSWER

I had no issues running this on my machine.
I suggest you try catching the error on read file and see if that helps.
You can also provide the file path if needed.

func GetElementSliceString(s string) []string {
    vi := viper.New()
    vi.SetConfigFile("element.yml")
    vi.AddConfigPath("./")          // Path here
    err := vi.ReadInConfig()        // catch error while reading the configs
    if err != nil {
        panic(err)
    }
    return vi.GetStringSlice(s)
}