对于我正在从事的一个项目,我尝试使用Viper将stings的映射作为环境变量进行传递。我尝试了几种方法来实现这一点,但都没有成功。当我从代码中读取env变量时,它是空的。这是我使用的代码:
// To configure viper
viper.SetEnvPrefix("CONFIG")
viper.AutomaticEnv()
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
// To read the configuration value I tried all this variants:
fmt.Print(viper.GetString("options.values"))
fmt.Print(viper.GetStringMapString("options.values"))
fmt.Print(viper.GetStringMap("options.values"))这就是我传递值的方式:
CONFIG_OPTIONS_VALUES_ROOT=“。
我也尝试过:
根目录“{\”CONFIG_OPTIONS_VALUES=\“:\".\",\"cmd\":\"exec\",\"logging\":\"on\"}”
我想要处理传入env变量的值的方式是:
values := viper.GetStringMapString("options.values")
for key, val := range values {
fmt.Printf("Key: %s, Value: %s", key, val)
}如果我在一个配置文件中编写这个配置,并使用viper读取它,我可以完美地做到这一点:
options:
values:
root: .
cmd: exec
logging: on
#more values can be added here 希望有人能给我指明正确的方向。
发布于 2016-02-09 06:46:42
我已经调查了一些,似乎你没有正确设置你的环境变量的值,以及你是如何用viper调用它的。在下面找到一个这样的例子,并随时评论你的任何想法:
package main
import (
"bytes"
"fmt"
"github.com/spf13/viper"
"strings"
)
func main() {
//Configure the type of the configuration as JSON
viper.SetConfigType("json")
//Set the environment prefix as CONFIG
viper.SetEnvPrefix("CONFIG")
viper.AutomaticEnv()
//Substitute the _ to .
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
//Get the string that is set in the CONFIG_OPTIONS_VALUES environment variable
var jsonExample = []byte(viper.GetString("options.values"))
viper.ReadConfig(bytes.NewBuffer(jsonExample))
//Convert the sub-json string of the options field in map[string]string
fmt.Println(viper.GetStringMapString("options"))
}以及它将如何被调用:
CONFIG_OPTIONS_VALUES="{\"options\": {\"root\": \".\", \"cmd\": \"exec\", \"logging\": \"on\"}}" go run main.gohttps://stackoverflow.com/questions/35278329
复制相似问题