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
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.
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