config

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package config loads typed values from OS environment variables using schema-driven coercion.

FromEnv and FromEnvVar are pure functions — no adapter, no [ports.Pattern], no port. Config loading is standalone by nature: it happens once at startup, before any pipeline or transport exists, so there is nothing to bind it to. This is different from [ports.File] and [ports.Cache], which ARE declarative descriptors bound via a Pattern to an adapter family (adapters/file, adapters/redis) — see [ports]'s "Design pattern: declarative descriptor + plain function" section for the full comparison across building blocks.

Struct loading — FromEnv

FromEnv[T] loads an entire struct from environment variables using the codec's schema for schema-driven type coercion:

cfg, err := config.FromEnv(configCodec, "APP_")
// err is codex.ValidationErrors — parse errors + missing required + constraints

Naming convention: strings.ToUpper(prefix + field_name). Nested structs expand to prefixed vars (APP_DB_HOST) or accept a JSON object (APP_DB='{"host":"..."}'); slices accept comma-separated values (APP_TAGS=a,b,c) or a JSON array. See FromEnv's doc for the full coercion table.

Single variable — FromEnvVar

FromEnvVar[T] loads one typed value from a single environment variable:

port, err := config.FromEnvVar("APP_PORT", codex.Int().Refine(validate.RangeInt(1, 65535)))

Returns the zero value of T when the variable is not set — this is not an error. Returns EnvVarError wrapping codex.ValidationErrors when coercion or a Refine constraint fails.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromEnv

func FromEnv[T any](c codex.Codec[T], prefix string) (T, error)

FromEnv loads T from environment variables using schema-driven type coercion.

Naming convention: strings.ToUpper(prefix + field_name). Underscores in field names are preserved:

field "log_level"  + prefix "APP_" → "APP_LOG_LEVEL"
field "db"         + prefix "APP_" → recurse with prefix "APP_DB_"
nested field "host"                → "APP_DB_HOST"

Supported types (determined from the codec's schema):

flat primitives — direct env var, string coerced by schema type
nested structs  — prefix expansion (APP_DB_HOST) OR JSON object (APP_DB='{"host":"..."}')
slices          — comma-separated (APP_TAGS=a,b,c) OR JSON array (APP_TAGS='["a","b","c"]')
StringMap       — JSON object only (APP_LABELS='{"k":"v"}')
Nullable[T]     — absent = nil; present = coerce as inner type

JSON detection: when a field's env var is set and the value starts with '{' or '[' matching the field's schema type, it is parsed as JSON. JSON takes precedence over prefix expansion and comma-split when both would apply (e.g. APP_DB='{...}' takes priority over APP_DB_HOST=...).

Silently skipped: TaggedUnion, slices of objects.

Errors are returned as codex.ValidationErrors. Parse errors (an env var is set but its value cannot be coerced to the field's type) are collected and returned before the codec's Decode runs. Missing required fields and constraint violations are reported by Decode in the same error shape.

func FromEnvVar

func FromEnvVar[T any](key string, c codex.Codec[T]) (T, error)

FromEnvVar loads a single typed value from one environment variable.

The codec's schema determines the string coercion (integer, number, boolean, string). All Refine constraints run after coercion — the same rules apply as in any codec Decode call.

Returns EnvVarError wrapping a codex.ValidationErrors when coercion or constraint validation fails. Returns the zero value of T when the variable is not set. Use errors.As to inspect the structured error:

port, err := config.FromEnvVar("APP_PORT", codex.Int().Refine(validate.RangeInt(1, 65535)))
if err != nil {
    var envErr config.EnvVarError
    if errors.As(err, &envErr) {
        slog.Warn("env var invalid", "key", envErr.Key, "cause", envErr.Err)
    }
}

Types

type EnvVarError

type EnvVarError struct {
	// Key is the environment variable name (e.g. "APP_PORT").
	Key string
	// Err is the underlying coercion or validation error.
	// Typically wraps [codex.ValidationErrors].
	Err error
}

EnvVarError is returned by FromEnvVar when coercion or codec validation fails for a single environment variable.

Use errors.As to extract the key and structured cause:

var envErr config.EnvVarError
if errors.As(err, &envErr) {
    slog.Warn("env var invalid", "key", envErr.Key, "cause", envErr.Err)
    stats.ReportErrors(obs, "env", envErr.Err)
}

func (EnvVarError) Error

func (e EnvVarError) Error() string

func (EnvVarError) LogValue

func (e EnvVarError) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (EnvVarError) Unwrap

func (e EnvVarError) Unwrap() error

Unwrap allows errors.Is and errors.As to traverse the underlying error.

Jump to

Keyboard shortcuts

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