毒蛇.yaml值环境变量覆盖 [英] Go viper .yaml values environment variables override

查看:171
本文介绍了毒蛇.yaml值环境变量覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在go应用程序中包含 application.yaml 文件,该文件包含要使用环境变量覆盖的 $ {RMQ_HOST} 值.

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

application.yaml 中,我得到了:

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

在装载机中,我有:

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

我遇到的问题是 $ {RMQ_HOST} 不会被替换为我在环境变量中设置的值,而是尝试使用此字符串连接到RabbitMQ

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

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

代替

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

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

推荐答案

Viper无法在键/值对中保留值的占位符,因此,我设法使用以下代码片段解决了我的问题:

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.

这篇关于毒蛇.yaml值环境变量覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆