如何使用 viper 将环境变量解组到切片?
How do I unmarshal environment variables to a slice using viper?
我有以下代码:
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
设置为 "english spanish french russian" 时,我得到的长度为 1。它只是将变量作为 1 个长字符串,而不是切片。如何获得切片 ([]string{"english", "spanish", "french", "russian"}
?
感谢@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))
}
我有以下代码:
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
设置为 "english spanish french russian" 时,我得到的长度为 1。它只是将变量作为 1 个长字符串,而不是切片。如何获得切片 ([]string{"english", "spanish", "french", "russian"}
?
感谢@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))
}