Config API
Complete configuration options reference for the Config struct.
Struct Definition
Config uses nested structs to organize settings 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 parse options
YAMLConfig // YAML parse options
ParsingConfig // General parsing behavior
ComponentConfig // Custom components and advanced options
}Two access methods:
// Old way (via field promotion, still works)
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 on missing file
OverwriteExisting bool // Whether to overwrite existing env vars
AutoApply bool // Whether to auto-apply to os.Environ
}
// ValidationConfig controls key and value validation
type ValidationConfig struct {
RequiredKeys []string // List of required key names
AllowedKeys []string // Whitelist of allowed key names
ForbiddenKeys []string // Additional forbidden keys list
KeyPattern *regexp.Regexp // Key name match 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 single line length
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 // null converts to empty string
JSONNumberAsString bool // numbers convert to strings
JSONBoolAsString bool // booleans convert to strings
JSONMaxDepth int // Max nesting depth
}
// YAMLConfig controls YAML parsing behavior
type YAMLConfig struct {
YAMLNullAsEmpty bool // null/~ converts to empty string
YAMLNumberAsString bool // numbers convert to strings
YAMLBoolAsString bool // booleans convert 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 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 filesystem (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 doesn't exist. Default false (silent skip).
cfg.FailOnMissingFile = true // Error on missing fileOverwriteExisting bool
Whether to overwrite existing environment variables. Default false.
cfg.OverwriteExisting = true // Allow overwritingAutoApply bool
Automatically apply to the system environment (os.Environ) after loading. Default false.
cfg.AutoApply = true // Auto-apply after loadingTIP
The package-level Load() function automatically sets AutoApply = true. When using New() to create a Loader, you need to 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 if variable doesn't exist (uses original value if it exists even if empty) |
${VAR:=default} | Same as ${VAR:-default} (uses default if variable doesn't exist, does not write back to storage) |
${VAR:?error} | Error if variable doesn't exist or is empty |
TIP
${VAR:-default} and ${VAR:=default} use the default value only when the variable is not set; if the variable is explicitly set to an empty string (VAR=), the empty string original value is used. Only ${VAR:?error} treats an empty string as an error. See Variable Expansion.
Security Limits
MaxFileSize int64
Maximum bytes per file. Default 2MB, hard limit 100MB.
cfg.MaxFileSize = 10 * 1024 * 1024 // 10 MB| Setting | Default | Hard Limit |
|---|---|---|
MaxFileSize | 2MB (2097152) | 100MB |
MaxLineLength int
Maximum length of a single line. Default 1024, hard limit 64KB.
cfg.MaxLineLength = 2048| Setting | Default | Hard Limit |
|---|---|---|
MaxLineLength | 1024 | 65536 (64KB) |
MaxKeyLength int
Maximum key name length. Default 64, hard limit 1024.
cfg.MaxKeyLength = 128| Setting | Default | Hard Limit |
|---|---|---|
MaxKeyLength | 64 | 1024 |
MaxValueLength int
Maximum value length. Default 4096, hard limit 1MB.
cfg.MaxValueLength = 8192| Setting | Default | Hard Limit |
|---|---|---|
MaxValueLength | 4096 | 1048576 (1MB) |
MaxVariables int
Maximum variables per file. Default 500, hard limit 10000.
cfg.MaxVariables = 1000| Setting | Default | Hard Limit |
|---|---|---|
MaxVariables | 500 | 10000 |
MaxExpansionDepth int
Maximum variable expansion depth. Default 5, hard limit 20.
cfg.MaxExpansionDepth = 10| Setting | Default | Hard Limit |
|---|---|---|
MaxExpansionDepth | 5 | 20 |
Key Validation
KeyPattern *regexp.Regexp
Custom key name match pattern. Default nil (uses fast byte-level validation).
TIP
nil enables fast byte-level validation (about 10x performance improvement). Default validation rule: starts with a letter, contains only letters, numbers, and underscores.
import "regexp"
// Custom pattern
cfg.KeyPattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`)AllowedKeys []string
Whitelist of allowed key names. When empty, all keys are allowed (except forbidden keys).
cfg.AllowedKeys = []string{"APP_NAME", "APP_VERSION", "PORT"}ForbiddenKeys []string
Additional forbidden keys list (added to built-in forbidden keys).
cfg.ForbiddenKeys = []string{"CUSTOM_DANGEROUS_VAR"}TIP
The library has built-in forbidden keys including PATH, LD_PRELOAD, LD_LIBRARY_PATH, DYLD_INSERT_LIBRARIES and other system-critical variables. See Constants & Errors.
RequiredKeys []string
List of required key names. Checked when Validate() is called.
cfg.RequiredKeys = []string{"DB_HOST", "API_KEY"}ValidateValues bool
Validate value safety (control characters, null bytes, etc.). Default true.
WARNING
It is recommended to keep this enabled. Disable only in special scenarios (e.g., when you need to store values containing control characters).
cfg.ValidateValues = true // Enabled by defaultValidateUTF8 bool
Validate that 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)TIP
See Audit Logging for complete audit configuration documentation.
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 filesystem 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 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 config:
OverwriteExisting:trueAllowYamlSyntax:trueMaxFileSize: 10MB
TIP
ValidateValues remains true in all preset configurations (consistent with the default), 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 config:
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 config:
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 | ✗ | ✓ | ✓ | ✗ |
| Error on missing file | ✗ | ✗ | ✗ | ✓ |
| Audit logging | ✗ | ✗ | ✗ | ✓ |
| YAML syntax | ✗ | ✓ | ✗ | ✗ |
| File size limit | 2MB | 10MB | 64KB | 64KB |
| Max variables | 500 | 500 | 50 | 50 |
| Forbidden key check | ✓ | ✓ | ✓ | ✓ |
| Value validation | ✓ | ✓ | ✓ | ✓ |
TIP
- Development: Use
DevelopmentConfig()with relaxed limits for fast iteration - Testing: Use
TestingConfig()with overwrite support for test isolation - Production: Use
ProductionConfig()with audit and strict validation
Methods
Validate
func (c *Config) Validate() errorValidates configuration validity. Checks that all limit values are within valid ranges.
cfg := env.DefaultConfig()
cfg.MaxFileSize = 1000
if err := cfg.Validate(); err != nil {
// configuration invalid
}Validation rules:
- All limit values must be positive
- All limit values must not exceed hard limits
- If
KeyPatternis non-nil, it must match a valid key name (e.g.,TEST_KEY), must not match empty string, and must not match keys starting with a digit JSONMaxDepthandYAMLMaxDepthmust 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.
Returns:
bool- whether it's 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.)
WARNING
A partially initialized Config may not be detected as zero value. Always start customizing from DefaultConfig():
// Recommended
cfg := env.DefaultConfig()
cfg.Filenames = []string{".env.production"}
// Not recommended (some fields will be zero)
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)
}Using 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 letter prefix
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