Using env variables in YML with default value

Issue

I have the following code to read config files from yml which includes ENV variables too:

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)
    }

config.yml

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

It is working but how can I get it to read default values if DB_NAME env is not given?

Solution

You can replace the mapper on ExpandEnv using Expand and take into account default values like this:

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))
}

this will render

Good morning, Gopher

This is based on the example from Expand from the os package documentation.

Answered By – NuLo

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.