Documentation
¶
Overview ¶
Package config provides a hierarchical, typed configuration system with explicit loading, validation, snapshots, notifications, and runtime locks.
Index ¶
- Variables
- func Value[T any](setting *Setting) (T, error)
- func WithContext(ctx context.Context, set *Set) context.Context
- type BindOption
- type BindOptions
- type Candidate
- type Change
- type ChangeFunc
- type ChangeNotifier
- type Codec
- type LockedError
- type Notifier
- type NotifyFunc
- type NotifyHandle
- type RawValue
- type RuntimeSource
- type Set
- func (s *Set) AddValidator(validator SetValidator) error
- func (s *Set) Apply(values map[string]string) error
- func (s *Set) Bind(value any, bindOptions ...BindOption) error
- func (s *Set) Dump(w io.Writer) error
- func (s *Set) Get(name string) *Setting
- func (s *Set) Load(ctx context.Context, sources ...Source) error
- func (s *Set) Loaded() bool
- func (s *Set) Lock()
- func (s *Set) Locked() bool
- func (s *Set) Lookup(path string) (*Setting, error)
- func (s *Set) LookupAbsolute(path string) (*Setting, error)
- func (s *Set) LookupRelative(name string) (*Setting, error)
- func (s *Set) Name() string
- func (s *Set) Notify(n Notifier) *NotifyHandle
- func (s *Set) Parent() *Set
- func (s *Set) Path() string
- func (s *Set) Range(fn func(string, *Setting) bool)
- func (s *Set) Reload(ctx context.Context, sources ...Source) error
- func (s *Set) Revision() uint64
- func (s *Set) Root() *Set
- func (s *Set) Setting(name string, value any, description string, options ...SettingOption) *Setting
- func (s *Set) Snapshot() (Snapshot, error)
- func (s *Set) Subset(name string) *Set
- func (s *Set) Update(name, value string) (bool, error)
- func (s *Set) Validate() error
- type SetValidator
- type Setting
- func (s *Setting) Equals(text string) bool
- func (s *Setting) IsDefault() bool
- func (s *Setting) Notify(n Notifier) *NotifyHandle
- func (s *Setting) NotifyChange(n ChangeNotifier) *NotifyHandle
- func (s *Setting) Set(text string) error
- func (s *Setting) String() string
- func (s *Setting) ValueType() reflect.Type
- type SettingError
- type SettingMetadata
- type SettingOption
- type SettingSnapshot
- type Snapshot
- type Source
- type SourceFunc
- type Validator
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound reports that a configuration setting or path does not exist. ErrNotFound = errors.New("configuration setting not found") // ErrAlreadyExists reports an attempt to register a duplicate setting. ErrAlreadyExists = errors.New("configuration setting already exists") // ErrInvalidPath reports a malformed configuration path. ErrInvalidPath = errors.New("invalid configuration path") // ErrNotLoaded reports an operation that requires an initial load. ErrNotLoaded = errors.New("configuration has not been loaded") // ErrAlreadyLoaded reports a second call to Load. ErrAlreadyLoaded = errors.New("configuration has already been loaded") // ErrLocked reports an attempted change to a locked setting. ErrLocked = errors.New("configuration setting is locked") // ErrSchemaLocked reports an attempt to change a locked schema. ErrSchemaLocked = errors.New("configuration schema is locked") // ErrUnsupported reports an unsupported setting type or operation. ErrUnsupported = errors.New("unsupported configuration type") )
Functions ¶
Types ¶
type BindOption ¶ added in v0.3.0
type BindOption func(*BindOptions)
BindOption customizes struct binding.
func FlattenAnonymous ¶ added in v0.3.0
func FlattenAnonymous() BindOption
FlattenAnonymous makes binding flatten anonymous nested structs.
type BindOptions ¶ added in v0.3.0
type BindOptions struct {
// FlattenAnonymous binds fields of anonymous nested structs into the parent set.
FlattenAnonymous bool
}
BindOptions configures how a struct is bound to a Set.
type Candidate ¶ added in v0.3.0
type Candidate struct {
// contains filtered or unexported fields
}
Candidate exposes the complete parsed configuration candidate to set validators.
type Change ¶ added in v0.3.0
type Change struct {
// Path is the canonical path of the changed setting.
Path string
// Old is the previous formatted value.
Old string
// New is the committed formatted value.
New string
// Revision identifies the configuration revision containing the change.
Revision uint64
}
Change describes one committed setting change.
type ChangeFunc ¶ added in v0.3.0
type ChangeFunc func(Change)
ChangeFunc adapts a function to ChangeNotifier.
func (ChangeFunc) NotifyChange ¶ added in v0.3.0
func (f ChangeFunc) NotifyChange(change Change)
NotifyChange implements ChangeNotifier.
type ChangeNotifier ¶ added in v0.3.0
type ChangeNotifier interface {
// NotifyChange receives a committed setting change.
NotifyChange(Change)
}
ChangeNotifier receives stable change records after a commit.
type Codec ¶ added in v0.3.0
type Codec interface {
// Parse converts text into the setting's value type.
Parse(string) (any, error)
// Format converts a setting value to text.
Format(any) (string, error)
// Equal reports whether two values represent the same setting value.
Equal(any, any) bool
}
Codec converts a setting value to and from its text representation.
Implementations can add support for application-specific setting types.
type LockedError ¶ added in v0.3.0
type LockedError struct {
// Path is the canonical path of the locked setting.
Path string
}
LockedError identifies a lockable setting that could not be changed.
func (*LockedError) Error ¶ added in v0.3.0
func (e *LockedError) Error() string
Error returns the locked setting error message.
func (*LockedError) Unwrap ¶ added in v0.3.0
func (e *LockedError) Unwrap() error
Unwrap returns ErrLocked.
type Notifier ¶
type Notifier interface {
// Notify receives the changed setting.
Notify(s *Setting)
}
Notifier receives a setting after its value changes.
type NotifyHandle ¶
type NotifyHandle struct {
// contains filtered or unexported fields
}
NotifyHandle is used to stop notifications of Setting changes
func (*NotifyHandle) Close ¶
func (h *NotifyHandle) Close() error
Close stops notifications. Calling Close more than once is safe.
type RawValue ¶ added in v0.3.0
type RawValue struct {
// Path is the source-provided setting path.
Path string
// Value is the unparsed setting text. An empty value is explicit.
Value string
// Source identifies the source for diagnostics.
Source string
}
RawValue is one source-provided configuration value.
type RuntimeSource ¶ added in v0.3.0
type RuntimeSource struct {
// contains filtered or unexported fields
}
RuntimeSource is a named, mutable source layer intended to survive reloads.
func NewRuntimeSource ¶ added in v0.3.0
func NewRuntimeSource(name string) *RuntimeSource
NewRuntimeSource creates a named runtime override source.
func (*RuntimeSource) Delete ¶ added in v0.3.0
func (source *RuntimeSource) Delete(path string) error
Delete removes an override from the runtime source.
func (*RuntimeSource) Load ¶ added in v0.3.0
func (source *RuntimeSource) Load(context.Context, iter.Seq[SettingMetadata]) ([]RawValue, error)
Load implements Source.
func (*RuntimeSource) Set ¶ added in v0.3.0
func (source *RuntimeSource) Set(path, value string) error
Set assigns an override in the runtime source.
type Set ¶
type Set struct {
// contains filtered or unexported fields
}
Set is a hierarchical collection of configuration settings.
func FromContext ¶
FromContext returns the set stored in ctx, or nil when no set is stored.
func (*Set) AddValidator ¶ added in v0.3.0
func (s *Set) AddValidator(validator SetValidator) error
AddValidator adds a validator for complete configuration candidates.
func (*Set) Apply ¶ added in v0.3.0
Apply parses, validates, and commits multiple setting updates atomically.
func (*Set) Bind ¶
func (s *Set) Bind(value any, bindOptions ...BindOption) error
Bind binds a pointer to a struct into s.
Fields can use setting, description, and mask tags. Bound fields are package-owned after binding and should be treated as read-only by callers.
Example ¶
package main
import (
"os"
"github.com/renevo/config"
)
func main() {
settings := config.NewSet()
// create just a simple struct
myConfig := struct {
Name string `description:"This is a name"`
Password string `description:"Super secret password" mask:"true"`
HTTP struct {
Addr string `setting:"Address" description:"Address to listen"`
Port int16 `description:"What port to listen"`
}
Enabled bool `description:"Enable something"`
}{
Name: "Default User",
}
// set values like normal
myConfig.HTTP.Addr = "0.0.0.0"
myConfig.HTTP.Port = 8080
// bind the configuration under MyApplication to the pointer of the config
applicationSet := settings.Subset("MyApplication")
if applicationSet == nil {
panic("unable to create application configuration set")
}
bindErr := applicationSet.Bind(&myConfig)
if bindErr != nil {
panic(bindErr)
}
// manually update a setting by full path (the value being set can come from os.GetEnv())
_, _ = settings.Update("MyApplication.Enabled", "true")
// dump the output
_ = settings.Dump(os.Stdout)
}
Output: Path Type Value Default Value Description Myapplication.Enabled *bool "true" "false" Enable something Myapplication.Http.Address *string "0.0.0.0" "0.0.0.0" Address to listen Myapplication.Http.Port *int16 "8080" "8080" What port to listen Myapplication.Name *string "Default User" "Default User" This is a name Myapplication.Password *string "*****" "*****" Super secret password
func (*Set) Load ¶ added in v0.3.0
Load establishes the initial configuration from defaults and sources.
func (*Set) Loaded ¶ added in v0.3.0
Loaded reports whether the initial configuration has been loaded.
func (*Set) Lock ¶ added in v0.3.0
func (s *Set) Lock()
Lock freezes the schema and prevents changes to lockable settings.
func (*Set) Lookup ¶ added in v0.3.0
Lookup finds a setting using relative-first, case-insensitive path lookup.
func (*Set) LookupAbsolute ¶ added in v0.3.0
LookupAbsolute finds a setting from the root configuration path.
func (*Set) LookupRelative ¶ added in v0.3.0
LookupRelative finds a setting relative to s.
func (*Set) Notify ¶
func (s *Set) Notify(n Notifier) *NotifyHandle
Notify subscribes to setting additions and changes in s and its children.
func (*Set) Range ¶
Range visits settings below s in canonical path order-independent registry order.
func (*Set) Reload ¶ added in v0.3.0
Reload replaces the loaded configuration from defaults and sources atomically.
func (*Set) Revision ¶ added in v0.3.0
Revision returns the committed revision number of the root configuration.
func (*Set) Setting ¶
func (s *Set) Setting(name string, value any, description string, options ...SettingOption) *Setting
Setting registers a setting in s. The name must not be empty and value must not be nil.
func (*Set) Snapshot ¶ added in v0.3.0
Snapshot returns a coherent view of the configuration at one revision.
type SetValidator ¶ added in v0.3.0
SetValidator checks a complete candidate configuration before it commits.
type Setting ¶
type Setting struct {
// Mask causes String and snapshots to hide the current and default values.
Mask bool
// Name is the local name of the setting.
Name string
// Description is user-facing text suitable for help output.
Description string
// DefaultValue is the formatted value used before sources are applied.
DefaultValue string
// Path is the canonical dot-separated path of the setting.
Path string
// Lockable marks a setting that cannot change after its owning set is locked.
Lockable bool
// contains filtered or unexported fields
}
Setting describes one registered configuration value.
func (*Setting) Notify ¶
func (s *Setting) Notify(n Notifier) *NotifyHandle
Notify subscribes to setting change notifications.
func (*Setting) NotifyChange ¶ added in v0.3.0
func (s *Setting) NotifyChange(n ChangeNotifier) *NotifyHandle
NotifyChange subscribes to stable old/new change records.
type SettingError ¶ added in v0.3.0
type SettingError struct {
// Path is the canonical setting path associated with the error.
Path string
// Source identifies the source that produced the error, when applicable.
Source string
// Err is the underlying cause.
Err error
}
SettingError adds path and source context to an underlying error.
func (*SettingError) Error ¶ added in v0.3.0
func (e *SettingError) Error() string
Error returns the contextual error message.
func (*SettingError) Unwrap ¶ added in v0.3.0
func (e *SettingError) Unwrap() error
Unwrap returns the underlying cause.
type SettingMetadata ¶ added in v0.6.0
type SettingMetadata struct {
// Path is the canonical setting path.
Path string
// Name is the setting name relative to its containing set.
Name string
// Description is the setting's user-facing description.
Description string
// Type is the registered Go type.
Type reflect.Type
// Masked reports whether the setting hides its value.
Masked bool
// Lockable reports whether locking the set prevents changes to the setting.
Lockable bool
}
SettingMetadata describes a registered setting without exposing its value or mutation APIs.
type SettingOption ¶ added in v0.3.0
type SettingOption func(*Setting)
SettingOption configures a setting at registration time.
func Lockable ¶ added in v0.3.0
func Lockable() SettingOption
Lockable marks a setting as protected by Set.Lock.
func WithCodec ¶ added in v0.3.0
func WithCodec(codec Codec) SettingOption
WithCodec uses codec to parse, format, and compare a setting value.
func WithLockable ¶ added in v0.3.0
func WithLockable(lockable bool) SettingOption
WithLockable sets whether a setting is protected by Set.Lock.
func WithValidator ¶ added in v0.3.0
func WithValidator(validator Validator) SettingOption
WithValidator validates a setting value before a transaction commits.
type SettingSnapshot ¶ added in v0.3.0
type SettingSnapshot struct {
// Path is the canonical setting path.
Path string
// Type is the registered Go type.
Type string
// Value is the formatted current value, masked when requested.
Value string
// DefaultValue is the formatted default value, masked when requested.
DefaultValue string
// Description is the setting's user-facing description.
Description string
// Masked reports whether the value was masked.
Masked bool
}
SettingSnapshot is an immutable textual view of one setting at a revision.
type Snapshot ¶ added in v0.3.0
type Snapshot struct {
// Revision is the configuration revision represented by Values.
Revision uint64
// Values contains settings sorted by canonical path.
Values []SettingSnapshot
}
Snapshot contains settings observed at one committed revision.
type Source ¶ added in v0.3.0
type Source interface {
// Load returns the raw values currently supplied by the source. Settings is
// a replayable, order-unspecified snapshot of registered setting metadata.
Load(context.Context, iter.Seq[SettingMetadata]) ([]RawValue, error)
}
Source supplies raw configuration values for Load and Reload.
func EnvironmentSource ¶ added in v0.6.0
EnvironmentSource reads registered settings from environment variables. Prefix is normalized when the source loads; an invalid prefix fails loading.
type SourceFunc ¶ added in v0.3.0
SourceFunc adapts a function to Source.
func (SourceFunc) Load ¶ added in v0.3.0
func (source SourceFunc) Load(ctx context.Context, settings iter.Seq[SettingMetadata]) ([]RawValue, error)
Load implements Source.