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 ¶
- type Bundle
- type Config
- type LoadResult
- type Loader
- func (l *Loader) GetConfigInfo() map[string]interface{}
- func (l *Loader) Load(dest interface{}) (*LoadResult, error)
- func (l *Loader) LoadFromString(data, format string, dest interface{}) error
- func (l *Loader) MustLoad(dest interface{}) *LoadResult
- func (l *Loader) OnConfigChange(callback func(interface{}))
- func (l *Loader) Reload(dest interface{}) (*LoadResult, error)
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 (*Bundle) Close ¶
Close is deprecated. Use Stop() instead for proper lifecycle integration. Maintained for backward compatibility.
func (*Bundle) Initialize ¶
Initialize sets up the configuration loader.
func (*Bundle) StartWatching ¶
StartWatching starts watching configuration files for changes.
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.
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 ¶
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 ¶
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.