首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Viper在Go中将字符串映射作为环境变量传递

使用Viper在Go中将字符串映射作为环境变量传递
EN

Stack Overflow用户
提问于 2016-02-09 04:05:59
回答 1查看 8.1K关注 0票数 3

对于我正在从事的一个项目,我尝试使用Viper将stings的映射作为环境变量进行传递。我尝试了几种方法来实现这一点,但都没有成功。当我从代码中读取env变量时,它是空的。这是我使用的代码:

代码语言:javascript
复制
// 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变量的值的方式是:

代码语言:javascript
复制
values := viper.GetStringMapString("options.values")
for key, val := range values {
    fmt.Printf("Key: %s, Value: %s", key, val)
}

如果我在一个配置文件中编写这个配置,并使用viper读取它,我可以完美地做到这一点:

代码语言:javascript
复制
options:
        values:
                root: .
                cmd: exec
                logging: on
                #more values can be added here 

希望有人能给我指明正确的方向。

EN

回答 1

Stack Overflow用户

发布于 2016-02-09 06:46:42

我已经调查了一些,似乎你没有正确设置你的环境变量的值,以及你是如何用viper调用它的。在下面找到一个这样的例子,并随时评论你的任何想法:

代码语言:javascript
复制
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"))
}

以及它将如何被调用:

代码语言:javascript
复制
CONFIG_OPTIONS_VALUES="{\"options\": {\"root\": \".\", \"cmd\": \"exec\", \"logging\": \"on\"}}" go run main.go
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35278329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档