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):
- Base config files — all found (config.json, config.yaml, config.yml) merged
- 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.
- .env file — resolved via WithDotenvPath, CREDO_ENV_FILE, or default ".env"; read and parsed exactly once per Load. Disable with WithoutDotenv.
- 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 ¶
A Section names a section and its type once; its Section.Decode reads it from any RawConfig, and its method value is the constructor that binds the section in the container:
var ServerSection = config.Section[ServerConfig]("server")
serverCfg, err := ServerSection.Decode(c)
app.Provide(ServerSection.Decode)
Config.Unmarshal decodes into an existing value:
var serverCfg ServerConfig
c.Unmarshal("server", &serverCfg)
Reload ¶
A section is a snapshot unless it is declared live. Section.Live binds a Live handle whose value each reload that changes the section replaces whole; Live.Load reads it once per operation, and Live.OnChange keeps derived state in step:
var Limits = config.Section[LimitsConfig]("limits")
app.Provide(Limits.Live) // *config.Live[LimitsConfig]
A section is static or live within one configuration: reading one section through Section.Decode and through Section.Live fails, naming both reads. A raw Config.Unmarshal with a string key is outside that check.
Config.Reload re-reads every source the Config was built from, validates every live section the change touches before anything is published, then publishes the snapshot and the changed sections as one generation and runs their callbacks. It returns a ReloadResult naming the keys that changed, the sections it replaced, the keys whose change takes a restart and the file keys a later source keeps. It never switches CREDO_ENV, and a failed re-read or validation publishes nothing. The credo package calls it from SIGHUP and app.Reload (ADR-020).
Strict Decoding ¶
Every typed decode is strict: a key that maps to no field of the target is an error, and a value is not converted across kinds — a boolean into a number, a number into a string, a scalar into a list. Strings parse into the basic type of their target, so environment and .env overrides, which are always strings, decode into int, bool, float64 and duration fields, as they do into encoding.TextUnmarshaler targets. Each failure names its full key path. WithWeakDecoding opts in to mapstructure's weak coercion, under which unknown keys are ignored.
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 ¶
Examples ¶
Constants ¶
const ( FormatJSON = "json" FormatYAML = "yaml" )
Format constants for use with LoadBytes.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
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, and replaces the value of its live sections (Section.Live) in the same step.
func Load ¶
Load creates a Config instance and loads all configuration sources. Sources are merged in precedence order (lowest to highest):
- Base config files — all found among candidates, merged in order
- Env-specific files — config.{CREDO_ENV}.* when CREDO_ENV is set
- .env file (CREDO_ENV_FILE or default ".env") — all entries loaded, no prefix filtering
- 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; read a typed section with Section.Decode, or pass it to credo.WithRawConfig as-is.
func LoadBytes ¶
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; read a typed section with Section.Decode, or pass it to credo.WithRawConfig as-is.
func (*Config) Exists ¶
Exists reports whether the given key path exists in the merged configuration. Dots in the key always act as path separators.
func (Config) GoString ¶ added in v0.15.0
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
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) Reload ¶ added in v0.5.0
func (c *Config) Reload(ctx context.Context) (ReloadResult, error)
Reload re-reads every source the Config was built from — the same files (or the same embedded document for LoadBytes), the same .env resolution and the process environment — and applies the result to its live sections (ADR-020). The steps are:
- Re-read the sources into a candidate. A load error aborts the reload.
- Decode and validate, against the candidate, every live section whose keys the candidate changes. One failure aborts the reload: nothing is published, every live section keeps its value, and the result's Aborted names each failed section and its error.
- Publish the candidate and the changed sections' values as one generation: once a Live.Load returns this reload's value for one section, every later Load returns this reload's values or newer ones. No other value changes: a section read through Section.Decode keeps its snapshot.
- Run the Live.OnChange callbacks of the changed sections in registration order, with ctx. An error or a recovered panic is joined into the returned error, the later callbacks still run, and nothing rolls back. No callback is skipped when ctx ends.
- Return the result, whose RestartRequired lists every key whose value differs from the start's and that no live section covers.
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. Concurrent calls are serialized, callbacks included.
func (Config) String ¶ added in v0.15.0
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>".
Example ¶
Formatting a Config never shows its values or its keys.
package main
import (
"fmt"
"github.com/credo-go/credo/config"
)
// hermetic are the options that keep an example's load to its own document.
var hermetic = []config.Option{config.WithoutDotenv(), config.WithoutProcessEnv()}
func main() {
cfg, err := config.LoadBytes([]byte(`{"db": {"password": "s3cret"}}`), config.FormatJSON, hermetic...)
if err != nil {
panic(err)
}
fmt.Println(cfg)
fmt.Printf("%#v\n", *cfg)
}
Output: config.Config(1 keys, values redacted) config.Config(1 keys, values redacted)
func (*Config) Unmarshal ¶
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.
Decoding is strict unless the Config was loaded with WithWeakDecoding: a key under key that maps to no field of dst is an error, and a value is not converted across kinds — a boolean into a number, a number into a string, a scalar into a list. Strings parse into the basic type of their target (int, bool, float64 and the other numeric kinds), as do duration strings and encoding.TextUnmarshaler targets, so an environment or .env override of a typed field decodes. Each failure names its full key path.
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.
Example ¶
Unmarshal sets only the keys a source provides, so a pre-initialized value keeps its defaults; an explicit zero overrides one. Validate runs after the value is populated.
package main
import (
"errors"
"fmt"
"github.com/credo-go/credo/config"
)
// hermetic are the options that keep an example's load to its own document.
var hermetic = []config.Option{config.WithoutDotenv(), config.WithoutProcessEnv()}
type DatabaseConfig struct {
Host string
Port int
MaxOpenConns int
}
func DefaultDatabaseConfig() DatabaseConfig {
return DatabaseConfig{Host: "localhost", Port: 5432, MaxOpenConns: 25}
}
func (c *DatabaseConfig) Validate() error {
if c.Host == "" {
return errors.New("databases.default.host is required")
}
return nil
}
func main() {
rc, err := config.LoadBytes([]byte(`{"databases": {"default": {"host": "db", "max_open_conns": 0}}}`),
config.FormatJSON, hermetic...)
if err != nil {
panic(err)
}
dbCfg := DefaultDatabaseConfig()
err = rc.Unmarshal("databases.default", &dbCfg)
fmt.Printf("%+v %v\n", dbCfg, err)
rc, err = config.LoadBytes([]byte(`{"databases": {"default": {"host": ""}}}`), config.FormatJSON, hermetic...)
if err != nil {
panic(err)
}
dbCfg = DefaultDatabaseConfig()
fmt.Println(rc.Unmarshal("databases.default", &dbCfg))
}
Output: {Host:db Port:5432 MaxOpenConns:0} <nil> config: validation: databases.default.host is required
type Live ¶ added in v0.26.0
type Live[T any] struct { // contains filtered or unexported fields }
Live is the handle of a live section: a section whose value each reload that changes it replaces whole. A consumer that takes a *Live[T] says in its signature that the value can change:
var Limits = config.Section[LimitsConfig]("limits")
app.Provide(Limits.Live)
func NewOrderService(limits *config.Live[LimitsConfig]) *OrderService
Live.Load returns the current value with one atomic load. The type does not enforce two rules, which its consumers keep:
- Load once per operation, and use that value for the whole operation; a value kept past it, or read in a constructor, is the snapshot a reload does not change. Values that must agree within one operation belong to one section, since two Load calls can straddle a reload.
- Read the value's slices and maps, never write them: every Load of one reload shares them.
State derived from the section — a limiter, a compiled pattern, a slog.LevelVar — is updated in an Live.OnChange callback, not on each Load.
A Live is created by Section.Live over a *Config, or by Fixed for a consumer's unit test. A Live is safe for concurrent use.
func Fixed ¶ added in v0.26.0
Fixed returns a handle whose value is v and never changes, for a unit test of a consumer that takes a *Live[T]. Its Live.OnChange callbacks never run.
Example ¶
Fixed is a handle whose value never changes, for a consumer's unit test.
package main
import (
"fmt"
"github.com/credo-go/credo/config"
)
type LimitsConfig struct {
RPS int
Burst int
}
func main() {
limits := config.Fixed(LimitsConfig{RPS: 10, Burst: 20})
fmt.Printf("%+v\n", limits.Load())
}
Output: {RPS:10 Burst:20}
func (*Live[T]) Load ¶ added in v0.26.0
func (l *Live[T]) Load() T
Load returns the section's current value with one atomic load. Once a Load returns a reload's value for one section, every later Load of a live section of the same configuration returns that reload's values or newer ones.
func (*Live[T]) OnChange ¶ added in v0.26.0
OnChange registers fn for state derived from the section. fn runs after a reload that changes the section has published its new value, with the reload's context, the previous value and the new one. Callbacks of one configuration run in registration order, each once per reload that changes its section; an error or a recovered panic is joined into the reload's error, the later callbacks still run, and nothing rolls back. A callback still runs when the reload's context has been cancelled, since the next reload would not see the change again: it observes the cancellation through ctx.
A Fixed handle never changes, so its callbacks never run. OnChange panics for a nil fn.
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 ¶
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 ¶
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 ¶
WithLogger sets the logger used for load-time warnings (such as a missing optional .env file). Defaults to slog.Default.
func WithPrefix ¶
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 WithWeakDecoding ¶ added in v0.26.0
func WithWeakDecoding() Option
WithWeakDecoding makes every typed decode from this Config use mapstructure's weak coercion, under which unknown keys are ignored.
Without it a Config decodes strictly: a key that maps to no field of the target is an error, and a value is not converted across kinds. Strings still parse into the basic type of their target field, so an environment or .env override such as CREDO_SERVER__PORT=9090 decodes into an int. The policy rides on the Config instance: it covers Config.Unmarshal, a reload's candidate and the framework's own decode of the "server" section in credo.New.
Example ¶
Decoding is strict by default: an unknown key and a conversion across kinds fail with the key path and the opt-in; a string parses as its target type.
package main
import (
"fmt"
"github.com/credo-go/credo/config"
)
// hermetic are the options that keep an example's load to its own document.
var hermetic = []config.Option{config.WithoutDotenv(), config.WithoutProcessEnv()}
type AppConfig struct {
Name string
Port int
APIKey string
Region string `credo:"aws_region"`
}
var AppSection = config.Section[AppConfig]("app")
func main() {
doc := []byte(`{"app": {"name": "checkout", "port": "9090", "prot": 1}}`)
strict, err := config.LoadBytes(doc, config.FormatJSON, hermetic...)
if err != nil {
panic(err)
}
_, err = AppSection.Decode(strict)
fmt.Println(err)
weak, err := config.LoadBytes(doc, config.FormatJSON, append(hermetic, config.WithWeakDecoding())...)
if err != nil {
panic(err)
}
app, err := AppSection.Decode(weak)
fmt.Println(app.Port, err)
}
Output: config: section "app": config: unknown key "app.prot": no field of the target decodes it; fix the configuration, or opt in to weak coercion with config.WithWeakDecoding() 9090 <nil>
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 OverriddenKey ¶ added in v0.26.0
type OverriddenKey struct {
// Key is the dotted key path whose file value changed.
Key string `json:"key"`
// Source names the later source that keeps the key's value: the .env
// entry or the process environment variable.
Source string `json:"source"`
}
OverriddenKey is a file key whose change a later source hides.
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 ReloadResult ¶ added in v0.26.0
type ReloadResult struct {
// Published reports whether the reload published its snapshot. It is false
// when the sources failed to load or a live section failed to decode or
// validate, in which case every live section keeps its value.
Published bool `json:"published"`
// Aborted says why nothing was published, naming the live sections that
// failed and their errors; empty when Published is true.
Aborted string `json:"aborted,omitempty"`
// Changed lists the leaf keys whose value the reload changed, relative to
// the snapshot current before it, in sorted order.
Changed []string `json:"changed"`
// Replaced lists the keys of the live sections whose value the reload
// replaced, in the order the sections were declared live.
Replaced []string `json:"replaced"`
// RestartRequired lists, in sorted order, the leaf keys whose value
// differs from the one the start read and that no live section covers,
// a key of a section bound through Decode included: their change takes a
// restart. A reload that changes nothing keeps reporting them, and one
// that reverts a key to its start value clears it.
RestartRequired []string `json:"restart_required"`
// Overridden lists the keys whose file value differs from the one the
// start read while a later source, .env or the process environment, sets
// the key and so keeps its value.
Overridden []OverriddenKey `json:"overridden"`
}
ReloadResult reports what a reload did: the keys it changed, the live sections it replaced, the keys whose change takes a restart and the file keys a later source keeps. It names keys, never values, so it is safe to log and to return to an operator; its fields encode to JSON in snake_case.
type Section ¶ added in v0.26.0
Section names a configuration section and the type it decodes into, once:
var AppSection = config.Section[AppConfig]("app")
The key is a dotted path, as Config.Unmarshal takes. A Section is a named string type, so a declaration is a conversion and an untyped string constant converts to it wherever a Section is expected: app.GetConfig[AppConfig]("app") names the same section as app.GetConfig(AppSection).
The descriptor is the receiver of the call that reads it. Its Section.Decode method value is an ordinary constructor over the configuration, so binding a section in the container needs no App method:
app.Provide(AppSection.Decode) // a snapshot of the section, bound in DI
A section is a snapshot unless it is declared live: Section.Live binds a handle whose value each reload that changes the section replaces. A section is static or live within one configuration, and every read through its descriptor records which, so reading one section both ways fails.
A section that only one constructor reads, such as the section a database is opened from, is decoded in that constructor and not bound; two sections that decode into one type are each decoded where they are used, or bound under types of their own.
func (Section[T]) Decode ¶ added in v0.26.0
Decode decodes the section from src into a T, a snapshot that a reload does not change. It decodes through src's Unmarshal, so a *Config decodes strictly unless it was loaded with WithWeakDecoding, and a T that implements Validate() error is validated. A missing section, a decode failure and a failed validation are errors that name the section's key; so is an empty key, which would otherwise decode the whole tree.
Over a *Config, Decode records a static read of the section, and fails when the configuration reads the section, a section nested in it or one containing it as live, naming both reads.
Example ¶
A section's key and type are named once, by the descriptor; Decode reads it from any RawConfig.
package main
import (
"fmt"
"github.com/credo-go/credo/config"
)
// hermetic are the options that keep an example's load to its own document.
var hermetic = []config.Option{config.WithoutDotenv(), config.WithoutProcessEnv()}
type AppConfig struct {
Name string
Port int
APIKey string
Region string `credo:"aws_region"`
}
var AppSection = config.Section[AppConfig]("app")
func main() {
cfg, err := config.LoadBytes([]byte(`
app:
name: checkout
port: 8080
api_key: k-1
aws_region: eu-west-1
`), config.FormatYAML, hermetic...)
if err != nil {
panic(err)
}
app, err := AppSection.Decode(cfg)
fmt.Printf("%+v %v\n", app, err)
_, err = config.Section[AppConfig]("missing").Decode(cfg)
fmt.Println(err)
}
Output: {Name:checkout Port:8080 APIKey:k-1 Region:eu-west-1} <nil> config: section "missing": config: key "missing" not found
func (Section[T]) Live ¶ added in v0.26.0
Live decodes and validates the section from src as Section.Decode does and returns its live handle, registered with the configuration it read: each reload of that configuration that changes a key under the section replaces the handle's value whole, once every live section the reload changes has validated. Its method value is the constructor that binds the handle:
app.Provide(Limits.Live) // a *config.Live[LimitsConfig] in DI
src must be a *Config built by Load or LoadBytes; any other RawConfig cannot reload, and Live fails naming its type. A section is static or live within one configuration: Live fails when the configuration has read the section, a section nested in it, or one containing it as static (through Section.Decode, credo.App.GetConfig or the framework's own "server" section), naming both reads.
Example ¶
A live section is replaced whole by a reload that changes it, after it validated; its OnChange callbacks run after the new value is published. Every other change is reported as needing a restart.
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/credo-go/credo/config"
)
// hermetic are the options that keep an example's load to its own document.
var hermetic = []config.Option{config.WithoutDotenv(), config.WithoutProcessEnv()}
type LimitsConfig struct {
RPS int
Burst int
}
func main() {
dir, err := os.MkdirTemp("", "credo-config-example")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
file := filepath.Join(dir, "config.json")
write := func(doc string) {
if werr := os.WriteFile(file, []byte(doc), 0o600); werr != nil {
panic(werr)
}
}
write(`{"app": {"name": "checkout"}, "limits": {"rps": 10, "burst": 20}}`)
cfg, err := config.Load(append(hermetic, config.WithFiles(file))...)
if err != nil {
panic(err)
}
var Limits = config.Section[LimitsConfig]("limits")
limits, err := Limits.Live(cfg)
if err != nil {
panic(err)
}
limits.OnChange(func(ctx context.Context, prev, next LimitsConfig) error {
fmt.Println("changed:", prev.RPS, "→", next.RPS)
return nil
})
fmt.Println(limits.Load().RPS)
write(`{"app": {"name": "billing"}, "limits": {"rps": 50, "burst": 100}}`)
res, err := cfg.Reload(context.Background())
if err != nil {
panic(err)
}
fmt.Println(limits.Load().RPS)
out, _ := json.Marshal(res)
fmt.Println(string(out))
}
Output: 10 changed: 10 → 50 50 {"published":true,"changed":["app.name","limits.burst","limits.rps"],"replaced":["limits"],"restart_required":["app.name"],"overridden":[]}