env package loads environment variables from a .env file into the process environment and validates required variables into a typed Config. Existing process environment variables take precedence over file-defined values.
Functions
Load
.env file and sets them in the process environment. Existing variables are not overwritten. Repeated calls with the same path are no-ops and return the cached result.
Path to the
.env file. If not provided or empty, defaults to .env in the current directory.error - Returns an error if the file cannot be read or parsed. Returns nil if the file does not exist.
Behavior:
- Empty lines and lines starting with
#are ignored - Quotes (single or double) around values are automatically stripped
- Existing environment variables are never overwritten
- Thread-safe with internal caching to prevent duplicate loads
- Invalid lines are logged as warnings but do not cause errors
New
.env file and returns a Config populated from the environment. Required variables that are missing or empty are returned as a single error.
Returns: (*Config, error) - A populated Config struct or an error if loading fails or required variables are missing.
Example:
Types
Config
env tag to register a new variable.
Tag Format:
env:"VAR_NAME"- Optional variableenv:"VAR_NAME,required"- Required variable (must be present and non-empty)
PostgreSQL database connection URL. Maps to the
DATABASE_URL environment variable.Features
Environment Variable Precedence
The package respects existing environment variables. If a variable is already set in the process environment, the value from the.env file is ignored. This allows:
- Local development with
.envfiles - Production deployment with real environment variables
- Override capability for testing
Thread Safety
All operations are thread-safe. The package uses internal locking to ensure safe concurrent access and prevents race conditions when loading files.Caching
Loaded files are cached. CallingLoad() multiple times with the same path will only read the file once and return the cached result (including errors).
Error Handling
The package distinguishes between different error types:- Missing file: Returns
nil(not an error) - Unreadable file: Returns error
- Invalid format: Logs warning, continues processing
- Missing required variables: Returns error with all missing variable names
