无法通过环境变量获取嵌套键来覆盖使用viper的yaml配置文件。

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

Can't get nested key from env to override yaml config file using viper

问题

这是我的简化配置:

stripe:
  secret_key: sk_fromconfig

为什么 Viper 不从环境变量中获取值?

% echo $STRIPE_SECRET_KEY
sk_fromenv
% go run main.go 
sk_fromconfig

我期望它从环境变量中获取值,因为我有一个环境变量如下:

% echo $STRIPE_SECRET_KEY
sk_fromenv
% go run main.go 
sk_fromenv

以下是代码:

package main

import (
	"fmt"

	viper "github.com/spf13/viper"
)

type Config struct {
	Stripe Stripe
}

type Stripe struct {
	SecretKey string `mapstructure:"secret_key"`
}

func main() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")

	viper.AutomaticEnv()
	_ = viper.ReadInConfig()

	var config Config
	_ = viper.Unmarshal(&config)

	fmt.Println(config.Stripe.SecretKey)
}

我尝试过 viper.BindEnv("STRIPE_SECRET_KEY")viper.SetEnvPrefix("STRIPE"),但没有起作用。

英文:

This is my simplified config:

stripe:
  secret_key: sk_fromconfig

Why viper don't take value from env?

% echo $STRIPE_SECRET_KEY
sk_fromenv
% go run main.go 
sk_fromconfig

I expect it takes value from env because I have one like this:

% echo $STRIPE_SECRET_KEY
sk_fromenv
% go run main.go 
sk_fromenv

Here is the code:

package main

import (
	"fmt"

	viper "github.com/spf13/viper"
)

type Config struct {
	Stripe Stripe
}

type Stripe struct {
	SecretKey string `mapstructure:"secret_key"`
}

func main() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")

	viper.AutomaticEnv()
	_ = viper.ReadInConfig()

	var config Config
	_ = viper.Unmarshal(&config)

	fmt.Println(config.Stripe.SecretKey)
}

I tried viper.BindEnv("STRIPE_SECRET_KEY") and viper.SetEnvPrefix("STRIPE") but didn't work.

答案1

得分: 4

使用viper.SetEnvKeyReplacer,因为它没有自动将.替换为_

viper.SetEnvKeyReplacer(strings.NewReplacer(`.`,`_`))

因此,它正在寻找环境变量STRIPE.SECRET_KEY,但由于大多数shell不允许在环境变量名称中使用点号,我们必须将其替换为下划线。

英文:

Use viper.SetEnvKeyReplacer, because it wasn't automatically replaced from . to _

viper.SetEnvKeyReplacer(strings.NewReplacer(`.`,`_`))

so it was looking for environment variable STRIPE.SECRET_KEY but since most shell doesn't allow dot in the environment variable name, we have to replace it with underscore.

huangapple
  • 本文由 发表于 2022年5月28日 18:04:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/72414729.html
匿名

发表评论

匿名网友

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

确定