Loader API
Loader is the core type of the env package. It loads environment variable files, holds the values, and returns them through typed getters.
Thread safety
Every Loader method is thread-safe and can be called concurrently from multiple goroutines.
Type Definition
type Loader struct {
// Contains private fields
}
// Compile-time interface implementation checks
var _ EnvLoader = (*Loader)(nil)
var _ io.Closer = (*Loader)(nil)Method Overview
The table groups all Loader methods by purpose. Qualified names are like Loader.GetString; details follow in the sections below.
| Method | Description |
|---|---|
Loader.LoadFiles | Load multiple files in order (.env/JSON/YAML auto-detected) |
Loader.GetString / Loader.Lookup | String read and existence lookup |
Loader.GetInt / Loader.GetUint64 / Loader.GetFloat64 / Loader.GetBool / Loader.GetDuration | Typed reads |
Loader.GetSecure | Defensive copy of a sensitive value |
Loader.Set / Loader.Delete | Write and delete (with key/value validation) |
Loader.Keys / Loader.All / Loader.Len | Collection views |
Loader.Apply / Loader.IsApplied | Apply to the process environment and state query |
Loader.LoadTime / Loader.Config | Load time and configuration copy |
Loader.Validate / Loader.ParseInto | Required-key validation and struct mapping |
Loader.Close / Loader.IsClosed | Lifecycle: zero storage and close |
Creation
New
func New(cfg ...Config) (*Loader, error)Creates a new loader instance.
Parameters:
cfg- optional configuration. Omit it, or pass a zero-valueConfig, andDefaultConfig()is used. You may pass at most oneConfig; passing several returnsErrInvalidConfig, and the extra configs are not applied.
Returns:
*Loader- loader instanceerror- a wrappedErrInvalidConfigwhen configuration validation fails; a file-load failure during creation also returns an error, with the internal components already cleaned up
Behavior:
- Validates the configuration
- Creates the internal components (validator, auditor, expander) and the per-format parsers
- Uses
DefaultConfig()when no Config is passed or the Config is fully zero; itsFilenamesis[".env"], soNew()tries to load.envby default. ClearFilenamesexplicitly when you need an empty loader - Loads files if
cfg.Filenamesis non-empty; a failed load cleans up the internal components and returns the error - Applies to the process environment if
cfg.AutoApplyis true - Does not set the default loader; use
LoadorLoadWithConfigfor that
// Use default configuration
loader, err := env.New()
// Use custom configuration
cfg := env.DefaultConfig()
cfg.Filenames = []string{".env"}
cfg.AutoApply = true
loader, err := env.New(cfg)
if err != nil {
panic(err)
}
defer loader.Close()File Loading
LoadFiles
func (l *Loader) LoadFiles(filenames ...string) errorLoads one or more configuration files.
Parameters:
filenames- list of file paths; defaults to loading.envwhen empty
Returns:
error- load error
Behavior:
- Reads files in the order given. With the default
OverwriteExisting=false, the first file wins: a same-name key in a later file is skipped. - With
OverwriteExisting=true, later files overwrite earlier ones. Both the Development and Testing presets set it totrue. - A failure in one file returns an error immediately, but keys already loaded from earlier files are kept (partial success). On retry, mind
OverwriteExisting: withfalse, the kept keys block same-name keys from the retried files. - That partial-success rule applies to
LoadFileson an already-constructed loader; an auto-load failure insideNew()cleans up the internal components and returns the error instead. - Detects each file's format (.env, JSON, YAML)
- Handles a missing file according to
FailOnMissingFile - Applies to the process environment after loading when
AutoApplyis true RequiredKeysare checked at the end of each file's parse, so every required key must be satisfiable in a single file; do not split them across multiple files
Paths must be relative. Absolute paths, Windows drive letters, UNC paths, and any .. component are rejected with a *SecurityError. If your configuration is mounted at an absolute location (Docker, Kubernetes), change to that directory first or pass a path relative to the working directory.
// Load default .env file
err := loader.LoadFiles()
// Load specified files
err := loader.LoadFiles(".env", ".env.local")
// Mixed formats
err := loader.LoadFiles("config.env", "settings.json", "secrets.yaml")Error types:
ErrFileNotFound- file not found (whenFailOnMissingFile=true)ErrFileTooLarge- file exceeds the size limit. When theStatpre-check catches it, the error is wrapped in*FileErrorwithOp=size_check; when the read itself crosses the limit,ErrFileTooLargeis returned directlyErrClosed- loader has been closed*ParseError- parse error*JSONError- JSON parse error*YAMLError- YAML parse error*SecurityError- file path failed the security check (e.g. a path traversal attempt)ErrAuditFailed- fail-closed auditing is on and an audit event was lost
Format detection rules:
| Extension | Format |
|---|---|
.env | FormatEnv |
.json | FormatJSON |
.yaml, .yml | FormatYAML |
| Other | FormatAuto (uses the .env parser) |
Detection looks only at the extension, never at the content: .env.local has the extension .local, so it resolves to FormatAuto and is still parsed as .env.
Getting Values
Key Resolution
Every getter method resolves keys the same way (the sole exception is GetSecure, which skips the index fallback):
| Input Key | Resolved Result |
|---|---|
"DATABASE_HOST" | "DATABASE_HOST" (exact match) |
"database.host" | "DATABASE_HOST" (dots become underscores) |
"app.name" | "APP_NAME" (uppercase plus underscores) |
"servers.0.host" | "SERVERS_0_HOST" (array index) |
Resolution order:
- Exact match - look up the key name as given
- Uppercase conversion - a simple key also tries its uppercase form
- Path resolution - dot paths are converted to the underscore format
- Index fallback - an index that is missing falls back to the comma-separated value
GetString
func (l *Loader) GetString(key string, defaultValue ...string) stringReads a string value. Supports dot-path resolution.
Parameters:
key- key name (supports exact match, uppercase conversion, dot path)defaultValue- optional default value
Returns:
string- the value, or the default; an empty string when the key is missing and no default was given
// Basic usage
host := loader.GetString("HOST", "localhost")
// Dot-path access (JSON/YAML nested structures)
dbHost := loader.GetString("database.host", "localhost")
appName := loader.GetString("app.name")
// Returns empty string when no default
value := loader.GetString("NON_EXISTENT") // ""GetInt
func (l *Loader) GetInt(key string, defaultValue ...int64) int64Reads an integer value, converting the stored string. Supports dot-path resolution. A value that does not parse as an integer is audited and the default is returned.
Parameters:
key- key name (supports dot path)defaultValue- optional default value, typeint64
Returns:
int64- the value, or the default; 0 when the key is missing and no default was given
port := loader.GetInt("PORT", 8080)
maxConn := loader.GetInt("database.max_connections", 10)
// Returns 0 when no default
value := loader.GetInt("NON_EXISTENT") // 0GetBool
func (l *Loader) GetBool(key string, defaultValue ...bool) boolReads a boolean value. Supports dot-path resolution.
Parameters:
key- key name (supports dot path)defaultValue- optional default value
Returns:
bool- the value, or the default; false when the key is missing and no default was given
Supported values:
- Truthy:
true,1,yes,on,enabled - Falsy:
false,0,no,off,disabled
Matching is case-insensitive. An empty string parses as false rather than falling back to the default. Any other unmatched value is audited and returns the default.
debug := loader.GetBool("DEBUG", false)
cacheEnabled := loader.GetBool("cache.enabled", true)
// Returns false when no default
value := loader.GetBool("NON_EXISTENT") // falseGetUint64
func (l *Loader) GetUint64(key string, defaultValue ...uint64) uint64Reads an unsigned integer value. Supports dot-path resolution. A negative value or a malformed one fails to parse; the failure is audited and the default is returned.
Parameters:
key- key name (supports dot path)defaultValue- optional default value, typeuint64
Returns:
uint64- the value, or the default; 0 when the key is missing and no default was given
port := loader.GetUint64("PORT", 8080)
maxSize := loader.GetUint64("MAX_SIZE", 1024)
// Returns 0 when no default
value := loader.GetUint64("NON_EXISTENT") // 0GetFloat64
func (l *Loader) GetFloat64(key string, defaultValue ...float64) float64Reads a floating-point value. Supports dot-path resolution. A malformed value is audited and the default is returned.
Parameters:
key- key name (supports dot path)defaultValue- optional default value, typefloat64
Returns:
float64- the value, or the default; 0 when the key is missing and no default was given
rate := loader.GetFloat64("RATE", 0.5)
threshold := loader.GetFloat64("THRESHOLD")
// Returns 0 when no default
value := loader.GetFloat64("NON_EXISTENT") // 0GetDuration
func (l *Loader) GetDuration(key string, defaultValue ...time.Duration) time.DurationReads a duration value. Supports dot-path resolution. The value must follow Go's time.ParseDuration syntax; otherwise parsing fails, the failure is audited, and the default is returned.
Parameters:
key- key name (supports dot path)defaultValue- optional default value
Returns:
time.Duration- the value, or the default; 0 when the key is missing and no default was given
Supported formats: ns, us, ms, s, m, h (e.g. 30s, 5m, 1h30m)
timeout := loader.GetDuration("TIMEOUT", 30*time.Second)
ttl := loader.GetDuration("cache.ttl", 5*time.Minute)
// Returns 0 when no default
value := loader.GetDuration("NON_EXISTENT") // 0GetSecure
func (l *Loader) GetSecure(key string) *SecureValueReturns a defensive copy of a sensitive value. Key resolution matches Lookup (exact match, uppercase fallback, dotted path), but not the comma-separated index fallback.
Parameters:
key- key name
Returns:
*SecureValue- a defensive copy of the stored value, independent of the parent Loader. You own it and must release it (Release()zeroes, unlocks, and returns it to the pool;Close()zeroes and unlocks without pooling). Returns nil if the key does not exist, the loader is closed, or the stored value is already closed.
secret := loader.GetSecure("API_SECRET")
if secret != nil {
defer secret.Release()
value := secret.Reveal() // plaintext value
masked := secret.Masked() // [SECURE:32 bytes]
}TIP
See SecureValue API for the full reference.
Getting Slice Values
Loader has no slice getter method, because Go does not support generic methods. Use the standalone generic function GetSliceFrom[T] with a Loader instance:
// Use standalone generic function
hosts := env.GetSliceFrom[string](loader, "HOSTS")
ports := env.GetSliceFrom[int64](loader, "PORTS", []int64{80})
portsInt := env.GetSliceFrom[int](loader, "PORTS") // also supports intSupported types: string, int, int64, uint, uint64, bool, float64, time.Duration
TIP
See Package Functions - GetSliceFrom for the full reference.
Lookup
func (l *Loader) Lookup(key string) (string, bool)Reports whether a key exists and returns its value. Supports dot-path resolution.
Parameters:
key- key name (supports dot path)
Returns:
string- the value as stored, with no trimming applied here..envvalues were trimmed at parse time; JSON and YAML values keep any surrounding whitespace.bool- whether the key exists;("", false)when the loader is closed
value, exists := loader.Lookup("API_KEY")
if !exists {
// key does not exist
}
// Dot path
if value, exists := loader.Lookup("database.host"); exists {
fmt.Println(value)
}
// Index access (falls back to comma-separated value)
// HOSTS=localhost,example.com
if value, exists := loader.Lookup("hosts.0"); exists {
fmt.Println(value) // "localhost"
}Set and Delete
Set
func (l *Loader) Set(key, value string) errorSets an environment variable.
Parameters:
key- key namevalue- value
Returns:
error- set error;ErrAuditFailedwhen fail-closed auditing is on and an event is lost
Behavior:
- Validates the key name
- Validates value safety: the built-in baseline (length ceiling, control characters, and the UTF-8 check when
ValidateUTF8is on) always runs;ValidateValuesacts as a switch only for custom validators without the baseline capability - Skips the call and returns nil when
OverwriteExistingis false and the key already exists - Also writes to the process environment when
AutoApplyis true. WhenSetenvfails,Setreturns the error and stores nothing in memory. WithOverwriteExistingfalse and a process variable of that name already present, only the in-memory value updates; the process environment keeps its original value.
With the built-in validator, the baseline value checks run even when ValidateValues=false: the length ceiling and control-character rejection still apply, and the UTF-8 check follows ValidateUTF8. This matches the .env line-parsing path.
err := loader.Set("CUSTOM_KEY", "value")
if err != nil {
// Handle error
}Error types:
*ValidationError- invalid key name format (Field == "key")*SecurityError- the key is forbidden (matchable witherrors.Is(err, env.ErrSecurityViolation))ErrInvalidValue- invalid value content: null bytes or control characters (always checked with the built-in validator). A value overMaxValueLengthyields a*ValidationErrorwithRule == "max_length", which does not matchErrInvalidValueErrClosed- the loader has been closedErrAuditFailed- fail-closed auditing is on and an audit event was lost
Set accepts a wider key space than the .env line parser, matching keys loaded from JSON/YAML: ., -, and @ are allowed, while empty keys, all-digit keys, and characters outside letters, digits, _, @, -, and . are rejected.
Delete
func (l *Loader) Delete(key string) errorRemoves a variable from the loader.
Parameters:
key- key name
Returns:
error-ErrClosedwhen the loader is closed; the underlying os error when unsetting from the process environment fails (the key name is masked)
Behavior:
- Removes and securely zeroes the value in memory
- Unsets it from the process environment only if this loader wrote that key there; variables this loader did not set are untouched
- The order is in-memory delete first, then the process-environment unset. If
Unsetenvfails,Deletereturns the error, but the memory entry is already gone whileappliedKeyskeeps the key: the variable is still live in the process environment (possibly a secret). RetryDeleteor callos.Unsetenvyourself to clear it.
err := loader.Delete("TEMP_KEY")
if err != nil {
// The unset failed: the in-memory copy is gone but the process variable may still be live
log.Printf("delete failed: %v", err)
}Collection Operations
Keys
func (l *Loader) Keys() []stringReturns all key names.
Storage is split into 32 shards. Keys sizes the result from an atomic counter, then takes each shard's read lock in turn, so the snapshot is approximate: concurrent writes make the shards observe different points in time. Synchronize externally when you need a strictly consistent view.
Returns:
[]string- the key names in unspecified order; nil if the loader is closed
keys := loader.Keys()
for _, key := range keys {
fmt.Println(key)
}All
func (l *Loader) All() map[string]stringReturns every key-value pair as an approximate snapshot, collected the same way as Keys. For an exact snapshot, synchronize externally.
Each value is an ordinary Go string outside SecureValue's protection: it is not zeroed and not memory-locked (SEC-010). Do not log or retain this map when it can hold secrets; use GetSecure for those values.
Returns:
map[string]string- the key-value mapping; nil if the loader is closed
all := loader.All()
for key, value := range all {
fmt.Printf("%s=%s\n", key, value)
}Len
func (l *Loader) Len() intReturns the number of loaded variables.
Len is O(1): it reads an atomic counter instead of sweeping the shards. A write that lands concurrently may not be reflected in the returned count.
Returns:
int- variable count; 0 if the loader is closed
count := loader.Len()
fmt.Printf("Loaded %d variables\n", count)Apply to System
Apply
func (l *Loader) Apply() errorWrites the loaded variables into the process environment (os.Environ).
Returns:
error- apply error. The first key whoseSetenvfails aborts that pass; keys already written are not rolled back andIsApplied()staysfalse(see "Handling a failure" below)
Behavior:
- Iterates over the loaded variables and calls
Setenvfor each one - Stops at the first failure with no rollback: keys written before the failure stay in the process environment, and
appliedKeysonly records up to that point - With
OverwriteExisting=false, keys already present in the process environment (including variables explicitly set to empty) are skipped and audited asskipped (existing) - Keys written successfully are recorded in
appliedKeys, which is howDeletedecides ownership - Only after every key is written does
IsApplied()becometrue - Afterwards,
os.Getenv()returns the values
Error types:
ErrClosed- loader has been closed- Wrapped
oserror - setting an environment variable failed. Key names are masked, so sensitive names do not appear in the message. ErrAuditFailed- fail-closed auditing is on and an audit event was lost
if err := loader.Apply(); err != nil {
log.Printf("apply failed: %v", err) // a failure is "partially applied", not a reason to panic
return
}
// Afterwards os.Getenv() returns the values
host := os.Getenv("HOST")Handling a failure:
Do not answer an Apply failure with panic: it means "partially applied", not "nothing was applied". Every variable successfully Setenv-ed before the failing key stays in the process environment, while IsApplied() stays false because the pass did not complete. From there you have two options: Delete the keys you know were written, or fix the environment and call Apply again (with OverwriteExisting=false, already-present keys are skipped rather than rewritten).
IsApplied
func (l *Loader) IsApplied() boolReports whether the loader has written its variables to the process environment, whether through Apply, a load with AutoApply on, or Set with AutoApply on. A failed Apply leaves it false even though some keys reached the process environment.
Returns:
bool- whether the variables were applied; false if the loader is closed
if loader.IsApplied() {
// Variables have been applied to os.Environ
}Status Queries
LoadTime
func (l *Loader) LoadTime() time.TimeReturns the time of the most recent file load. Set and Delete do not update it.
Returns:
time.Time- the load time; the zero value if nothing has been loaded yet, or if the loader is closed
loadTime := loader.LoadTime()
if !loadTime.IsZero() {
fmt.Printf("Last load time: %v\n", loadTime)
}Config
func (l *Loader) Config() ConfigReturns a value copy of the loader's configuration.
Returns:
Config- configuration (treat it as read-only)
WARNING
Config() returns a value copy of the struct. It is safe to read, but not fully detached:
- Value fields (
MaxFileSize,ValidateValues, ...) are independent copies. KeyPatternis a pointer;FileSystemandAuditHandlerare interfaces;AllowedKeys,RequiredKeys,Filenames, and the other[]stringfields still share their backing arrays with the loader.
Mutating anything in the second group changes the running loader's behavior. To get a safe mutable copy, copy the fields you need into a new Config.
cfg := loader.Config()
fmt.Printf("Max file size: %d\n", cfg.MaxFileSize)Validation and Mapping
Validate
func (l *Loader) Validate() errorReports whether every key listed in ValidationConfig.RequiredKeys exists.
Returns:
error- validation error;ErrClosedwhen the loader is closed. A missing key yields a*ValidationErrorwhoseRuleisrequired(matchable witherrors.Is(err, ErrMissingRequired)), whoseFieldisrequired_keys, and whoseMessagelists the missing key names
Behavior:
- Checks only that the keys listed in
ValidationConfig.RequiredKeysexist AllowedKeysandForbiddenKeystake effect at parse time and inSet; this method does not check them
cfg := env.DefaultConfig()
cfg.RequiredKeys = []string{"DB_HOST", "API_KEY"}
cfg.Filenames = nil // do not auto-load in New, so construction does not fail on missing keys
loader, err := env.New(cfg)
if err != nil {
log.Fatal(err)
}
defer loader.Close()
if err := loader.LoadFiles(".env"); err != nil {
log.Fatal(err) // required keys are checked at the end of every file's parse
}
// Note: required keys are checked at the end of **each file** parse,
// so this example deliberately loads a single file
if err := loader.Validate(); err != nil {
// Missing required keys
var missingErr *env.ValidationError
if errors.As(err, &missingErr) {
fmt.Printf("Missing: %s\n", missingErr.Message)
}
}ParseInto
func (l *Loader) ParseInto(v any) errorMaps the loader's variables onto a struct. The loader takes a snapshot of its values, then calls UnmarshalInto on that snapshot.
Parameters:
v- non-nil pointer to a struct
Returns:
error- mapping error, includingErrClosedwhen the loader is closed; a*ValidationError(Fieldisvalue) whenvis nil or not a struct pointer; a*MarshalErrorwhen tag parsing or type conversion fails (match it witherrors.Asorenv.IsMarshalError)
Supported tags:
env:"KEY"- the environment variable name to readenv:"-"- skip this fieldenvDefault:"value"- default value
Slice fields split on a comma ,; whitespace around each separator is stripped. There is no tag for a custom separator.
type Config struct {
Host string `env:"HOST" envDefault:"localhost"`
Port int64 `env:"PORT" envDefault:"8080"`
Debug bool `env:"DEBUG" envDefault:"false"`
Hosts []string `env:"HOSTS"`
Ignored string `env:"-"`
}
var cfg Config
err := loader.ParseInto(&cfg)
if err != nil {
panic(err)
}Resource Release
Close
func (l *Loader) Close() errorReleases resources and clears storage.
Returns:
error- the auditor error while closing an owned factory; nil when already closed or on a nil receiver
Behavior:
- Securely zeroes all stored sensitive data (the full capacity, not just the current length)
- Closes custom parsers that implement
io.Closer - Closes the ComponentFactory when the loader owns one
- Idempotent; repeated calls return nil
- Does not roll back variables already written to the process environment; see "Lifecycle and Process-Environment Semantics" below
loader, _ := env.New(cfg)
defer loader.Close()
// Use loader...Behavior after Close
After closing, every operation returns either an error or a zero value:
LoadFiles→ErrClosedGetString→ empty valueSet→ErrClosedKeys→ nilLen→ 0
IsClosed
func (l *Loader) IsClosed() boolReports whether the loader has been closed. A nil receiver counts as closed and returns true.
Returns:
bool- whether closed
if loader.IsClosed() {
// loader has been closed
}Complete Example
package main
import (
"errors"
"fmt"
"log"
"os"
"time"
"github.com/cybergodev/env"
)
func main() {
// Create production configuration
cfg := env.ProductionConfig()
cfg.RequiredKeys = []string{"DB_HOST", "API_KEY"}
// loader.Close() closes the handler (and JSONAuditHandler closes its writer),
// so write to a file rather than os.Stdout
auditFile, err := os.OpenFile("audit.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
log.Fatal(err)
}
cfg.AuditHandler = env.NewJSONAuditHandler(auditFile)
// Create loader
loader, err := env.New(cfg)
if err != nil {
auditFile.Close() // on failure the handler did not take over the file, so close it here
log.Fatal(err)
}
defer loader.Close()
// Load files
if err := loader.LoadFiles(".env", ".env.production"); err != nil {
if errors.Is(err, env.ErrFileNotFound) {
log.Fatal("Configuration file not found")
}
log.Fatal(err)
}
// Validate required keys
if err := loader.Validate(); err != nil {
log.Fatal("Missing required configuration:", err)
}
// Read configuration
host := loader.GetString("DB_HOST")
port := loader.GetInt("DB_PORT", 5432)
debug := loader.GetBool("DEBUG", false)
timeout := loader.GetDuration("TIMEOUT", 30*time.Second)
fmt.Printf("Server: %s:%d\n", host, port)
fmt.Printf("Debug: %v, Timeout: %v\n", debug, timeout)
// Sensitive data
secret := loader.GetSecure("API_KEY")
if secret != nil {
defer secret.Release()
fmt.Printf("API Key length: %d\n", secret.Length())
}
// Apply to system environment
if err := loader.Apply(); err != nil {
log.Fatal(err)
}
// All variables
fmt.Printf("Loaded %d variables\n", loader.Len())
fmt.Printf("Load time: %v\n", loader.LoadTime())
}Lifecycle and Process-Environment Semantics
This section is the concise, authoritative summary for the API reference; see the concurrency guide for concurrent scenarios and a full walkthrough.
Close does not roll back os.Environ
Close()zeroes and unlocks the in-memory copies of the variables. It does not unset variables already written to the process environment byApply,AutoApply, orSet(whenAutoApplyis on).- The unlock happens before the zeroing:
SecureValue.CloseandReleaseboth unlock first, then zero the full capacity, so no locked memory page is left behind. - To remove the variables before closing, call
Deletefor each key:
loader.Delete("API_KEY") // unsets in the process env only if this loader set it
loader.Close()Per-key ownership tracking in Delete
- The loader records which keys it wrote to the process environment (
appliedKeys). Deleteunsets only those keys and never touches process variables it did not set (HOME,TERM, ...).- That per-key tracking is why multiple loaders in one process do not interfere with each other.
Apply distinguishes "unset" from "explicitly empty"
ApplyusesLookupEnvto detect existing values.- A variable explicitly set to an empty string counts as present, so with
OverwriteExisting=falseit is skipped like any other existing variable rather than overwritten.
State and metadata methods
Config(): returns a copy of the configuration for read-only use. Value fields are copied, butKeyPattern,FileSystem, andAuditHandlershare their underlying objects, as do the[]stringslices (AllowedKeys,RequiredKeys,Filenames). Mutating any of them affects the running loader.IsClosed(): whether the loader is closed (a nil receiver returns true).IsApplied(): whether the variables were fully applied toos.Environ(staysfalsewhenApplyfailed midway).LoadTime(): time of the most recent load (zero value if never loaded).
Key-resolution details on the read path
- Exact match first: lookup tries the key as written, then falls back to the uppercase form.
- Dot paths:
database.hostexpands toDATABASE_HOST(the flattened JSON/YAML key). An indexed path such asservice.cors.origins.0falls back to the comma-separated value when the indexed key is missing. - No trimming here:
Lookupreturns the stored value as-is..envvalues were trimmed at parse time; JSON and YAML values keep any surrounding whitespace. - Lock-free fast path: single-key reads (
LookupandGetSecure) skip the loader-level read lock and check an atomic closed flag instead. A race withClosedegrades gracefully: you read either the value or the cleared state.
Silent-skip semantics of Set
With OverwriteExisting=false, calling Set on an existing key is silently skipped: it returns nil and writes nothing. To observe skips, watch the audit log for skipped (no overwrite) events.
Defense-in-depth for file loading (TOCTOU)
A theoretical replacement window exists between the Stat() size check and the actual read. Three layers mitigate it:
- The parsers wrap the file stream in a hardened read path that enforces the cap while reading.
- Even if the file grows after the check, reading stops at
MaxFileSize(bounded by the 100 MB hard cap) and returnsErrFileTooLarge, which prevents memory exhaustion. - The parsed content is then re-checked for size, format, and security instead of relying on the original
Stat()result.
Related Documentation
- Package Functions - Package-level convenience functions
- Config API - Configuration options
- SecureValue API - Secure value handling
- Interfaces - Interface definitions