英文:
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.Fatalf("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。它只将变量作为一个长字符串,而不是一个切片。如何获取一个切片([]string{"english", "spanish", "french", "russian"}
)?
英文:
I have the following code:
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))
}
When $MYPREFIX_LANGUAGES
is not set the length of C.Languages is 2 (eg the default). When I set $MYPREFIX_LANGUAGES
to "english spanish french russian" I get a length of 1. It is just taking the variable as 1 long string, not a slice. How do I get a slice ([]string{"english", "spanish", "french", "russian"}
?
答案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("无法解码为结构体,%v", err)
}
log.Println(C)
log.Println(len(C.Languages))
}
英文:
Thanks to @Charlino here is the answer:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论