config

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 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
  4. Process environment variables — CREDO_* prefix (configurable)

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.

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: experimental

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.

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 uses WeaklyTypedInput, 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) 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) 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.

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.

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.

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_").

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