This is my simplified YAML config:
stripe:
secret_key: sk_fromconfig
Why Viper don't take value from the environment variable?
% echo $STRIPE_SECRET_KEY
sk_fromenv
% go run main.go
sk_fromconfig
I expect it takes value from the environment variable 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With