doupao1978 2018-10-11 09:20
浏览 429

毒蛇.yaml值环境变量覆盖

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 values I've set in my environment variables and will try connect to the RabbitMQ with this string

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

instead of

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

  • 写回答

2条回答 默认 最新

  • dq13733519262 2018-10-12 10:27
    关注

    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(env) == 0 {
            panic("Mandatory env variable not found:" + env)
        }
        return res
    }
    

    This will overwrite all the placeholders found in the collection.

    评论

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。