我有以下代码:
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"}
?
答案 0 :(得分:3)
感谢@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))
}