Config API
Complete configuration options reference for the Config struct.
Struct Definition
Config uses nested structs for organization while maintaining backward compatibility through Go's field promotion:
type Config struct {
FileConfig // File loading behavior
ValidationConfig // Key and value validation
LimitsConfig // Size and count limits
JSONConfig // JSON parsing options
YAMLConfig // YAML parsing options
ParsingConfig // General parsing behavior
ComponentConfig // Custom components and advanced options
}Two Access Methods:
// Old way (via field promotion, still valid)
cfg.Filenames = []string{".env"}
cfg.MaxFileSize = 1024
// New way (recommended, clearer)
cfg.FileConfig.Filenames = []string{".env"}
cfg.LimitsConfig.MaxFileSize = 1024Nested Structs
// FileConfig controls file loading behavior
type FileConfig struct {
Filenames []string // List of files to load
FailOnMissingFile bool // Whether to error when file not found
OverwriteExisting bool // Whether to overwrite existing environment variables
AutoApply bool // Whether to automatically apply to os.Environ
}
// ValidationConfig controls key and value validation
type ValidationConfig struct {
RequiredKeys []string // List of required key names
AllowedKeys []string // Allowed key name whitelist
ForbiddenKeys []string // Additional forbidden key list
KeyPattern *regexp.Regexp // Key name matching pattern
ValidateValues bool // Whether to validate value safety
ValidateUTF8 bool // Whether to validate values as valid UTF-8
}
// LimitsConfig controls size and count limits
type LimitsConfig struct {
MaxFileSize int64 // Max bytes per file
MaxVariables int // Max variables per file
MaxLineLength int // Max length per line
MaxKeyLength int // Max key name length
MaxValueLength int // Max value length
MaxExpansionDepth int // Max variable expansion depth
}
// JSONConfig controls JSON parsing behavior
type JSONConfig struct {
JSONNullAsEmpty bool // Convert null to empty string
JSONNumberAsString bool // Convert numbers to strings
JSONBoolAsString bool // Convert booleans to strings
JSONMaxDepth int // Max nesting depth
}
// YAMLConfig controls YAML parsing behavior
type YAMLConfig struct {
YAMLNullAsEmpty bool // Convert null/~ to empty string
YAMLNumberAsString bool // Convert numbers to strings
YAMLBoolAsString bool // Convert booleans to strings
YAMLMaxDepth int // Max nesting depth
}
// ParsingConfig controls general parsing behavior
type ParsingConfig struct {
AllowExportPrefix bool // Allow export KEY=value syntax
AllowYamlSyntax bool // Allow YAML-style values
ExpandVariables bool // Whether to expand ${VAR} references
}
// ComponentConfig for custom components and advanced options
type ComponentConfig struct {
CustomValidator Validator // Custom key/value validator
CustomExpander VariableExpander // Custom variable expander
CustomAuditor AuditLogger // Custom audit logger
FileSystem FileSystem // Custom file system (for testing)
AuditHandler AuditHandler // Custom audit handler
AuditEnabled bool // Enable audit logging
Prefix string // Only process variables with this prefix
}Configuration Fields
File Handling
These fields control file loading behavior.
Filenames []string
List of file paths to load. Default [".env"].
cfg.Filenames = []string{".env", ".env.local"}FailOnMissingFile bool
Whether to return an error when a file is not found. Default false (silently skip).
cfg.FailOnMissingFile = true // Error when file not foundOverwriteExisting bool
Whether to overwrite existing environment variables. Default false.
cfg.OverwriteExisting = true // Allow overwriteAutoApply bool
Automatically apply to the system environment (os.Environ) after loading. Default false.
cfg.AutoApply = true // Auto-apply after loadingNote
The package-level Load() function automatically sets AutoApply = true. When using New() to create a Loader, you must set it manually.
Variable Expansion
ExpandVariables bool
Enable ${VAR} syntax variable expansion. Default true.
cfg.ExpandVariables = trueSupported expansion syntax:
| Syntax | Description |
|---|---|
${VAR} | Reference a variable |
${VAR:-default} | Use default value when variable doesn't exist or is empty |
${VAR:=default} | Set default value when variable doesn't exist or is empty |
${VAR:?error} | Error when variable doesn't exist or is empty |
Security Limits
MaxFileSize int64
Maximum bytes per file. Default 2MB, hard maximum 100MB.
cfg.MaxFileSize = 10 * 1024 * 1024 // 10 MB| Config | Default | Hard Maximum |
|---|---|---|
MaxFileSize | 2MB (2097152) | 100MB |
MaxLineLength int
Maximum length per line. Default 1024, hard maximum 64KB.
cfg.MaxLineLength = 2048| Config | Default | Hard Maximum |
|---|---|---|
MaxLineLength | 1024 | 65536 (64KB) |
MaxKeyLength int
Maximum key name length. Default 64, hard maximum 1024.
cfg.MaxKeyLength = 128| Config | Default | Hard Maximum |
|---|---|---|
MaxKeyLength | 64 | 1024 |
MaxValueLength int
Maximum value length. Default 4096, hard maximum 1MB.
cfg.MaxValueLength = 8192| Config | Default | Hard Maximum |
|---|---|---|
MaxValueLength | 4096 | 1048576 (1MB) |
MaxVariables int
Maximum variables per file. Default 500, hard maximum 10000.
cfg.MaxVariables = 1000| Config | Default | Hard Maximum |
|---|---|---|
MaxVariables | 500 | 10000 |
MaxExpansionDepth int
Maximum variable expansion depth. Default 5, hard maximum 20.
cfg.MaxExpansionDepth = 10| Config | Default | Hard Maximum |
|---|---|---|
MaxExpansionDepth | 5 | 20 |
Key Validation
KeyPattern *regexp.Regexp
Custom key name matching pattern. Default nil (uses fast byte-level validation).
Performance Optimization
A nil value enables fast byte-level validation (~10x performance improvement). Default validation rules: starts with a letter, contains only letters, digits, and underscores.
import "regexp"
// Custom pattern
cfg.KeyPattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`)AllowedKeys []string
Allowed key name whitelist. When empty, all keys are allowed (except forbidden keys).
cfg.AllowedKeys = []string{"APP_NAME", "APP_VERSION", "PORT"}ForbiddenKeys []string
Additional forbidden key list (added on top of built-in forbidden keys).
cfg.ForbiddenKeys = []string{"CUSTOM_DANGEROUS_VAR"}Built-in Forbidden Keys
The library built-in forbids system-critical variables like PATH, LD_PRELOAD, LD_LIBRARY_PATH, DYLD_INSERT_LIBRARIES, etc. See Constants & Errors.
RequiredKeys []string
List of required key names. Checked when Validate() is called.
cfg.RequiredKeys = []string{"DB_HOST", "API_KEY"}ValidateValues bool
Validates value safety (control characters, null bytes, etc.). Default true.
Security Recommendation
It is recommended to keep this enabled at all times. Only disable in special scenarios (e.g., when you need to store values containing control characters).
cfg.ValidateValues = true // Enabled by defaultValidateUTF8 bool
Validates whether values are valid UTF-8 encoded. Default false.
cfg.ValidateUTF8 = true // Enable UTF-8 validationParsing Options
AllowExportPrefix bool
Allow export KEY=value syntax. Default true.
cfg.AllowExportPrefix = false // Disallow export prefixAllowYamlSyntax bool
Allow YAML-style syntax (KEY: value). Default false.
cfg.AllowYamlSyntax = trueJSON Options
JSONNullAsEmpty bool
Convert JSON null values to empty strings. Default true.
cfg.JSONNullAsEmpty = trueJSONNumberAsString bool
Convert JSON numbers to strings. Default true.
cfg.JSONNumberAsString = trueJSONBoolAsString bool
Convert JSON booleans to strings. Default true.
cfg.JSONBoolAsString = trueJSONMaxDepth int
Maximum JSON nesting depth. Default 10.
cfg.JSONMaxDepth = 20YAML Options
YAMLNullAsEmpty bool
Convert YAML null/~ values to empty strings. Default true.
cfg.YAMLNullAsEmpty = trueYAMLNumberAsString bool
Convert YAML numbers to strings. Default true.
cfg.YAMLNumberAsString = trueYAMLBoolAsString bool
Convert YAML booleans to strings. Default true.
cfg.YAMLBoolAsString = trueYAMLMaxDepth int
Maximum YAML nesting depth. Default 10.
cfg.YAMLMaxDepth = 15Audit
AuditEnabled bool
Enable audit logging. Default false.
cfg.AuditEnabled = trueAuditHandler AuditHandler
Custom audit handler.
cfg.AuditHandler = env.NewJSONAuditHandler(os.Stdout)See Also
Audit Logging for complete audit configuration details.
Advanced Options
Prefix string
Only process variables with this prefix. Default "" (process all variables).
cfg.Prefix = "MYAPP_" // Only load variables starting with MYAPP_FileSystem FileSystem
Custom file system interface (for testing).
cfg.FileSystem = &MockFileSystem{}CustomValidator Validator
Custom key/value validator. Overrides the built-in validator.
cfg.CustomValidator = &MyValidator{}CustomExpander VariableExpander
Custom variable expander. Overrides the built-in expander.
cfg.CustomExpander = &MyExpander{}CustomAuditor AuditLogger
Custom audit logger. Overrides the built-in auditor.
cfg.CustomAuditor = &MyAuditLogger{}Factory Functions
DefaultConfig
func DefaultConfig() ConfigReturns a safe default configuration.
Default Values:
| Field | Value |
|---|---|
Filenames | [".env"] |
FailOnMissingFile | false |
OverwriteExisting | false |
AutoApply | false |
ExpandVariables | true |
MaxFileSize | 2MB |
MaxLineLength | 1024 |
MaxKeyLength | 64 |
MaxValueLength | 4096 |
MaxVariables | 500 |
MaxExpansionDepth | 5 |
ValidateValues | true |
KeyPattern | nil (fast validation) |
AllowExportPrefix | true |
AllowYamlSyntax | false |
JSONNullAsEmpty | true |
JSONNumberAsString | true |
JSONBoolAsString | true |
JSONMaxDepth | 10 |
YAMLNullAsEmpty | true |
YAMLNumberAsString | true |
YAMLBoolAsString | true |
YAMLMaxDepth | 10 |
ValidateUTF8 | false |
AuditEnabled | false |
Prefix | "" |
DevelopmentConfig
func DevelopmentConfig() ConfigReturns development environment configuration (relaxed limits).
Differences from Default:
OverwriteExisting:trueAllowYamlSyntax:trueMaxFileSize: 10MB
Security Guarantee
ValidateValues remains true across all preset configurations (consistent with the default value), ensuring security regardless of environment.
cfg := env.DevelopmentConfig()
cfg.Filenames = []string{".env.development"}
loader, _ := env.New(cfg)TestingConfig
func TestingConfig() ConfigReturns testing environment configuration.
Differences from Default:
OverwriteExisting:trueMaxFileSize: 64KBMaxVariables: 50
func TestSomething(t *testing.T) {
cfg := env.TestingConfig()
cfg.Filenames = []string{".env.test"}
loader, _ := env.New(cfg)
defer loader.Close()
}ProductionConfig
func ProductionConfig() ConfigReturns production environment configuration (strict validation + audit).
Differences from Default:
FailOnMissingFile:trueAuditEnabled:trueMaxFileSize: 64KBMaxVariables: 50
cfg := env.ProductionConfig()
cfg.RequiredKeys = []string{"DB_HOST", "API_KEY"}
cfg.AuditHandler = env.NewJSONAuditHandler(os.Stdout)
loader, _ := env.New(cfg)Detailed Preset Comparison
| Feature | Default | Development | Testing | Production |
|---|---|---|---|---|
| Overwrite existing variables | No | Yes | Yes | No |
| Error on file not found | No | No | No | Yes |
| Audit logging | No | No | No | Yes |
| YAML syntax | No | Yes | No | No |
| File size limit | 2MB | 10MB | 64KB | 64KB |
| Max variables | 500 | 500 | 50 | 50 |
| Forbidden key check | Yes | Yes | Yes | Yes |
| Value validation | Yes | Yes | Yes | Yes |
Selection Guide
- Development: Use
DevelopmentConfig()with relaxed limits for rapid iteration - Testing: Use
TestingConfig()with overwrite enabled for test isolation - Production: Use
ProductionConfig()with audit and strict validation enabled
Methods
Validate
func (c *Config) Validate() errorValidates configuration validity. Checks whether all limit values are within valid ranges.
cfg := env.DefaultConfig()
cfg.MaxFileSize = 1000
if err := cfg.Validate(); err != nil {
// Configuration is invalid
}Validation Rules:
- All limit values must be positive
- All limit values must not exceed hard maximums
KeyPatternif non-nil must match valid key names (e.g.,TEST_KEY), must not match empty strings, and must not match key names starting with digitsJSONMaxDepthandYAMLMaxDepthmust be between 1-100
IsZero
func (c *Config) IsZero() boolChecks whether the Config is an uninitialized zero value. Used to determine whether DefaultConfig() should be used instead.
Returns:
bool- Whether this is a zero-value configuration
Detection Scope:
- Numeric limits (MaxFileSize, MaxVariables, etc.)
- Boolean fields (ValidateValues, AutoApply, etc.)
- Pointer/interface fields (KeyPattern, FileSystem, etc.)
- Slice fields (Filenames, RequiredKeys, etc.)
Note
A partially initialized Config may not be detected as zero value. It is recommended to always start from DefaultConfig() for custom configuration:
// Recommended
cfg := env.DefaultConfig()
cfg.Filenames = []string{".env.production"}
// Not recommended (some fields are zero values)
var cfg env.Config
cfg.Filenames = []string{".env.production"}Usage Examples
Basic Configuration
cfg := env.DefaultConfig()
cfg.Filenames = []string{".env", ".env.local"}
cfg.OverwriteExisting = true
loader, err := env.New(cfg)
if err != nil {
log.Fatal(err)
}
defer loader.Close()Production Configuration
cfg := env.ProductionConfig()
cfg.RequiredKeys = []string{"DB_HOST", "DB_PORT", "API_KEY"}
cfg.AuditHandler = env.NewJSONAuditHandler(os.Stdout)
loader, err := env.New(cfg)
if err != nil {
log.Fatal(err)
}
defer loader.Close()
if err := loader.LoadFiles(".env"); err != nil {
log.Fatal(err)
}
if err := loader.Validate(); err != nil {
log.Fatal("Missing required configuration:", err)
}Prefix Filtering
cfg := env.DefaultConfig()
cfg.Prefix = "MYAPP_" // Only load MYAPP_KEY1, MYAPP_KEY2, etc.
cfg.Filenames = []string{".env"}
loader, _ := env.New(cfg)
// loader contains only variables starting with MYAPP_Custom Validation
import "regexp"
cfg := env.DefaultConfig()
// Only allow uppercase letters at the start
cfg.KeyPattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`)
// Add custom forbidden keys
cfg.ForbiddenKeys = []string{"DEBUG", "TRACE"}
loader, _ := env.New(cfg)Related Documentation
- Loader API - Loader methods
- Constants & Errors - Limit constants and error types
- Audit Logging - Audit configuration guide