configloader

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package configloader provides automatic configuration loading and management for Forge applications.

The configuration loader bundle provides:

  • Automatic loading from multiple sources (files, environment, defaults)
  • Support for YAML, JSON, and TOML configuration files
  • Environment variable binding with struct tag support
  • Configuration validation and merging with priority handling
  • Hot reload and file watching capabilities
  • Secure handling of sensitive configuration data
  • Configuration source tracking and debugging

Basic Usage

Define your configuration struct with appropriate tags:

type MyServiceConfig struct {
	config.BaseConfig `yaml:",inline" env:",inline"`

	// Service-specific configuration
	DatabaseURL string `yaml:"database_url" env:"DATABASE_URL" validate:"required"`
	APIKey      string `yaml:"api_key" env:"API_KEY" validate:"required" sensitive:"true"`
	Debug       bool   `yaml:"debug" env:"DEBUG" default:"false"`
}

Load configuration automatically:

loader := configloader.New(configloader.Config{
	ConfigPaths: []string{"./config.yaml", "/etc/myservice/config.yaml"},
	EnvPrefix:   "MYSERVICE",
	WatchFiles:  true,
})

var cfg MyServiceConfig
if err := loader.Load(&cfg); err != nil {
	log.Fatal(err)
}

Configuration Sources (Priority Order)

1. Command line flags (highest priority) 2. Environment variables 3. Configuration files (first found file wins) 4. Default values from struct tags (lowest priority)

File Formats Supported

  • YAML: config.yaml, config.yml
  • JSON: config.json
  • TOML: config.toml (future)

Environment Variable Binding

The loader automatically binds environment variables based on:

  • Field names (converted to UPPER_SNAKE_CASE)

  • `env` struct tags for custom names

  • `envPrefix` configuration for namespacing

    DatabaseURL string `env:"DATABASE_URL"` // Exact name APITimeout int `env:"API_TIMEOUT_SECONDS"` // Custom name Debug bool // Automatic: DEBUG or MYSERVICE_DEBUG (with prefix)

Hot Reload

Enable automatic configuration reloading when files change:

loader.OnConfigChange(func(newConfig *MyServiceConfig) {
	log.Printf("Configuration reloaded: %+v", newConfig)
	// Handle configuration changes
})

Secure Configuration

Mark sensitive fields to prevent logging:

APIKey string `yaml:"api_key" env:"API_KEY" sensitive:"true"`

The loader will redact sensitive fields in logs and error messages.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bundle

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

Bundle provides configuration loading for Forge applications.

func NewBundle

func NewBundle(config Config) *Bundle

NewBundle creates a new configuration loading bundle.

func (*Bundle) Close

func (b *Bundle) Close() error

Close is deprecated. Use Stop() instead for proper lifecycle integration. Maintained for backward compatibility.

func (*Bundle) Initialize

func (b *Bundle) Initialize(app *framework.App) error

Initialize sets up the configuration loader.

func (*Bundle) Loader

func (b *Bundle) Loader() *Loader

Loader returns the configuration loader instance.

func (*Bundle) Name

func (b *Bundle) Name() string

Name returns the bundle name.

func (*Bundle) StartWatching

func (b *Bundle) StartWatching(ctx context.Context, dest interface{}) error

StartWatching starts watching configuration files for changes.

func (*Bundle) Stop

func (b *Bundle) Stop(ctx context.Context) error

Stop implements the Bundle interface for graceful shutdown. Stops file watching and cleans up resources respecting the context deadline.

type Config

type Config struct {
	// ConfigPaths is a list of configuration file paths to search.
	// The first existing file will be used.
	ConfigPaths []string

	// EnvPrefix is prepended to environment variable names.
	// For example, with prefix "MYSERVICE", field "Debug" becomes "MYSERVICE_DEBUG".
	EnvPrefix string

	// WatchFiles enables automatic reloading when configuration files change.
	WatchFiles bool

	// RequireConfigFile determines if a configuration file must exist.
	// If false, the loader will work with environment variables and defaults only.
	RequireConfigFile bool

	// ValidateOnLoad enables automatic validation using the Validator interface.
	ValidateOnLoad bool

	// SecureLogging prevents sensitive fields from appearing in logs.
	SecureLogging bool

	// Security configuration
	MaxFileSize      int64       // Maximum configuration file size (default: 1MB)
	AllowedPaths     []string    // Allowed configuration file directories
	RequiredFileMode os.FileMode // Required file permissions (default: 0o644)
}

Config contains configuration loader settings.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration loader settings.

type LoadResult

type LoadResult struct {
	LoadedFrom       string   `json:"loaded_from"`
	Sources          []string `json:"sources"`
	EnvVarsUsed      []string `json:"env_vars_used"`
	DefaultsApplied  []string `json:"defaults_applied"`
	ValidationErrors []string `json:"validation_errors,omitempty"`
}

LoadResult contains information about the configuration loading process.

func LoadConfig

func LoadConfig[T any](configPaths ...string) (*T, *LoadResult, error)

LoadConfig is a convenience function for loading configuration with default settings.

func MustLoadConfig

func MustLoadConfig[T any](configPaths ...string) (*T, *LoadResult)

MustLoadConfig is a convenience function that panics on configuration loading errors.

type Loader

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

Loader provides configuration loading functionality.

func (*Loader) GetConfigInfo

func (l *Loader) GetConfigInfo() map[string]interface{}

GetConfigInfo returns information about the loaded configuration.

func (*Loader) Load

func (l *Loader) Load(dest interface{}) (*LoadResult, error)

Load loads configuration into the provided struct from multiple sources.

func (*Loader) LoadFromString

func (l *Loader) LoadFromString(data, format string, dest interface{}) error

LoadFromString loads configuration from a string (useful for testing).

func (*Loader) MustLoad

func (l *Loader) MustLoad(dest interface{}) *LoadResult

MustLoad loads configuration and panics on error (useful for application startup).

func (*Loader) OnConfigChange

func (l *Loader) OnConfigChange(callback func(interface{}))

OnConfigChange registers a callback for configuration changes (hot reload).

func (*Loader) Reload

func (l *Loader) Reload(dest interface{}) (*LoadResult, error)

Reload reloads configuration from all sources.

Jump to

Keyboard shortcuts

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