Documentation
¶
Overview ¶
Package dotenv parses .env files into a map and (optionally) applies them to the process environment. Designed for the framework's startup path so apps get familiar .env behavior without taking on a third-party dependency.
Format (a strict subset of the de facto dotenv spec):
# comments and blank lines are allowed
FOO=bar # bareword value
QUOTED="hello world" # double-quoted: escapes interpreted
LITERAL='hello\nworld' # single-quoted: VERBATIM, no escapes
export PORT=8080 # optional `export` prefix tolerated
PATH_TPL="${HOME}/bin" # ${VAR} expansion (double-quoted only)
Hard rules:
- Keys must start with a letter or underscore; rest is [A-Za-z0-9_].
- Multi-line values are NOT supported. Use \n inside a double-quoted value if you need a newline character.
- Inline comments after an UNQUOTED value are preserved as part of the value — write a quoted value if you need to embed `#`.
- On a malformed line the parser returns an error with line number.
See Expand for the variable-expansion semantics and the hardening (cycle detection, depth cap, undefined-as-empty, \$ escape).
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Apply ¶
Apply writes vals into the process environment via os.Setenv, but ONLY for keys not already present in os.Environ. Returns the keys actually set (loaded) and those skipped because env already had a value. Both slices are sorted for stable test output.
Existing env wins — operators expect their explicit configuration to override dotfiles. (Some loaders flip this; do not.)
func Expand ¶
Expand performs ${VAR} substitution in s, drawing values from local first then envFn. Bracket form ONLY — bare $VAR is left verbatim (less ambiguous, fewer footguns).
Hardening:
- Cycle detection via a visited-set; a self-reference (`A=${A}`) or a multi-key cycle yields empty for the offending name.
- Depth cap (maxExpandDepth) to bound worst-case work.
- Undefined names → empty string (consistent with shell behavior).
- `\${...}` literal-escape is the parser's job, not Expand's: unescapeDouble strips the `\$` to `$` so Expand sees just `$`, which doesn't form a `${`-prefix and is therefore left alone.
- Malformed `${...` without closing `}` is left verbatim — better than silently dropping bytes.
envFn may be nil — in that case the only lookup source is local.
func Load ¶
Load reads one or more .env files and returns the merged key/value map. EARLIER paths take precedence on key conflict — the convention is to pass most-specific first (e.g. .env.local, .env.<APP_ENV>, .env). Missing files are silently skipped; a malformed file returns an error naming the file.
func LoadAndApply ¶
LoadAndApply is Load + Apply in one call — the common shape for boot-time wiring.
Types ¶
This section is empty.