Enable environment variable substitution in configuration files using
${VAR} syntax. Supports 12-factor app deployment patterns without
hardcoding secrets or environment-specific values.
Syntax:
- Only ${VAR} with curly braces (avoids conflict with $variable system)
- Missing variables preserved as-is (${MISSING} stays unchanged)
- Multiple variables per line supported
- Adjacent variables ${A}${B} handled correctly
Integration:
- Applied in config.Load() after os.ReadFile, before yaml.Unmarshal
- Applied in processIncludes() for each included file
- 12 unit tests covering single/multiple/missing/empty variables
23 lines
447 B
Go
23 lines
447 B
Go
package config
|
|
|
|
import (
|
|
"os"
|
|
"regexp"
|
|
)
|
|
|
|
var envPattern = regexp.MustCompile(`\$\{([^}]+)\}`)
|
|
|
|
// ExpandEnv replaces ${VAR} patterns with environment variable values.
|
|
func ExpandEnv(data []byte) []byte {
|
|
return envPattern.ReplaceAllFunc(data, func(match []byte) []byte {
|
|
name := string(match[2 : len(match)-1])
|
|
if name == "" {
|
|
return match
|
|
}
|
|
if value, ok := os.LookupEnv(name); ok {
|
|
return []byte(value)
|
|
}
|
|
return match
|
|
})
|
|
}
|