cfgx

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package cfgx provides functionality to parse configuration from multiple sources in a predictable precedence order with strong error handling and traceability. It is designed to be flexible enough for most applications while providing sensible defaults that follow Go idioms and best practices. with a defined precedence: command line args > environment variables > yaml files > defaults. It uses struct tags to customize field names and validation rules.

Index

Constants

View Source
const (
	PriorityDefault = 0   // Default values from struct tags
	PriorityEnv     = 50  // Environment variables
	PrioritySecrets = 75  // Docker secrets and other file-based secrets
	PriorityFlags   = 100 // Command-line flags
)

Priority levels for built-in sources. Custom sources can use any priority value. Higher priority sources override lower priority sources.

Variables

View Source
var DefaultConfigOptions = Options{
	ProgramName:   os.Args[0],
	EnvPrefix:     "",
	SkipFlags:     false,
	SkipEnv:       false,
	Args:          os.Args[1:],
	ErrorHandling: flag.ContinueOnError,
	Sources:       []Source{},
}

DefaultConfigOptions are the default set of configuration options. Each option can be overridden.

View Source
var (
	ErrNotPointerToStruct = errors.New("config must be a pointer to a struct")
)

Functions

func Parse

func Parse(cfg any, options Options) error

Parse populates the config struct from different sources. It follows this priority order (highest to lowest):

Command line arguments - 100, Environment variables - 50, Default values from struct tags - 0

To add a source in order, choose a priority in between the included sources. Add a top level field named Version to read the build info into it (as of 1.24 it uses the git tag).

Types

type ConfigField

type ConfigField struct {
	Path        string
	Value       reflect.Value
	Kind        reflect.Kind
	Name        string
	StructField reflect.StructField
	Tag         reflect.StructTag
	Description string
}

ConfigField represents a field in the config struct.

type DockerSecretsSource

type DockerSecretsSource struct {
	SecretsPath string
	FileContentSource
}

DockerSecretsSource wraps a FileContentSource. It reads the docker secret file at “/run/secrets/<secret_name>“. It defaults to snake case based on the struct path. Override the name with the tag "dsec".

func NewDockerSecretsSource added in v0.2.0

func NewDockerSecretsSource() *DockerSecretsSource

NewDockerSecretsSource sets a priority of PrioritySecrets (75), a tag of "dsec", and a secrets path of `/run/secrets`.

func (*DockerSecretsSource) Process added in v0.2.0

func (s *DockerSecretsSource) Process(structMap map[string]ConfigField) error

Process opens an os.Root and calls the underlying FileContentSource's Process method with the os.Root.FS.

type FileContentSource

type FileContentSource struct {
	PriorityLevel int
	Tag           string
	FS            fs.FS
}

FileContentSource reads individual files. It can be used for any files that live in the same directory or have explicit file locations. Do not use this directly, use one of the implementations, e.g. DockerSecretsSource. This allows to use an os.Root.FS in the implementation's Process method.

func (*FileContentSource) Priority

func (s *FileContentSource) Priority() int

Priority implements Source.

func (*FileContentSource) Process

func (s *FileContentSource) Process(structMap map[string]ConfigField) error

Process implements Source.

type MultiError

type MultiError struct {
	Errors []error `json:"errors"`
}

MultiError holds multiple errors that occurred during parsing.

func (*MultiError) Error

func (m *MultiError) Error() string

Error implements error interface.

type Options

type Options struct {
	// ProgramName is the name of the running program (defaults to os.Args[0]).
	ProgramName string
	// EnvPrefix looks adds a prefix to environment variable lookups.
	EnvPrefix string
	// SkipFlags ignores command line flags.
	SkipFlags bool
	// SkipEnv ignores environment variables.
	SkipEnv bool
	// Args provides command line arguments (defaults to os.Args[1:]).
	Args []string
	// ErrorHandling determines how parsing errors are handled.
	ErrorHandling flag.ErrorHandling
	// Sources adds additional sources.
	Sources []Source
}

Options holds options for the Parse function.

type Source

type Source interface {
	Priority() int
	Process(map[string]ConfigField) error
}

Source processes the configField map and applies values to the config struct. Choose a priority to process before or after other sources.

type ValidationError

type ValidationError struct {
	Field  string `json:"field"`
	Value  any    `json:"value"`
	Reason string `json:"reason"`
}

ValidationError represents a configuration validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

Jump to

Keyboard shortcuts

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