envx

package module
v2.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 10 Imported by: 1

README

envx

Go Reference Go version Mutation

envx configures your Go app from environment variables and Docker secrets, with typed getters that fall back to your defaults and log a typo instead of hiding it.

It replaces the os.Getenv, strconv and KEY_FILE code a service otherwise writes at startup. The root module depends only on pathinside, which uses only the standard library. The optional yamlenv module adds go-yaml v3 for YAML config files. Both need Go 1.27.2 or later and are licensed under Apache-2.0.

Why use it

envx is built for Go services in containers, configured by compose or Kubernetes through variables and mounted secret files.

  • Bool, Int and Duration return your default for an unset, empty or malformed value. A malformed one also logs a warning through slog.Default() naming the variable.
  • A key name no variable can have, such as APP LISTEN, panics on first read. Otherwise the getter would return its default forever.
  • Require returns a typed error, so startup can report every missing variable at once.
  • Secret reads KEY_FILE before KEY, caps the file at 1 MB and keeps the secret out of every error and log line.
  • yamlenv fills ${VAR} in a YAML config file after parsing it, so a value cannot change its structure. Load errors never carry an expanded value by default.

Consider caarlos0/env if you want your whole config parsed into a tagged struct, with float, slice, map and custom-type parsers.

Install

go get github.com/cplieger/envx/v2@latest

yamlenv is a separate module with its own version tags:

go get github.com/cplieger/envx/yamlenv/v2@latest

Usage

Read each setting with its default:

addr := cmp.Or(envx.String("APP_LISTEN"), ":8080")
debug := envx.Bool("APP_DEBUG", false)                 // true/1/yes/on · false/0/no/off
retries := envx.Int("APP_RETRIES", 3)
interval := envx.Duration("APP_INTERVAL", 6*time.Hour) // Go duration syntax

Fail at startup on a missing variable, and read a Docker secret from APP_API_KEY_FILE when it is set, else from APP_API_KEY:

token, err := envx.Require("APP_TOKEN") // *envx.MissingError when unset or empty
if err != nil {
	slog.Error("startup", "error", err)
	os.Exit(1)
}

// An empty APP_API_KEY_FILE names no file, so Secret would read APP_API_KEY
// instead. Stop here when a broken secret mount must not fall back:
if envx.IsBlankSecretFilePath("APP_API_KEY") {
	slog.Error("startup", "error", "APP_API_KEY_FILE is set but empty")
	os.Exit(1)
}

apiKey, err := envx.Secret("APP_API_KEY")

Keep a run(os.Args, os.Getenv) test seam and still get the typed getters:

func main() { os.Exit(run(os.Args, os.Getenv)) }

func run(args []string, getenv func(string) string) int {
	env := envx.Source{Get: getenv}
	timeout := env.Duration("DUMP_TIMEOUT", 5*time.Minute)
	workers := env.Int("DUMP_CONCURRENCY", 2)
	// ...
}

Load a YAML config file whose values refer to environment variables as ${VAR}. Load checks, parses, expands and decodes in one call. With its default options, every error it returns is safe to log:

cfg := defaultConfig() // the decode overlays the file onto your defaults
allow := func(name string) bool { return strings.HasPrefix(name, "APP_") }
unresolved, err := yamlenv.Load(data, &cfg, allow)
if len(unresolved) > 0 {
	slog.Warn("config references unset environment variables",
		"vars", strings.Join(unresolved, ","))
}
if err != nil {
	return err // a misspelled key, a second document or a decode failure, with no secret in the text
}

YAML config files with yamlenv covers the expansion rules, the steps Load runs and WithErrorPassthrough, which returns the decode errors you select unchanged. The runnable examples on pkg.go.dev show more cases, and go test keeps them true.

API

  • Getters: String, Bool, Int and Duration, which take the variable name as a Key.
  • Strict getters that return a malformed value as an error and never log: BoolStrict, IntStrict, DurationStrict and ParseError.
  • Required values and secrets: Require, Secret, SecretWithSource, IsBlankSecretFilePath, MissingError and one error value for each way a secret file can fail.
  • An injected environment: Source, which carries the getters, the strict getters and Require as methods.
  • yamlenv: Load with its options, and the steps it runs, ExpandWith, Expand, SanitizeDecodeError, CheckUnknownKeys and CheckSingleDocument.

The full reference is on pkg.go.dev for envx and yamlenv.

Behavior contract

  • Every getter treats an empty variable as unset. Use os.LookupEnv when the difference matters.
  • A value never causes a panic or an exit. The one panic is a malformed key name, which comes from the code.
  • A tolerant getter and its strict variant share one parser, so they accept exactly the same values.
  • Bool, Int, Duration and the strict getters trim surrounding whitespace. String returns the value as set.
  • Secret returns KEY as set, and a file's content with at most one trailing line ending removed.
  • envx keeps no state, starts no goroutines and reads the environment only when a getter is called.

Behavior contract has every rule, including the secret-file checks and the error values.

Unsupported by design

These are deliberate non-goals:

  • Struct tags or reflection-based config loading.
  • Loading .env files.
  • Float, slice and map getters.
  • Prefix namespacing such as WithPrefix("APP_").
  • MustX variants that panic on a missing variable.
  • Accepting a malformed key name with a warning.

Non-goals gives the reason for each.

Documentation

Contributing

See CONTRIBUTING.md.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package envx reads typed configuration from environment variables.

Every parsing getter takes a Key and a fallback and never fails on the environment's content: an unset or empty variable returns the fallback, and a malformed value returns it with one Warn through slog's default logger. A Key that is not a valid variable name panics on first use (see Key). String takes no fallback; compose one with cmp.Or.

Require errors on a missing mandatory variable; Secret also reads a Docker-style KEY_FILE secret file, with each failure class a sentinel. BoolStrict, IntStrict and DurationStrict return (value, ok, error) and never log. A Source carries the same getters over an injected environment.

envx holds no state and starts no goroutines.

Example
package main

import (
	"cmp"
	"fmt"
	"os"
	"time"

	"github.com/cplieger/envx/v2"
)

func main() {
	os.Setenv("APP_LISTEN", ":9090")
	os.Setenv("APP_DEBUG", "yes")
	defer os.Unsetenv("APP_LISTEN")
	defer os.Unsetenv("APP_DEBUG")

	// String takes no fallback, so there is no argument order to get wrong;
	// cmp.Or composes the default, and treats an empty value as absent
	// exactly as the parsing getters do.
	addr := cmp.Or(envx.String("APP_LISTEN"), ":8080")
	debug := envx.Bool("APP_DEBUG", false)
	interval := envx.Duration("APP_INTERVAL", 6*time.Hour)

	fmt.Println(addr, debug, interval)
}
Output:
:9090 true 6h0m0s

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrSecretFilePathRejected means KEY_FILE named a path this package
	// refuses to open: not already clean, or containing a ".." path component.
	ErrSecretFilePathRejected = errors.New("envx: secret file path rejected")
	// ErrSecretFileTooLarge means the file was already over maxSecretFileSize
	// when it was opened.
	ErrSecretFileTooLarge = errors.New("envx: secret file exceeds the size limit")
	// ErrSecretFileGrew means the file passed the size gate and then grew past
	// maxSecretFileSize while it was being read, so the content would have been
	// silently truncated.
	ErrSecretFileGrew = errors.New("envx: secret file grew past the size limit during read")
	// ErrSecretFileUnreadable means the operating system refused the open, stat
	// or read. The underlying *os.PathError stays reachable with errors.As, so
	// a caller can still report the syscall and its reason (without the path,
	// which the PathError also carries).
	ErrSecretFileUnreadable = errors.New("envx: secret file could not be read")
)

The failure classes of a KEY_FILE secret read. Every error Secret and SecretWithSource return for a configured secret file wraps exactly one of these or ErrBlankSecretFile, so a caller can name WHY the file was unusable with errors.Is and apply a different policy per class.

The classes exist because the alternative was worse: without them the only way to tell a rejected path from an oversized file was matching this package's error TEXT, so callers folded every non-blank failure into one generic message instead. That mattered here more than in most packages, because these errors embed the operator-supplied PATH and a caller whose KEY_FILE was misconfigured to hold the secret ITSELF (rather than a path to it) must be able to describe the failure without echoing the value into a log. Naming the class no longer requires touching the path.

The classes are deliberately narrow rather than one "unusable file" sentinel: their remediations differ (fix the variable, shrink the file, stop rewriting it, fix the mount) and only a caller writing an operator-facing message knows which of those it wants to say.

View Source
var ErrBlankSecretFile = errors.New("envx: secret file is blank")

ErrBlankSecretFile is returned by Secret and SecretWithSource when KEY_FILE names a readable file whose content is blank — empty, or whitespace only.

Blankness is the one judgement made on the whitespace-trimmed content: a file holding only spaces or newlines is a broken secret mount, not a secret. The value a readable file DOES carry is returned with at most a trailing line ending removed, so the two operations do not share a rule (see trimTrailingLineEnding).

It is a distinct sentinel because a caller often has a policy for a blank secret that differs from its policy for an unusable one. cert-converter is the motivating case: it offers PFX_ALLOW_EMPTY_PASSWORD as an explicit opt-in to running without a password, and that opt-in has to mean the same thing whether the blank value arrived through the environment or through a mounted file. Without a sentinel the file channel could only be classified by matching this package's error TEXT, so the opt-in silently applied to one channel and not the other.

It is deliberately NOT a *MissingError: the operator did configure a secret file, and treating "you forgot to set this" the same as "the file you mounted is blank" would hide a broken secret mount behind a caller's default.

Functions

func Bool

func Bool(key Key, fallback bool) bool

Bool returns the boolean value of the environment variable key, or fallback when the variable is unset or empty.

Parsing is tolerant of the spellings deployment files actually contain: true/1/yes/on and false/0/no/off, case-insensitive, surrounding whitespace ignored. Any other value logs one Warn through slog's default logger and returns fallback, so a typo ("ture") is visible in the logs instead of silently flipping a flag.

The Warn line carries the raw value. Use BoolStrict for a key whose value may be sensitive, or when the caller owns its own diagnostics.

func BoolStrict

func BoolStrict(key Key) (value, ok bool, err error)

BoolStrict returns the boolean value of the environment variable key with the parse result owned by the caller: a set-but-malformed value is returned as an error instead of the tolerant getters' warn-and-fallback.

The accepted spellings are exactly Bool's (true/1/yes/on and false/0/no/off, case-insensitive, surrounding whitespace ignored) because both route through the same parser and cannot drift apart. The three states match IntStrict: unset or empty (false, false, nil), malformed (false, false, err), valid (b, true, nil). value is false in two of those three, so ok — never value alone — distinguishes "set to false" from "not set".

Unlike IntStrict and DurationStrict, the error carries no fragment of the value: there is no parse error to wrap, and the reason to reach for BoolStrict is usually that the value must not be repeated anywhere. It names the key and the accepted vocabulary. Strict variants never log.

Use Bool when a malformed value should fall back with a Warn naming the raw value; use BoolStrict for a key whose value may be sensitive (one an operator could wire to a secret by mistake, so no diagnostic may echo it) or when the caller owns its own diagnostics.

(value and ok share their bool type in the signature at the linter's insistence; they mean what the family's other strict variants mean.)

func Duration

func Duration(key Key, fallback time.Duration) time.Duration

Duration returns the value of the environment variable key parsed with time.ParseDuration ("30s", "6h", "1h30m"), or fallback when the variable is unset or empty. A set-but-unparseable value logs one Warn through slog's default logger and returns fallback.

A bare number without a unit is deliberately not accepted: "30" is ambiguous between seconds and minutes across tools, and time.ParseDuration rejecting it (with the Warn line naming the key) is clearer than guessing.

func DurationStrict

func DurationStrict(key Key) (value time.Duration, ok bool, err error)

DurationStrict returns the value of the environment variable key parsed with time.ParseDuration ("30s", "6h", "1h30m"), with the parse result owned by the caller: a set-but-malformed value is returned as an error instead of the tolerant getters' warn-and-fallback.

The three states match IntStrict: unset or empty (0, false, nil), malformed (0, false, err), valid (d, true, nil). As with Duration, a bare number without a unit is rejected ("30" is ambiguous between seconds and minutes across tools). Strict variants never log.

A malformed value returns a *ParseError carrying the key and the trimmed value, so a caller quoting the rejected input needs no second environment read.

func Int

func Int(key Key, fallback int) int

Int returns the integer value of the environment variable key, or fallback when the variable is unset or empty. A set-but-unparseable value logs one Warn through slog's default logger and returns fallback.

func IntStrict

func IntStrict(key Key) (value int, ok bool, err error)

IntStrict returns the integer value of the environment variable key with the parse result owned by the caller: a set-but-malformed value is returned as an error instead of the tolerant getters' warn-and-fallback.

ok reports a successfully parsed value; it is false when the variable is unset or empty (empty equals unset, as with every getter) and false when the value did not parse. err is non-nil only for a set-but-malformed value; it names the key and wraps the underlying strconv error. Exactly one of the three states holds: unset (0, false, nil), malformed (0, false, err), or valid (n, true, nil). Strict variants never log.

Use Int when a malformed value should fall back with a Warn; use IntStrict when the caller must decide what a malformed value means (reject startup, apply bounds, keep an existing value).

A malformed value returns a *ParseError carrying the key and the trimmed value, so a caller quoting the rejected input needs no second environment read.

func IsBlankSecretFilePath

func IsBlankSecretFilePath(key Key) bool

IsBlankSecretFilePath reports whether the KEY_FILE companion variable for key is present in the environment but blank — set to the empty string, or to whitespace only — and therefore names no secret file.

SecretWithSource cannot report this state, and deliberately still does not: it gates the file channel on a non-empty KEY_FILE, so `KEY_FILE=` is indistinguishable from unset and resolves through KEY exactly as if the operator had never written it. That is the right rule for a VALUE, which is why every getter here treats empty as unset: compose files and CI matrices materialize `KEY=` for a knob left blank. KEY_FILE holds a POINTER, though, and a blank pointer is a broken secret mount rather than an operator declining to configure one — `KEY_FILE=${SECRETS_DIR}/token` with SECRETS_DIR undefined produces exactly this shape.

The state is reported instead of acted on because only the caller knows what its secret's absence means, and the two answers are far apart. For a mandatory credential the fallthrough surfaces as *MissingError and startup fails anyway; for an OPTIONAL one — a bearer token whose absence serves an endpoint unauthenticated — a blank KEY_FILE silently disarms the gate, so the fallthrough is fail-OPEN. A caller that must refuse that asks before resolving:

if envx.IsBlankSecretFilePath("BEAT_TOKEN") {
	return errors.New("BEAT_TOKEN_FILE is set but empty: unset it to configure BEAT_TOKEN directly, or point it at a secret file")
}
token, src, err := envx.SecretWithSource("BEAT_TOKEN")

Whitespace counts as blank, the rule ErrBlankSecretFile already applies to a secret file's CONTENT: a whitespace-only path is a quoting slip, never a filename an operator meant to write. Resolution treats the two shapes differently — an empty KEY_FILE is ignored, a whitespace-only one is opened and fails — so for that shape this predicate buys a diagnostic naming the blank variable in place of a "no such file or directory" for a filename nobody can see, not a change of fail direction.

It reports the state and changes none of it: a deployment where `KEY_FILE=` falls through to KEY keeps doing so, including for callers that never ask.

Example
package main

import (
	"fmt"
	"os"

	"github.com/cplieger/envx/v2"
)

func main() {
	// The shape compose interpolation of an undefined variable produces: the
	// pointer is present, but it names no file.
	os.Setenv("APP_API_KEY_FILE", "")
	os.Setenv("APP_API_KEY", "inline-key")
	defer os.Unsetenv("APP_API_KEY_FILE")
	defer os.Unsetenv("APP_API_KEY")

	// Resolution cannot see it: the inline value wins as if the operator had
	// never written APP_API_KEY_FILE.
	_, source, _ := envx.SecretWithSource("APP_API_KEY")
	fmt.Println("resolved from:", source)
	fmt.Println("blank secret pointer:", envx.IsBlankSecretFilePath("APP_API_KEY"))
}
Output:
resolved from: env
blank secret pointer: true

func Require

func Require(key Key) (string, error)

Require returns the value of the environment variable key, or a *MissingError when it is unset or empty. It returns an error rather than exiting so the caller controls startup failure (collect every missing key, log through the configured handler, then exit once).

Example
package main

import (
	"fmt"

	"github.com/cplieger/envx/v2"
)

func main() {
	// Collect every missing variable, then fail once.
	var missing []error
	if _, err := envx.Require("APP_TOKEN_UNSET_A"); err != nil {
		missing = append(missing, err)
	}
	if _, err := envx.Require("APP_TOKEN_UNSET_B"); err != nil {
		missing = append(missing, err)
	}
	fmt.Println(len(missing), "missing")
}
Output:
2 missing

func Secret

func Secret(key Key) (string, error)

Secret returns a required secret from the environment, supporting the Docker secrets convention: when KEY_FILE is set to a non-empty value, the secret is read from that file (size-bounded, with at most one trailing line ending removed); otherwise the value of KEY itself is returned. An unset or empty result is a *MissingError, and a configured file whose content is blank is ErrBlankSecretFile.

The file channel returns the secret as written apart from that single trailing newline, so a value whose leading or trailing SPACES are part of the credential survives the round trip: the two channels must not disagree about what the secret IS, and KEY is never rewritten either. Only the line ending an editor or `kubectl create secret` appends is removed, because that one is an artifact of storing a value in a file rather than part of the value.

The KEY_FILE indirection keeps the secret value out of `docker inspect` output and compose files; the file path must be clean (no ".." traversal), and the read uses a single handle so the size check and the read cannot race. The secret value itself never appears in an error or a log line; errors carry the key name and file path only. Each failure class is named by a sentinel (ErrSecretFilePathRejected, ErrSecretFileTooLarge, ErrSecretFileGrew, ErrSecretFileUnreadable, ErrBlankSecretFile) so a caller can report WHY the file was unusable without echoing the path.

Use SecretWithSource when the caller needs to know WHICH channel supplied the value — for example to warn that a KEY it also set was ignored in favour of KEY_FILE. Secret delegates to it, so the two cannot drift. Use IsBlankSecretFilePath when a KEY_FILE that is present but blank must be refused instead of read as absent.

func String

func String(key Key) string

String returns the value of the environment variable key, empty when the variable is unset or set to the empty string. Those two cases are deliberately indistinguishable here, because compose files and CI matrices routinely materialize `KEY=` for a knob the operator left blank; use os.LookupEnv directly for the rare caller that must tell them apart.

String takes no fallback, and that is the whole reason it is safe. A (key, fallback string) pair is two adjacent strings, so a transposed call read the fallback as a variable name and returned the name as the value — silently, forever. There is nothing to transpose against one parameter. Compose the default with cmp.Or, which is what the two-parameter form did internally anyway:

addr := cmp.Or(envx.String("APP_LISTEN"), ":8080")

The parsing getters (Bool, Int, Duration) keep their fallback: it is a different type from the key, so no transposition compiles, and a malformed value has to resolve to something. String has nothing to parse, so it needs no such rule.

Unlike the parsing getters, String does not trim the value: whitespace can be meaningful in a free-form string, and the caller knows whether its value is a path, a token, or a list. A whitespace-only value therefore counts as set, and cmp.Or keeps it.

Types

type Key

type Key string

Key is the NAME of an environment variable — "APP_LISTEN", never its value. Every getter in this package takes its key as a Key.

The type states the role, and its validation catches a malformed name. What it deliberately no longer carries is the old key/fallback transposition story: String takes no fallback, and the parsing getters' fallbacks are typed (bool, int, time.Duration), so no getter in this package has two adjacent parameters a caller could swap. That hazard is closed by the signatures, not by this type.

What the type does buy, in two layers:

  • At compile time it guards VARIABLE-passing sites: a plain string variable in a key position does not compile. Untyped literals still convert implicitly, so existing literal call sites are unaffected — the type alone was never the guard, which is why the signatures had to carry it.

  • At run time, first use validates the spelling: a Key that is not an environment-variable name ([A-Za-z_][A-Za-z0-9_]*, and never empty) PANICS, naming the offending string. This catches a typo ("MY VAR", "app.listen") and a badly built dynamic name, both of which would otherwise read as a permanently unset variable and return a default forever. It is the regexp.MustCompile class: a programmer error at a usually-literal call site, deterministic from the first read.

type MissingError

type MissingError struct {
	// Key is the environment variable name that was required.
	Key Key
}

MissingError reports a required environment variable that is unset or empty. It carries the key so a caller can aggregate several missing variables into one startup failure.

func (*MissingError) Error

func (e *MissingError) Error() string

Error implements the error interface.

type ParseError

type ParseError struct {
	// Err is the underlying strconv or time parse error.
	Err error
	// Key is the environment variable name whose value did not parse.
	Key Key
	// Value is the trimmed value the parser rejected.
	Value string
}

ParseError reports a set-but-malformed environment variable from IntStrict or DurationStrict. It carries the key and the TRIMMED value the parser actually saw, so a caller can quote what was rejected without reaching back to the environment.

That second read is what this type exists to remove, and it was never equivalent: os.Getenv returns the value UNTRIMMED, so a diagnostic built that way can quote " 5x " while the parse error beside it is about "5x". Value is the string the parse failed on, by construction.

BoolStrict deliberately does NOT return it. That variant exists for a key whose value must never be echoed (see BoolStrict), and a typed error carrying the value would hand it to every caller that logs the error. For Int and Duration the value is already repeated inside the wrapped parse error (*strconv.NumError.Num, time.ParseDuration's message), so Value discloses nothing the error did not already carry.

Err is the underlying strconv or time parse error; errors.As still reaches *strconv.NumError through it.

Key carries the Key type, not a plain string: the field IS an environment variable name, so a caller that aggregates failures and re-reads a variable with a default passes it straight back into a getter. Value stays a plain string because a rejected value is not a key.

Field order is govet fieldalignment's, not editorial: Err leads because an interface is two pointer words, which shortens the GC scan range.

func (*ParseError) Error

func (e *ParseError) Error() string

Error implements the error interface. The text is the key followed by the underlying parse error, which is the form every strict variant has always returned; only the type is new.

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

Unwrap exposes the underlying parse error so errors.As reaches *strconv.NumError, as callers of IntStrict already rely on.

type SecretSource

type SecretSource string

SecretSource reports which channel a secret value came from.

const (
	// SourceNone means no value was found in either channel.
	SourceNone SecretSource = "none"
	// SourceEnv means the value came from KEY itself.
	SourceEnv SecretSource = "env"
	// SourceFile means the value came from the file named by KEY_FILE.
	SourceFile SecretSource = "file"
)

The secret delivery channels SecretWithSource distinguishes.

func SecretWithSource

func SecretWithSource(key Key) (value string, source SecretSource, err error)

SecretWithSource is Secret, additionally reporting which channel supplied the value.

Secret resolves KEY_FILE ahead of KEY and returns only the value, so a caller cannot tell whether an environment variable it also set was used or silently ignored. That matters when both are set: the operator expressed two intentions and exactly one takes effect. Only the caller knows whether that is worth a warning in its own configuration vocabulary, so this reports the fact rather than logging it here — consistent with this package's rule that the caller owns the policy and envx owns the parse.

A caller that needs the both-channels-set condition composes it in one line:

v, src, err := envx.SecretWithSource("PFX_PASSWORD")
if src == envx.SourceFile && os.Getenv("PFX_PASSWORD") != "" { /* warn */ }

That works on the error paths too, which is where it matters most: an unreadable file still reports SourceFile, so the caller can tell the operator that the environment variable they also set is not a fallback.

Precedence is unchanged from Secret: KEY_FILE wins when set to a non-empty value, because the entire point of the file channel is keeping the value out of the process environment. A KEY_FILE that is present but blank names no file and is therefore not the file channel at all: resolution falls through to KEY, and IsBlankSecretFilePath is how a caller detects that a secret pointer it was given is broken.

type Source

type Source struct {
	// Get returns the value of the named environment variable, empty when it
	// is unset (os.Getenv's contract, which os.Getenv itself satisfies). nil
	// means os.Getenv.
	Get func(string) string
}

Source reads environment variables through an injected getter, so an app that threads its environment as a function value — the testable-main shape, run(os.Args, os.Getenv) — can use the typed getters without giving that seam up. Construct one from whatever getenv the seam carries:

func run(args []string, getenv func(string) string) int {
	env := envx.Source{Get: getenv}
	timeout := env.Duration("DUMP_TIMEOUT", 5*time.Minute)
	...
}

The zero Source reads the process environment: a nil Get means os.Getenv, and the package-level getters are exactly the zero Source's methods, so the two forms cannot drift apart. Every other rule is shared too — keys are validated Keys, empty equals unset, the parsing methods trim, tolerant and strict variants share one parser, the tolerant methods Warn through slog.Default() on a malformed value, and the strict methods never log.

Example
package main

import (
	"fmt"
	"time"

	"github.com/cplieger/envx/v2"
)

func main() {
	// The testable-main shape: main hands run its real environment
	// (run(os.Args, os.Getenv)), tests hand it a fake. Source adopts the
	// injected getter without giving that seam up; the zero Source reads the
	// process environment.
	run := func(getenv func(string) string) (int, time.Duration) {
		env := envx.Source{Get: getenv}
		return env.Int("APP_RETRIES", 3), env.Duration("APP_INTERVAL", 6*time.Hour)
	}

	fake := map[string]string{"APP_RETRIES": "5"}
	retries, interval := run(func(name string) string { return fake[name] })
	fmt.Println(retries, interval)
}
Output:
5 6h0m0s

func (Source) Bool

func (s Source) Bool(key Key, fallback bool) bool

Bool returns the boolean value of the environment variable key, or fallback when the variable is unset or empty, with the package-level Bool's exact semantics: tolerant spellings, one Warn through slog's default logger on a malformed value.

func (Source) BoolStrict

func (s Source) BoolStrict(key Key) (value, ok bool, err error)

BoolStrict returns the boolean value of the environment variable key with the parse result owned by the caller, with the package-level BoolStrict's exact semantics: never logs, and the error names the key and the accepted spellings but never the value.

(value and ok share their bool type in the signature at the linter's insistence; they mean what the family's other strict variants mean.)

func (Source) Duration

func (s Source) Duration(key Key, fallback time.Duration) time.Duration

Duration returns the value of the environment variable key parsed with time.ParseDuration, or fallback when the variable is unset or empty, with the package-level Duration's exact semantics: a bare unitless number is rejected, and a malformed value logs one Warn through slog's default logger.

func (Source) DurationStrict

func (s Source) DurationStrict(key Key) (value time.Duration, ok bool, err error)

DurationStrict returns the value of the environment variable key parsed with time.ParseDuration, with the parse result owned by the caller and the package-level DurationStrict's exact semantics: never logs, and a malformed value returns a *ParseError carrying the key and the trimmed value.

func (Source) Int

func (s Source) Int(key Key, fallback int) int

Int returns the integer value of the environment variable key, or fallback when the variable is unset or empty, with the package-level Int's exact semantics: one Warn through slog's default logger on a malformed value.

func (Source) IntStrict

func (s Source) IntStrict(key Key) (value int, ok bool, err error)

IntStrict returns the integer value of the environment variable key with the parse result owned by the caller, with the package-level IntStrict's exact semantics: never logs, and a malformed value returns a *ParseError carrying the key and the trimmed value.

func (Source) Require

func (s Source) Require(key Key) (string, error)

Require returns the value of the environment variable key, or a *MissingError when it is unset or empty, with the package-level Require's exact semantics. It is on Source so a caller that injects its environment for tests (the run(args, getenv) seam) can require its one mandatory secret through the same seam it reads everything else through.

func (Source) String

func (s Source) String(key Key) string

String returns the value of the environment variable key, empty when the variable is unset or empty, with the package-level String's exact semantics: no trimming, whitespace-only counts as set, and the default is the caller's to compose with cmp.Or.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL