在 YML 中使用具有默认值的环境变量

Sar*_*oev 1 go

我有以下代码从 yml 读取配置文件,其中也包含 ENV 变量:

confContent, err := ioutil.ReadFile("config.yml")
    if err != nil {
        panic(err)
    }
    // expand environment variables
    confContent = []byte(os.ExpandEnv(string(confContent)))
    conf := &SysConfig{}
    if err := yaml.Unmarshal(confContent, conf); err != nil {
        panic(err)
    }
Run Code Online (Sandbox Code Playgroud)

config.yml

db:
  name: ${DB_NAME:qm}
  host: localhost

Run Code Online (Sandbox Code Playgroud)

DB_NAME它正在工作,但是如果没有给出 env ,我怎样才能让它读取默认值?

NuL*_*uLo 6

ExpandEnv您可以在使用时替换映射器Expand并考虑默认值,如下所示:

package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    mapper := func(placeholderName string) string {
        split := strings.Split(placeholderName, ":")
        defValue := ""
        if len(split) == 2 {
            placeholderName = split[0]
            defValue = split[1]
        }

        val, ok := os.LookupEnv(placeholderName)
        if !ok {
            return defValue
        }

        return val
    }

    os.Setenv("DAY_PART", "morning")

    fmt.Println(os.Expand("Good ${DAY_PART:test}, ${NAME:Gopher}", mapper))
}
Run Code Online (Sandbox Code Playgroud)

这将呈现

Good morning, Gopher
Run Code Online (Sandbox Code Playgroud)

这是基于os 包文档中Expand 的示例。