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

Die*_*ego 5 go viper-go

对于我正在从事的一个项目,我尝试使用 Viper 将刺痛图作为环境变量传递。我尝试了多种方法来实现这一目标,但没有成功。当我从代码中读取环境变量时,它是空的。这是我正在使用的代码:

// 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"))
Run Code Online (Sandbox Code Playgroud)

这就是我传递值的方式:

CONFIG_OPTIONS_VALUES_ROOT="。"

我也尝试过:

CONFIG_OPTIONS_VALUES="{\"root\": \".\",\"cmd\": \"exec\", \"logging\": \"on\"}"

我想要处理 env 变量中的值传递的方式是:

values := viper.GetStringMapString("options.values")
for key, val := range values {
    fmt.Printf("Key: %s, Value: %s", key, val)
}
Run Code Online (Sandbox Code Playgroud)

如果我将此配置写入配置文件并使用 viper 读取它,我可以完美地做到这一点:

options:
        values:
                root: .
                cmd: exec
                logging: on
                #more values can be added here 
Run Code Online (Sandbox Code Playgroud)

希望有人能在这里指出我正确的方向。

Jes*_*oco 3

我已经进行了一些调查,似乎您没有正确设置环境变量的值,以及如何使用 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"))
}
Run Code Online (Sandbox Code Playgroud)

以及如何称呼它:

CONFIG_OPTIONS_VALUES="{\"options\": {\"root\": \".\", \"cmd\": \"exec\", \"logging\": \"on\"}}" go run main.go
Run Code Online (Sandbox Code Playgroud)