config

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package config provides struct-centric configuration loading with deterministic merge order. A single-pass Load merges files, the .env file, and environment variables into one nested map, exposed through the high-level Credo API focused on type safety and developer ergonomics.

Source Precedence

Configuration merges in this order (later overrides earlier):

  1. Base config files — all found (config.json, config.yaml, config.yml) merged
  2. Env-specific files — when CREDO_ENV is set (via process env or the .env file). Discovery mode: config.{env}.*. Explicit mode (WithFiles): name.{env}.ext.
  3. .env file — resolved via WithDotenvPath, CREDO_ENV_FILE, or default ".env"; read and parsed exactly once per Load. Disable with WithoutDotenv.
  4. Process environment variables — CREDO_* prefix (configurable). Disable with WithoutProcessEnv.

Each opt-out removes its source entirely, bootstrap keys included: WithoutProcessEnv also ignores the env-sourced CREDO_ENV and CREDO_ENV_FILE values, and WithoutDotenv never reads any .env file. Combining both with WithFiles (or LoadBytes) yields fully hermetic loading where only the listed files (or the embedded document) are read.

Quick Start

type AppConfig struct {
    Debug  bool         // auto-mapped to key "debug"
    Server ServerConfig `credo:"server"` // decodes the nested "server" sub-tree
}

type ServerConfig struct {
    Port int // auto-mapped to key "port"
}

c, err := config.Load()
if err != nil {
    log.Fatal(err)
}
var cfg AppConfig
if err := c.Unmarshal("", &cfg); err != nil {
    log.Fatal(err)
}

Sub-Tree Access

Read a typed section in one call with the generic Config.Get method, or decode into an existing value with Config.Unmarshal:

serverCfg, err := c.Get[ServerConfig]("server")

var serverCfg ServerConfig
c.Unmarshal("server", &serverCfg)

Reload

Config.Reload re-reads every source the Config was built from and swaps the tree in atomically, returning the leaf keys that changed. It never switches CREDO_ENV, and a failed re-read leaves the previous snapshot in place. Config.Stage is the two-phase form: inspect the candidate through the returned Staged handle, then Commit. The credo package drives these from SIGHUP or app.Reload, validating typed per-section subscribers against the candidate before committing (ADR-020); call them directly only when you own the reload trigger yourself.

Strict Decoding

WithStrictDecoding makes every typed decode reject unknown keys and disables weak string-to-number/bool coercion (TextUnmarshaler and duration strings keep working). It suits typed sources — config files and LoadBytes documents — and pairs naturally with WithoutProcessEnv and WithoutDotenv; string env overrides on typed fields do not decode under strict mode. The default remains weak decoding.

Custom Prefix

Use WithPrefix to override the default "CREDO_" env var prefix:

c, err := config.Load(config.WithPrefix("MYAPP_"))

Adapted From

Map-merge utilities adapted from koanf (MIT). See NOTICES file for full attribution.

Maturity: beta

Index

Constants

View Source
const (
	FormatJSON = "json"
	FormatYAML = "yaml"
)

Format constants for use with LoadBytes.

Variables

This section is empty.

Functions

This section is empty.

Types

type Changes added in v0.5.0

type Changes struct {
	// contains filtered or unexported fields
}

Changes is the set of leaf key paths whose value differs between two configuration snapshots — added, removed, or changed. It records key paths only, never values, so it is safe to log.

func (Changes) Affects added in v0.5.0

func (c Changes) Affects(prefix string) bool

Affects reports whether any changed key equals prefix or lies under it ("server" matches "server.port"). The empty prefix matches any change.

func (Changes) Empty added in v0.5.0

func (c Changes) Empty() bool

Empty reports whether nothing changed.

func (Changes) Keys added in v0.5.0

func (c Changes) Keys() []string

Keys returns a copy of the changed leaf key paths in sorted order.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config holds configuration loaded from files, .env, and environment variables, merged into a single nested map. Create with Load or LoadBytes, then use Config.Unmarshal to extract typed values. Pass an empty key to decode the entire configuration tree.

A Config is safe for concurrent reads. Config.Reload replaces the whole tree atomically, so concurrent readers observe either the previous or the new snapshot, never a mix.

func Load

func Load(opts ...Option) (*Config, error)

Load creates a Config instance and loads all configuration sources. Sources are merged in precedence order (lowest to highest):

  1. Base config files — all found among candidates, merged in order
  2. Env-specific files — config.{CREDO_ENV}.* when CREDO_ENV is set
  3. .env file (CREDO_ENV_FILE or default ".env") — all entries loaded, no prefix filtering
  4. Process environment variables (prefix-filtered, default "CREDO_")

The .env file is read and parsed once: CREDO_ENV is taken from it before file loading (the process environment wins), and its entries are merged into the config tree after file loading.

Layers 3 and 4 can be disabled entirely with WithoutDotenv and WithoutProcessEnv; each opt-out also removes its source's bootstrap keys (CREDO_ENV, CREDO_ENV_FILE) from consideration.

Load is NOT concurrency-safe; call it once at startup.

The returned *Config satisfies RawConfig; use Config.Get for typed snapshot access or pass it to credo.WithRawConfig as-is.

func LoadBytes

func LoadBytes(data []byte, format string, opts ...Option) (*Config, error)

LoadBytes creates a Config from raw bytes. After parsing, .env and environment variable layers are applied on top (same as Load). This is useful with go:embed to bundle config files in the binary.

//go:embed config.json
var configData []byte

rc, err := config.LoadBytes(configData, config.FormatJSON)

The returned *Config satisfies RawConfig; use Config.Get for typed snapshot access or pass it to credo.WithRawConfig as-is.

func (*Config) Exists

func (c *Config) Exists(key string) bool

Exists reports whether the given key path exists in the merged configuration. Dots in the key always act as path separators.

func (*Config) Get

func (c *Config) Get[T any](key string) (T, error)

Get decodes the value or sub-tree at the given dotted key path into a value of type T and returns it. It is the typed-snapshot form of Config.Unmarshal:

db, err := cfg.Get[DatabaseConfig]("database")
port, err := cfg.Get[int]("server.port")

T may be a struct, map, slice, or primitive. The same rules as Config.Unmarshal apply: a missing key or decode failure returns an error, type coercion is weak by default and strict under WithStrictDecoding, and a T implementing Validate() error is validated after decoding. On error the zero value of T is returned.

Get is a bootstrap/composition-root helper. Prefer extracting typed config here and injecting it into services via DI over reading string keys inside business code.

func (Config) GoString added in v0.15.0

func (c Config) GoString() string

GoString returns the same redacted description as Config.String, so the %#v verb cannot dump the config tree either.

func (Config) LogValue added in v0.15.0

func (c Config) LogValue() slog.Value

LogValue implements slog.LogValuer with the same redacted description, so passing a Config or *Config as an slog attribute value logs metadata only.

func (*Config) MustGet

func (c *Config) MustGet[T any](key string) T

MustGet is like Config.Get but panics on error. It suits bootstrap and composition-root code where a missing or invalid required key should abort startup.

func (*Config) Reload added in v0.5.0

func (c *Config) Reload() (Changes, error)

Reload re-reads every source the Config was created from — the same files (or the same embedded document for LoadBytes), the same .env resolution, and the process environment — builds a fresh tree, and swaps it in atomically. It returns the leaf keys whose values differ from the previous snapshot.

The effective CREDO_ENV is fixed at the first load: Reload does not switch environments, because that would swap entire file sets under sections that were never designed to change at runtime (ADR-020).

On any read or parse error the previous snapshot stays current and the error is returned. Reload is safe to call concurrently with readers; concurrent Reload calls are serialized by the caller (the App does this), and the last one to finish wins.

func (*Config) Stage added in v0.5.0

func (c *Config) Stage() (Staged, error)

Stage re-reads every source exactly as Config.Reload does, but returns the candidate as a Staged handle instead of publishing it. Readers keep seeing the current snapshot until Commit. Changes are computed against the snapshot current at Stage time; callers that stage concurrently must serialize themselves (the App does), as the last Commit wins.

func (Config) String added in v0.15.0

func (c Config) String() string

String returns a redacted, metadata-only description of the Config — the number of leaf keys, never any key names or values — so formatting a Config with %v, %s, or %+v cannot leak secrets into logs or error messages. The formatting methods are declared on the value type, so they cover both *Config and a dereferenced copy (*cfg); a nil *Config formats as fmt's usual "<nil>".

func (*Config) Unmarshal

func (c *Config) Unmarshal(key string, dst any) error

Unmarshal decodes the value or sub-tree at the given dotted key path into dst. dst must be a pointer to a struct, map, slice, or primitive (e.g., *int, *string, *bool, *float64, *time.Duration).

Pass an empty key ("") to decode the entire configuration tree into dst. Dots in the key always act as path separators.

By default, type coercion uses mapstructure's WeaklyTypedInput, which handles common conversions like string to int, string to bool, int to float64, etc. This is particularly useful when env vars (always strings) override typed YAML/JSON values. Under WithStrictDecoding, weak coercion is off and unknown keys are rejected; see that option for the full policy.

If dst implements Validate() error, validation is called automatically after a successful decode.

A present but null value (YAML/JSON null) is a no-op: dst is left unchanged and no error is returned. A null overlays nothing — mirroring how a partial section overlays only the keys it contains — so it neither zeroes dst nor is misreported as missing (Exists still reports it as present). A null never resets dst: to clear a value, set it explicitly in the config or decode into a fresh zero-value target.

Returns an error if the key does not exist or decoding fails.

type Option

type Option func(*options)

Option configures the loading behavior of a Config instance.

func WithDotenvOptional

func WithDotenvOptional() Option

WithDotenvOptional makes a missing explicit .env file a warning instead of an error. This only affects explicit paths set via WithDotenvPath or the CREDO_ENV_FILE environment variable. The default implicit ".env" is always optional regardless of this setting.

func WithDotenvPath

func WithDotenvPath(path string) Option

WithDotenvPath overrides the .env file path. Takes precedence over the CREDO_ENV_FILE environment variable. Useful for binary-relative deployments where the working directory differs from the project root.

By default, an explicit path must exist: if the file is missing, Load returns an error. To make a missing file non-fatal, combine with WithDotenvOptional. Combining with WithoutDotenv is contradictory and makes Load return an error.

func WithFiles

func WithFiles(files ...string) Option

WithFiles overrides the default config file discovery list. All found files are loaded and merged in order (later files override earlier ones for overlapping keys).

Unlike the default discovery list, explicitly specified files are required: if none of the listed files exist, Load returns an error.

When CREDO_ENV is set (via process env or .env file), env-specific files are derived from each listed file by inserting ".{env}" before the extension (e.g., "myapp.yaml" becomes "myapp.production.yaml"). Derived files are optional — missing derived files are silently skipped.

Pass an empty list to explicitly disable file loading.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger used for load-time warnings (such as a missing optional .env file). Defaults to slog.Default.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix overrides the default environment variable prefix ("CREDO_").

An empty prefix does not disable the environment source — it removes the filter, so every process environment variable is merged into the tree. To disable the source entirely, use WithoutProcessEnv.

func WithStrictDecoding added in v0.15.0

func WithStrictDecoding() Option

WithStrictDecoding makes every typed decode from this Config strict: unknown keys — keys present in the configuration that do not map to a field of the target — become errors (nested sections included), and weak type coercion is disabled, so a string "123" no longer decodes into an int and a string "true" no longer decodes into a bool. Two deliberate coercions are retained: strings still decode through encoding.TextUnmarshaler implementations, and duration strings such as "5s" still decode into time.Duration. Numeric kind conversions (a JSON number into an int or float field) are native decoding, not weak coercion, and keep working.

The policy rides on the Config instance: it applies to Config.Unmarshal, Config.Get, Config.MustGet, the Staged candidate produced by Config.Stage (and therefore to reload subscriber validation), and to the framework's own decode of the "server" section when the Config is passed to credo.New — an unknown key under "server" then fails app construction.

Strict decoding is designed for typed sources (config files, LoadBytes documents). Environment variables and .env entries are always strings, so string-to-number and string-to-bool overrides on typed fields fail to decode under strict mode — pair it with WithoutProcessEnv and WithoutDotenv, or keep the default weak decoding when such overrides are needed. Under strict mode every typed view must also be complete: a struct that decodes a section (including narrow reload subscribers) must cover all of that section's keys.

Unknown-key errors report key paths and never configuration values; type mismatch errors may quote the offending value.

func WithoutDotenv added in v0.15.0

func WithoutDotenv() Option

WithoutDotenv disables the .env file as a configuration source. No .env file is read at all: the default ".env" is not probed, CREDO_ENV_FILE is not consulted, and no CREDO_ENV bootstrap value can come from a .env file. Combining it with an explicit WithDotenvPath is contradictory and makes Load (and LoadBytes) return an error.

func WithoutProcessEnv added in v0.15.0

func WithoutProcessEnv() Option

WithoutProcessEnv disables the process environment as a configuration source. No environment variables are merged into the tree (regardless of WithPrefix), and the env-sourced bootstrap keys are ignored too: CREDO_ENV is not read from the process environment and CREDO_ENV_FILE does not influence .env resolution. WithDotenvPath still works, and a CREDO_ENV entry inside an applicable .env file still drives env-specific file derivation — combine with WithoutDotenv for fully hermetic loading where only the config files (or LoadBytes document) are read.

type RawConfig

type RawConfig interface {
	// Unmarshal decodes the value or sub-tree at the given dotted key path
	// into dst. dst must be a pointer (to a struct, map, slice, or primitive).
	// Returns an error if the key does not exist or decoding fails.
	Unmarshal(key string, dst any) error

	// Exists reports whether the given key path exists in the merged configuration.
	Exists(key string) bool
}

RawConfig provides low-level access to the merged configuration. This is a bootstrap mechanism — application code should use typed config structs injected via DI instead of calling RawConfig directly.

Unmarshal decodes both struct sections and primitive values:

var port int
rawCfg.Unmarshal("server.port", &port)

var dbCfg DatabaseConfig
rawCfg.Unmarshal("databases.default", &dbCfg)

type Reloader added in v0.5.0

type Reloader interface {
	Reload() (Changes, error)
}

Reloader is implemented by configuration stores that can re-read their sources at runtime. *Config implements it; a custom RawConfig opts into the App-level reload (see the credo package and ADR-020) by implementing it too.

Reload must be atomic from a reader's point of view — after it returns, a concurrent Unmarshal or Exists sees either the previous or the new snapshot, never a mix — and must leave the previous snapshot untouched on error.

A store that also implements Stager lets the App validate the new snapshot before it is published; a Reloader-only store is reloaded first and validated afterwards, so a bad value reaches readers before it is reported.

type Staged added in v0.5.0

type Staged interface {
	RawConfig
	Changes() Changes
	Commit()
}

Staged is a candidate snapshot produced by Stager.Stage. Its RawConfig methods read the candidate, Changes reports how it differs from the snapshot that was current when it was staged, and Commit publishes it atomically. A Staged that is never committed is simply discarded.

type Stager added in v0.5.0

type Stager interface {
	Stage() (Staged, error)
}

Stager is the two-phase form of Reloader: Stage re-reads the sources into a candidate snapshot that can be inspected through the Staged handle without affecting readers, and Staged.Commit publishes it. The App uses this form when available so that typed subscribers are decoded and validated against the candidate and a failure leaves the previous snapshot current.

*Config implements Stager; Config.Reload is Stage followed by Commit.

Jump to

Keyboard shortcuts

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