Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go viper .yaml values environment variables override

Tags:

go

viper-go

I'm trying to have application.yaml file in go application which contains ${RMQ_HOST} values which I want to override with environment variables.

In application.yaml I've got:

rmq:
  test:
    host: ${RMQ_HOST}
    port: ${RMQ_PORT}

And in my loader I have:

log.Println("Loading config...")
viper.SetConfigName("application")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AutomaticEnv()
err := viper.ReadInConfig()

The problem I have is ${RMQ_HOST} won't get replaced by the values I've set in my environment variables, and tries to connect to the RabbitMQ with this string

amqp://test:test@${RMQ_HOST}:${RMQ_PORT}/test

instead of

amqp://test:test@test:test/test

like image 307
Ajdin Halac Avatar asked Dec 14 '22 14:12

Ajdin Halac


1 Answers

Viper doesn't have the ability to keep placeholders for values in key/value pairs, so I've managed to solve my issue with this code snippet:

log.Println("Loading config...")
viper.SetConfigName("application")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
    panic("Couldn't load configuration, cannot start. Terminating. Error: " + err.Error())
}
log.Println("Config loaded successfully...")
log.Println("Getting environment variables...")
for _, k := range viper.AllKeys() {
    value := viper.GetString(k)
    if strings.HasPrefix(value, "${") && strings.HasSuffix(value, "}") {
        viper.Set(k, getEnvOrPanic(strings.TrimSuffix(strings.TrimPrefix(value,"${"), "}")))
    }
}

func getEnvOrPanic(env string) string {
    res := os.Getenv(env)
    if len(res) == 0 {
        panic("Mandatory env variable not found:" + env)
    }
    return res
}

This will overwrite all the placeholders found in the collection.

like image 109
Ajdin Halac Avatar answered Jan 08 '23 14:01

Ajdin Halac