xconfig

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 10 Imported by: 0

README

xconfig

Unified configuration loading for Go applications with support for multiple formats and sources.

 

This package provides a configuration loader abstraction based on parsers. Each parser implements a common interface that converts external sources into a normalized internal map with lowercased, trimmed keys.


Purpose

xconfig is designed to centralize configuration loading from multiple sources (environment variables, .env files, JSON, YAML) and to compose multiple parsers with deterministic linear override priority.

It exposes:

  • xconfig.Parser — generic interface for configuration providers.
  • xconfig.Config — concurrent-safe structure for storing and querying data.
  • xconfig.InitAppConfig — bootstrap function for registering parsers and loading data.

Installation

Use go get pointing to the package module:

  go get github.com/AeonDigital/Go-Core/xconfig@latest

In your code, import the required dependencies:

import (
    "github.com/AeonDigital/Go-Core/xconfig"
    "github.com/AeonDigital/Go-Core/xconfig/parser/dotenv"
    "github.com/AeonDigital/Go-Core/xconfig/parser/json"
    "github.com/AeonDigital/Go-Core/xconfig/parser/varenv"
    "github.com/AeonDigital/Go-Core/xconfig/parser/yaml"
)

Basic usage

The typical usage pattern is to instantiate one or more parsers and pass them to InitAppConfig:

cfg, err := xconfig.InitAppConfig(
    []xconfig.Parser{
        varenv.NewParser(),
        yaml.NewParser(),
    },
    []xconfig.Options{
        {Prefix: "APP_", Separator: "_"},
        {ConfigPath: "config"},
    },
)
if err != nil {
    // handle error
}

value, ok := cfg.Get("database.host")
if ok {
    fmt.Println(value)
}

The package also provides:

  • cfg.Has(key) — check if a key exists.
  • cfg.Keys() — list all loaded keys.
  • cfg.Reload() — reload all registered parsers.
  • cfg.Populate(target) — populate a struct from the loaded data.

Supported parsers

The package includes drivers for:

  • xconfig/parser/varenv — system environment variables.
  • xconfig/parser/dotenv.env files.
  • xconfig/parser/json — JSON files.
  • xconfig/parser/yaml — YAML files.

External dependencies

xconfig uses only the Go standard library and one external YAML parser:

  • gopkg.in/yaml.v3

It also depends on the internal repository package github.com/AeonDigital/Go-Core/xerrors.

Documentation

Index

Constants

View Source
const XERR_NONE xerrors.ErrorCode = ""
View Source
const XERR_PKGCTX xerrors.ErrorCode = "ERR_XCONFIG"

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

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

Config manages the internal global state of loaded configuration variables. It maintains a thread-safe registry of parsers and a consolidated map of data.

func InitAppConfig

func InitAppConfig(parsers []Parser, options []Options) (*Config, error)

InitAppConfig acts as a bootstrap orchestrator. It receives a collection of 'Parser' and 'Options' objects, pairs them together, registers them to a new Config instance, and executes the initial data load in a single sequential flow.

Constraints:

  • The length of both slices must be identical. If not, it fails immediately.
  • Registration and loading order follows the exact slice position (index 0 to N).

Returns a fully initialized, populated pointer to Config, or nil and an error if it fails.

func NewConfig

func NewConfig() Config

NewConfig initializes an empty Config instance with prepared maps and slices, ensuring it is fully ready to safely register parsers or look up keys.

func (*Config) Get

func (c *Config) Get(key string) (any, bool)

Get performs a concurrent-safe lookup for a specific key. The target key parameter is automatically normalized (lowercased and trimmed). Returns the raw value and a boolean indicating whether the key was found.

func (*Config) Has

func (c *Config) Has(key string) bool

Has verifies the presence of a specific configuration key in a thread-safe manner. The search key parameter is normalized (lowercased and trimmed) to guarantee matching consistency.

func (*Config) Keys

func (c *Config) Keys() []string

Keys returns a thread-safe snapshot slice containing all keys currently loaded.

func (*Config) Load

func (c *Config) Load() error

Load clears the current state and triggers all registered parsers sequentially. Keys extracted from subsequent parsers will overwrite existing values with the same name, establishing a strict linear override priority matching the registration order. All keys are lowercased and stripped of leading/trailing spaces during ingestion to avoid ambiguity.

func (*Config) Populate

func (c *Config) Populate(target any) error

Populate maps the consolidated internal configuration data into a custom struct pointer. It leverages standard JSON marshaling/unmarshaling workflows to map generic string/interface structures into typed application structures.

Constraints:

  • 'target' must be a non-nil pointer.
  • 'target' must point strictly to a struct category object.

Returns an error if validation fails or if the structural decoding cannot be achieved.

func (*Config) Register

func (c *Config) Register(p Parser, opts Options) error

Register adds a custom provider/parser and its respective Options to the internal execution queue. This function does not trigger the data read operation. Returns an error if the underlying parser fails to ingest the provided options.

func (*Config) Reload

func (c *Config) Reload() error

Reload completely clears the internal data map and re-executes the ordered queue of registered parsers. This is particularly useful for live-reload strategies.

type Options

type Options struct {
	// Prefix defines the string that environment variables must start with.
	Prefix string
	// Separator defines the delimiter used to split hierarchical keys (e.g., "_").
	Separator string
	// FilePath points directly to a single configuration file.
	FilePath string
	// DirPath points to a directory containing multiple configuration files.
	DirPath string
	// ConfigPath is a generic path that can accept either a single file or a directory.
	ConfigPath string
	// ExpandOptions holds dynamic, vendor-specific extra options.
	ExpandOptions map[string]any
}

Options centralizes all possible configuration parameters required by the various configuration providers (e.g., Environment, DotEnv, JSON).

func (Options) RetrieveConfigFilePaths

func (o Options) RetrieveConfigFilePaths(extensions []string, parserType string) ([]string, error)

RetrieveConfigFilePaths inspects the configured path properties and resolves them into a slice of valid file paths matching any of the requested extensions. The resulting file path slice is explicitly sorted in alphabetical order to guarantee a deterministic and predictable execution pipeline where subsequent files overwrite prior ones.

Key behaviors:

  • If 'ConfigPath' is provided, it auto-detects whether it is a file or directory and normalizes the lookup strategy accordingly.
  • If 'FilePath' is provided, it adds the file directly to the checklist.
  • If 'DirPath' is provided, it scans the directory and retrieves all files matching any of the requested extensions (e.g., []string{".yaml", ".yml"}).

Parameters:

  • extensions: A list of target file extensions to match (e.g., []string{"yaml", ".yml"}). Leading dots are automatically added if missing. Pass an empty slice to match all files.
  • parserType: Used exclusively to generate descriptive, context-aware error messages.

Returns a sorted slice of string paths if successful, or an error if paths cannot be read, resolved, or if zero files match the criteria.

func (*Options) ValidateExclusivePaths

func (o *Options) ValidateExclusivePaths(parserType string) error

ValidateExclusivePaths ensures that path options are strictly exclusive. It counts how many path strategies are defined (FilePath, DirPath, ConfigPath). It returns an error if more than one path property is set at the same time, preventing ambiguous behavior during configuration loading.

func (*Options) ValidatePrefixAndSeparator

func (o *Options) ValidatePrefixAndSeparator(parserType string) error

ValidatePrefixAndSeparator ensures that both 'Prefix' and 'Separator' properties are filled. This validation is essential for providers that rely on structured string lookups, such as Environment Variables and DotEnv files. Returns an error specifying which field is missing if either is empty.

type Parser

type Parser interface {
	// SetOptions injects the necessary configuration properties into the parser instance.
	SetOptions(opts Options) error
	// Read executes the reading strategy and returns a generic key-value map.
	Read() (map[string]any, error)
}

Parser defines the universal contract for modules capable of reading, parsing, and converting external configuration files or key-value stores into a standardized Go map.

Directories

Path Synopsis
parser

Jump to

Keyboard shortcuts

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