Load Environment Variables Into Config
Read configuration from environment variables with typed parsing and defaults, validating required fields at startup rather than at first use.
Code
package config
import (
"fmt"
"os"
"strconv"
)
type Config struct {
Port int
DatabaseURL string
Debug bool
}
func Load() (Config, error) {
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
return Config{}, fmt.Errorf("DATABASE_URL is required")
}
port, err := strconv.Atoi(getEnv("PORT", "8080"))
if err != nil {
return Config{}, fmt.Errorf("PORT must be a number: %w", err)
}
return Config{
Port: port,
DatabaseURL: databaseURL,
Debug: getEnv("DEBUG", "false") == "true",
}, nil
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}What the code does
Load Environment Variables Into Config comes down to the functions Load and getEnv.
Error handling is inline: 1 place test err != nil and branch immediately.
Behavior branches on DATABASE_URL read from the process environment at load time.
Points of care
- Nothing third-party is pulled in; the snippet is dependency-free.
- Failure is a return value (
error), which keeps control flow explicit at every call site.
Using it
Entry signature: func Load() (Config, error)
The surface worth importing is Load; the helpers around it are private to the snippet.
Key statements worth quoting
return Config{}, fmt.Errorf("PORT must be a number: %w", err)
return Config{}, fmt.Errorf("DATABASE_URL is required")
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
Interactive Tools for This Topic
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.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.
FAQ
- How should callers handle failures?
- As returned `error` values — 1 site in the snippet check `err` before using other results.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Every import resolves inside the standard library — `fmt`, `os`, `strconv`. The file defines `Load`, `getEnv` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.