3

我有以下代码:

package main

import (
    "log"

    "github.com/spf13/viper"
)

func main() {
    viper.SetEnvPrefix("myprefix")
    viper.SetDefault("languages", []string{"french", "spanish"})
    viper.BindEnv("name")
    viper.BindEnv("languages")

    type config struct {
        Name      string
        Languages []string
    }

    var C config

    err := viper.Unmarshal(&C)
    if err != nil {
        log.Fatalln("unable to decode into struct, %v", err)
    }

    log.Println(C)
    log.Println(len(C.Languages))
}

$MYPREFIX_LANGUAGES未设置时,C.Languages 的长度为 2(例如默认值)。当我设置$MYPREFIX_LANGUAGES为“英语西班牙语法语俄语”时,我得到的长度为 1。它只是将变量视为 1 个长字符串,而不是切片。如何获得切片 ( []string{"english", "spanish", "french", "russian"}?

4

1 回答 1

7

感谢@Charlino,这是答案:

package main

import (
    "log"

    "github.com/spf13/viper"
)

func main() {
    viper.SetEnvPrefix("myprefix")
    viper.SetTypeByDefaultValue(true)
    viper.SetDefault("languages", []string{"french", "spanish"})
    viper.BindEnv("name")
    viper.BindEnv("languages")

    type config struct {
        Name      string
        Languages []string
    }

    var C config

    err := viper.Unmarshal(&C)
    if err != nil {
        log.Fatalln("unable to decode into struct, %v", err)
    }

    log.Println(C)
    log.Println(len(C.Languages))
}
于 2017-04-05T21:21:21.703 回答