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

Time:05-29

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.

CodePudding user response:

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.

  • Related