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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- How do you run os.Expand Variable Interpolation?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.