英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论