Environment Variables Config Precedence
Load config from environment variables with defaults and validation in Go.
Code
package main
import ("os";"strconv";"fmt")
type Config struct {
Port int
Host string
Debug bool
}
func LoadConfig() Config {
port, _ := strconv.Atoi(getEnv("PORT", "8080"))
return Config{
Port: port,
Host: getEnv("HOST", "localhost"),
Debug: getEnv("DEBUG", "false") == "true",
}
}
func getEnv(key, def string) string {
if v := os.Getenv(key); v != "" { return v }
return def
}How it works
Environment Variables Config Precedence keeps everything in the functions LoadConfig and getEnv.
Applying it
The primary signature is func LoadConfig() Config
The surface worth importing is LoadConfig; the helpers around it are private to the snippet.
Statements that matter
func getEnv(key, def string) string {
if v := os.Getenv(key); v != "" { return v }
return def
}
func LoadConfig() Config {
port, _ := strconv.Atoi(getEnv("PORT", "8080"))
return Config{
Port: port,
Host: getEnv("HOST", "localhost"),
Debug: getEnv("DEBUG", "false") == "true",
}
}
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.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.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `LoadConfig`, `getEnv` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.