os.Expand Variable Interpolation

Interpolate variables in config templates with os.Expand and a resolver callback, or os.ExpandEnv when missing variables should expand to empty strings.

GoConfig Management

Code

gosnippet
23 lines
package main

import (
	"fmt"
	"os"
)

func main() {
	os.Setenv("PORT", "8080")
	os.Setenv("REGION", "eu-west")

	// os.Expand:回调决定每个 $VAR / ${VAR} 的取值,缺失变量可给显式占位
	tmpl := "listen on ${PORT} in ${REGION} (replica ${REPLICA})"
	fmt.Println(os.Expand(tmpl, func(key string) string {
		if v, ok := os.LookupEnv(key); ok {
			return v
		}
		return "unset:" + key
	}))

	// os.ExpandEnv:直接按 os.Getenv 展开,缺失变量得到空串
	fmt.Println(os.ExpandEnv("region=${REGION} shards=${SHARDS}"))
}

Where the logic sits

Structurally, expect the function main and nothing else.

Caveats

  • Entirely standard-library — copy it in and it runs.

Putting it to use

Entry signature: func main()

Core lines

return "unset:" + key

Interactive Tools for This Topic

FAQ

How do you run os.Expand Variable Interpolation?
It runs as-is — treat the file as the whole program and execute it.