env package loads environment variables from a .env file into the process environment and validates required variables into a typed Config struct. Existing process environment variables take precedence over file-defined values.
Installation
Quick Start
Functions
Load
Reads key=value pairs from a.env file and sets them in the process environment.
pkg/env/env.go:25
Path to the .env file. If not provided or empty, defaults to
.env in the current directory.- Existing environment variables are not overwritten
- Repeated calls with the same path are no-ops and return the cached result
- Returns
nilif the file doesn’t exist (not an error) - Supports
#for comments - Supports quoted values with
"or' - Strips leading/trailing whitespace from keys and values
New
Loads the.env file and returns a Config populated from the environment.
pkg/env/config.go:29
- The
.envfile cannot be loaded - Required variables are missing or empty
Types
Config
Holds all environment variables required by the application.pkg/env/config.go:21
env:"VAR_NAME"- Optional variableenv:"VAR_NAME,required"- Required variable (must be set and non-empty)
.env File Format
The.env file uses a simple KEY=VALUE format:
- One variable per line:
KEY=VALUE - Comments start with
# - Empty lines are ignored
- Values can be quoted with
"or'(quotes are stripped) - Whitespace around keys and values is trimmed
- Process environment variables take precedence over file values
Error Handling
The package provides clear error messages for common issues:Thread Safety
TheLoad function is thread-safe and uses a mutex to prevent race conditions. Multiple goroutines can safely call Load concurrently.
Best Practices
- Call early in main(): Load environment variables before initializing other packages
- Don’t commit .env files: Add
.envto your.gitignore
- Provide an example file: Create
.env.examplewith dummy values
- Production environments: Use actual environment variables instead of
.envfiles in production
