Help us shape the future of Go! Take the 2026 Go Developer Survey

config

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package config decodes layered settings through typed field declarations. Feature packages own their settings structs, keys, defaults and validation.

Index

Constants

View Source
const MaxTableBytes = 1 << 20
View Source
const MaxTableEntries = namedservice.MaxEntries

Variables

This section is empty.

Functions

func DecodeTable

func DecodeTable[K ~string, V any](raw string, schema *Schema[V], defaults func(K) V, validate func(V) error) (map[K]V, error)

DecodeTable decodes named objects using the SAME generated element schema as ordinary settings. Durations remain duration strings, secrets retain their codec and unknown fields fail. Defaults is called once for every input name. Each supplied table REPLACES the whole collection: it does not merge entries with earlier layers. Typed overrides also replace the collection. Empty maps are allowed; an enabled service family's validator requires its default. Names follow the service identifier grammar. Duplicate JSON keys, null, oversized input and excessive depth fail without a partial result.

func ValidateNamespace

func ValidateNamespace(namespace string) error

ValidateNamespace uses the same grammar as configuration field names.

Types

type Entry

type Entry struct {
	Name   string
	Source string
	Secret bool
}

Entry records provenance without storing or formatting a setting's value.

type Field

type Field[T any] interface {
	// contains filtered or unexported methods
}

Field is a sealed typed setting declaration, normally generated from a feature's settings type. It does not expose untyped getters to consumers.

type Inputs

type Inputs[T any] struct {
	Files       []Values
	Environment Lookup
	Environ     func() []string
	Prefix      string
	Overrides   []Override[T]
	Validate    func(T) error
}

Inputs always applies files in order, then environment, then typed overrides. Environment names use PREFIX__SECTION__FIELD for a section.field declaration. NAME_FILE instead reads the value from the named regular file (at most MaxTableBytes, one trailing newline removed); setting both is an error.

Environ, such as os.Environ, additionally enables per-entry overrides inside named collections: PREFIX__SERVICES__DATABASE__CONNECTIONS__MAIN__PRIMARY__PASSWORD sets primary.password of entry "main" (entry names of lowercase letters, digits and single underscores). They merge into the collection supplied by a file or the collection's own variable, or create entries in an empty one, then decode through the same element schema. _FILE applies to them too.

type Key

type Key[T, V any] struct {
	// contains filtered or unexported fields
}

Key couples a configuration identifier to its concrete Go field and decoder. The field accessor is compiler-checked; no reflection-based field-name lookup or automatic dependency injection is performed.

func Bool

func Bool[T any](name string, field func(*T) *bool) Key[T, bool]

Bool declares a boolean configuration key.

func Duration

func Duration[T any](name string, field func(*T) *time.Duration) Key[T, time.Duration]

Duration declares a duration configuration key parsed with time.ParseDuration.

func Enum

func Enum[T any, V enum.Scalar](name string, field func(*T) *V, descriptor enum.Descriptor[V]) Key[T, V]

Enum retains descriptor membership for file/environment values, defaults and typed overrides. A type-correct but undeclared Go enum value is still invalid.

func Int

func Int[T any](name string, field func(*T) *int) Key[T, int]

Int declares an integer configuration key.

func JSON

func JSON[T, V any](name string, field func(*T) *V) Key[T, V]

JSON declares a structured setting, such as a slice, map or settings struct. Its text representation is JSON in every source, including environment variables. File adapters normalize collections into that representation. Unknown struct fields and trailing JSON values are rejected. Custom decoding behavior, including null handling, follows the declared Go type's JSON codec.

func NewKey

func NewKey[T, V any](name string, field func(*T) *V, parse func(string) (V, error)) Key[T, V]

NewKey declares a field accessor and text decoder without resolving the field by reflection. Schema construction validates the declaration's name/functions.

func Scalar

func Scalar[T any, V ScalarValue](name string, field func(*T) *V) Key[T, V]

Scalar declares a scalar with its exact Go width. Reflection operates only on the decoded scalar; the compiler-checked accessor owns the destination field. No runtime field-name lookup is used. Floating values must be finite.

func Secret

func Secret[T any](name string, field func(*T) *secret.String) Key[T, secret.String]

Secret declares a sensitive configuration key containing a secret string.

func String

func String[T any](name string, field func(*T) *string) Key[T, string]

String declares a string configuration key.

func Text

func Text[T, V any, P interface {
	*V
	encoding.TextUnmarshaler
}](name string, field func(*T) *V) Key[T, V]

Text declares a value with an encoding.TextUnmarshaler implementation. A fresh value is decoded on every load; decoder errors never return a partial value.

func (Key[T, V]) Name

func (k Key[T, V]) Name() string

Name returns the configuration key's identifier.

func (Key[T, V]) Sensitive

func (k Key[T, V]) Sensitive() Key[T, V]

Sensitive returns a copy of the key marked private.

func (Key[T, V]) Set

func (k Key[T, V]) Set(value V) Override[T]

Set creates a typed override for the key.

type Lookup

type Lookup func(string) (string, bool)

Lookup matches os.LookupEnv and is injectable for deterministic tests.

type Override

type Override[T any] struct {
	// contains filtered or unexported fields
}

Override is produced by Key.Set, preserving the value type at the call site.

type PublicKind added in v0.3.0

type PublicKind string

PublicKind classifies the browser validation and decoding applied to a public setting.

const (
	PublicString       PublicKind = "string"
	PublicBoolean      PublicKind = "boolean"
	PublicNumber       PublicKind = "number"
	PublicLocale       PublicKind = "locale"
	PublicFormatLocale PublicKind = "format_locale"
	PublicCurrency     PublicKind = "currency"
	PublicTimeZone     PublicKind = "time_zone"
	PublicEnum         PublicKind = "enum"
)

func (PublicKind) Validate added in v0.3.0

func (k PublicKind) Validate() error

Validate checks that the public configuration kind is supported; the empty kind is allowed.

type PublicSetting added in v0.3.0

type PublicSetting struct {
	Name        string     `json:"name"`
	Env         string     `json:"env"`
	Description string     `json:"description,omitempty"`
	Fallback    string     `json:"fallback,omitzero"`
	Optional    bool       `json:"optional,omitempty"`
	Kind        PublicKind `json:"kind"`
	MaxLength   int        `json:"max_length,omitzero"`
	EnumCases   []string   `json:"enum_cases,omitempty"`
}

PublicSetting is a browser-visible configuration setting declared in Go. Optional settings decode missing or blank browser values as undefined and cannot declare a non-empty fallback.

type Report

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

Report is immutable provenance, suitable for diagnostics without credentials.

func (Report) Entries

func (r Report) Entries() []Entry

Entries returns a copy of the report's entries.

type ScalarValue

type ScalarValue interface {
	~string | ~bool | ~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
}

ScalarValue preserves named Go scalar types at the configuration boundary. Complex numbers, pointers and machine addresses are not configuration values.

type Schema

type Schema[T any] struct {
	// contains filtered or unexported fields
}

Schema owns validated, ordered field declarations. It is safe for concurrent Load calls provided caller-supplied accessors/decoders are themselves safe.

func New

func New[T any](fields ...Field[T]) (*Schema[T], error)

New validates and snapshots a settings struct's field declarations. Duplicate names and environment-name collisions fail before any input is decoded.

func (*Schema[T]) Load

func (s *Schema[T]) Load(defaults T, inputs Inputs[T]) (result T, report Report, err error)

Load returns caller-owned configuration plus value-free provenance. Defaults and reference-containing override values are copied, so one application/load cannot mutate another application's defaults. Invalid loads return no partial configuration; parse and validation causes are retained but not formatted.

func (*Schema[T]) Names

func (s *Schema[T]) Names() []string

Names returns declared setting names in declaration order. File adapters use this snapshot to resolve namespaces against the same schema as Load.

func (*Schema[T]) WithinNamespace

func (s *Schema[T]) WithinNamespace(namespace string) error

WithinNamespace requires every key to be a descendant of the selected namespace. It never rewrites keys or silently drops unknown input values.

type Values

type Values struct {
	Name string
	Data map[string]string
}

Values is the text-value boundary implemented by file format adapters. Values use declared setting names; unknown file entries are errors, never ignored.

func DecodeObject

func DecodeObject[T any](object map[string]any, schema *Schema[T], source string) (Values, error)

DecodeObject converts a normalized object into a schema-owned layer. It is shared by TOML and nested named tables; field decoding remains owned by Schema. Supported scalars are strings, booleans, int64, float64 and json.Number. Collections at declared keys become JSON for that key's codec. Dotted object keys are rejected rather than ambiguously reinterpreted as namespace paths.

Directories

Path Synopsis
Package toml adapts bounded TOML documents to Foundry's typed configuration schema.
Package toml adapts bounded TOML documents to Foundry's typed configuration schema.

Jump to

Keyboard shortcuts

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