使用viper如何将环境变量反序列化为切片?

huangapple go评论107阅读模式
英文:

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))
}

huangapple
  • 本文由 发表于 2017年4月3日 12:14:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/43176391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定