config

package
v1.19.4 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 23 Imported by: 0

README

Config Package

Go Version GoDoc

Production-ready application lifecycle management system for Go with automatic dependency resolution, event-driven architecture, and component orchestration.

AI Disclaimer (EU AI Act Article 50.4): AI assistance was used solely for testing, documentation, and bug resolution under human supervision.


Table of Contents


Overview

The config package provides a comprehensive lifecycle management framework for building modular, production-ready Go applications. It orchestrates component initialization, startup, hot-reloading, and graceful shutdown while automatically resolving dependencies and managing shared resources.

Design Philosophy
  1. Dependency-Driven: Automatic topological ordering ensures components start in the correct sequence
  2. Event-Driven: Lifecycle hooks enable observability and cross-cutting concerns
  3. Context-Aware: Shared application context provides coordinated cancellation
  4. Component-Based: Pluggable architecture supports modular development
  5. Thread-Safe: Atomic operations and proper synchronization for concurrent access
  6. Hot-Reload: Support for configuration reloading without full restart
Why Use This Package?
  • Zero boilerplate for component lifecycle management
  • Automatic dependency resolution eliminates manual ordering
  • Built-in components for common services (HTTP, SMTP, LDAP, Database, TLS, etc.)
  • Event hooks for logging, metrics, and custom logic
  • Graceful shutdown with proper cleanup
  • Hot-reload support for configuration changes
  • Shell commands for runtime introspection
  • Comprehensive testing with race detector validation

Key Features

  • Lifecycle Management: Coordinated start, reload, and stop sequences across all components
  • Dependency Resolution: Automatic topological sorting ensures correct initialization order
  • Event Hooks: Before/after callbacks for lifecycle events (start, reload, stop)
  • Context Sharing: Application-wide context accessible to all components
  • Thread-Safe Operations: Mutex-protected component registry with concurrent-safe access
  • Shell Commands: Built-in interactive commands for runtime component management
  • Config Generation: Automatic default configuration file creation from all components
  • Monitoring Integration: Support for health checks and metrics via monitor pools
  • Viper Integration: Seamless configuration loading with github.com/spf13/viper
  • Signal Handling: Graceful shutdown on SIGINT, SIGTERM, SIGQUIT
  • Version Tracking: Built-in version information management

Installation

go get github.com/nabbar/golib/config

Architecture

Package Structure

The package is organized into a main package with supporting sub-packages:

config/
├── config/                  # Main package with lifecycle orchestration
│   ├── interface.go        # Config interface and factory
│   ├── components.go       # Component management
│   ├── events.go           # Lifecycle event handlers
│   ├── manage.go           # Hook and function registration
│   ├── context.go          # Context and cancellation
│   ├── shell.go            # Shell command integration
│   ├── errors.go           # Error definitions
│   └── model.go            # Internal data structures
├── types/                  # Interface definitions
│   ├── component.go        # Component interface
│   └── componentList.go    # Component list interface
├── const/                  # Package constants
│   └── const.go           # JSON formatting constants
└── components/            # Pre-built component implementations
    ├── aws/               # AWS component
    ├── database/          # Database component
    ├── http/              # HTTP server component
    ├── log/               # Logger component
    └── ...                # Other components
Component Orchestration Flow
┌─────────────────────────────────────────────────────────┐
│                   Config Orchestrator                    │
│                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │  Component   │  │  Component   │  │  Component   │ │
│  │  Registry    │  │  Lifecycle   │  │   Events     │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
│         │                  │                  │          │
│         ▼                  ▼                  ▼          │
│  ┌──────────────────────────────────────────────────┐  │
│  │        Dependency Resolution Engine               │  │
│  │  (Topological Sort + Validation)                 │  │
│  └──────────────────────────────────────────────────┘  │
│                                                          │
│  ┌──────────────────────────────────────────────────┐  │
│  │           Shared Application Context              │  │
│  │  (Thread-safe storage + Cancellation)            │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
         │                  │                  │
         ▼                  ▼                  ▼
   Component A        Component B        Component C
   (Database)         (Cache)            (HTTP Server)
Lifecycle Execution Order
Start Phase:
┌─────────────────────────────────────────────────────┐
│ 1. Global Before-Start Hooks                        │
├─────────────────────────────────────────────────────┤
│ 2. For each component (dependency order):           │
│    ┌─────────────────────────────────────────────┐ │
│    │ a. Component Before-Start Hook              │ │
│    │ b. Component.Start()                        │ │
│    │ c. Component After-Start Hook               │ │
│    └─────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────┤
│ 3. Global After-Start Hooks                         │
└─────────────────────────────────────────────────────┘

Stop Phase:
┌─────────────────────────────────────────────────────┐
│ 1. Global Before-Stop Hooks                         │
├─────────────────────────────────────────────────────┤
│ 2. For each component (reverse dependency order):   │
│    └─→ Component.Stop()                             │
├─────────────────────────────────────────────────────┤
│ 3. Global After-Stop Hooks                          │
└─────────────────────────────────────────────────────┘

Quick Start

Basic Usage
package main

import (
    "fmt"
    
    libcfg "github.com/nabbar/golib/config"
    libver "github.com/nabbar/golib/version"
)

func main() {
    // Create version information
    version := libver.NewVersion(
        libver.License_MIT,
        "myapp",
        "My Application",
        "2024-01-01",
        "commit-hash",
        "v1.0.0",
        "Author Name",
        "myapp",
        struct{}{},
        0,
    )
    
    // Create config instance
    cfg := libcfg.New(version)
    
    // Register components
    // cfg.ComponentSet("database", databaseComponent)
    // cfg.ComponentSet("cache", cacheComponent)
    
    // Register lifecycle hooks (optional)
    cfg.RegisterFuncStartBefore(func() error {
        fmt.Println("Starting application...")
        return nil
    })
    
    // Start all components
    if err := cfg.Start(); err != nil {
        panic(err)
    }
    
    // Application running...
    fmt.Println("Application started successfully")
    
    // Graceful shutdown
    defer cfg.Stop()
}
With Signal Handling
package main

import (
    libcfg "github.com/nabbar/golib/config"
    libver "github.com/nabbar/golib/version"
)

func main() {
    version := libver.NewVersion(/* ... */)
    cfg := libcfg.New(version)
    
    // Register components
    // ...
    
    // Start components
    if err := cfg.Start(); err != nil {
        panic(err)
    }
    
    // Wait for interrupt signal (SIGINT, SIGTERM, SIGQUIT)
    libcfg.WaitNotify()
}

Performance

Memory Characteristics

The config system maintains minimal memory overhead:

  • Config Instance: ~1 KB base footprint
  • Per Component: ~500 bytes overhead for tracking
  • Context Storage: O(n) where n = number of stored key-value pairs
  • Hook Storage: O(m) where m = number of registered hooks
Thread Safety

All operations are thread-safe through:

  • Mutex Protection: sync.RWMutex for component registry access
  • Context Storage: Thread-safe context implementation from github.com/nabbar/golib/context
  • Atomic Operations: Used where appropriate for state management
  • Concurrent Access: Multiple goroutines can safely access components
Startup Performance
Operation Components Time Notes
Component Registration 10 ~50µs O(1) per component
Dependency Resolution 10 ~200µs O(n log n) topological sort
Start Sequence 10 ~10ms Depends on component logic
Context Operations - ~100ns Per operation

Benchmarks on AMD64, Go 1.21


Use Cases

This package is designed for applications requiring coordinated lifecycle management:

Microservices

  • Orchestrate HTTP servers, database pools, message queues, and caches
  • Graceful shutdown with proper cleanup order
  • Hot reload configuration without downtime

Backend Services

  • Coordinate startup of multiple subsystems (auth, API, workers, schedulers)
  • Manage dependencies between services (database before cache before API)
  • Unified logging and monitoring across all components

CLI Applications

  • Modular command-line tools with pluggable components
  • Shell command integration for runtime inspection
  • Configuration file generation for user customization

Long-Running Daemons

  • Signal-based graceful shutdown
  • Component health monitoring
  • Runtime component restart without full application restart

Plugin Systems

  • Dynamic component registration at runtime
  • Dependency injection for cross-component communication
  • Version-aware component loading

Available Components

The config package includes pre-built components for common services:

Component Package Description Dependencies
AWS components/aws AWS SDK integration and configuration -
Database components/database SQL database connection pooling -
HTTP Server components/http HTTP/HTTPS server with routing TLS (optional)
HTTP Client components/httpcli HTTP client with connection pooling TLS, DNS Mapper
LDAP components/ldap LDAP client for authentication -
Logger components/log Structured logging component -
Mail components/mail Email sending (SMTP) SMTP
Request components/request HTTP request handling HTTP Client
SMTP components/smtp SMTP client configuration TLS (optional)
TLS components/tls TLS/SSL certificate management -
Head components/head HTTP headers management -
Component Features

Each component provides:

  • DefaultConfig() - Generate sensible default configuration
  • RegisterFlag() - CLI flag registration for Cobra
  • RegisterMonitorPool() - Health check and metrics integration
  • Dependencies() - Explicit dependency declaration
  • Hot-reload - Configuration reload without restart (where applicable)
  • Thread-safe - Concurrent access protection
  • Comprehensive tests - Ginkgo/Gomega test suites with race detection
Using Components
import (
    libcfg "github.com/nabbar/golib/config"
    cpthttp "github.com/nabbar/golib/config/components/http"
    cptlog "github.com/nabbar/golib/config/components/log"
)

func main() {
    cfg := libcfg.New(version)
    
    // Register logger component
    logCpt := cptlog.New(ctx)
    cptlog.Register(cfg, "logger", logCpt)
    
    // Register HTTP server component  
    httpCpt := cpthttp.New(ctx)
    cpthttp.Register(cfg, "http-server", httpCpt)
    
    // Start all components (logger starts before HTTP due to dependencies)
    if err := cfg.Start(); err != nil {
        panic(err)
    }
}

For detailed component documentation, see the respective README.md in each component's directory.


Core Concepts

Config Interface

The main Config interface provides methods for managing the application lifecycle and components:

type Config interface {
    // Lifecycle
    Start() error
    Reload() error
    Stop()
    Shutdown(code int)
    
    // Components
    ComponentSet(key string, cpt Component)
    ComponentGet(key string) Component
    ComponentDel(key string)
    ComponentList() map[string]Component
    ComponentKeys() []string
    
    // Context
    Context() libctx.Config[string]
    CancelAdd(fct ...func())
    CancelClean()
    
    // Events
    RegisterFuncStartBefore(fct FuncEvent)
    RegisterFuncStartAfter(fct FuncEvent)
    RegisterFuncReloadBefore(fct FuncEvent)
    RegisterFuncReloadAfter(fct FuncEvent)
    RegisterFuncStopBefore(fct FuncEvent)
    RegisterFuncStopAfter(fct FuncEvent)
    
    // Others
    RegisterFuncViper(fct libvpr.FuncViper)
    RegisterDefaultLogger(fct liblog.FuncLog)
    GetShellCommand() []shlcmd.Command
}
Component Interface

Components must implement the Component interface:

type Component interface {
    Type() string
    Init(key string, ctx FuncContext, get FuncCptGet, vpr FuncViper, vrs Version, log FuncLog)
    DefaultConfig(indent string) []byte
    Dependencies() []string
    SetDependencies(d []string) error
    
    IsStarted() bool
    IsRunning() bool
    Start() error
    Reload() error
    Stop()
    
    RegisterFlag(cmd *cobra.Command) error
    RegisterMonitorPool(p FuncPool)
    RegisterFuncStart(before, after FuncCptEvent)
    RegisterFuncReload(before, after FuncCptEvent)
}

Component Lifecycle

The config system manages a three-phase lifecycle for all components:

Start Phase
cfg.Start() // Calls in order:
// 1. RegisterFuncStartBefore hooks
// 2. Component.Start() for each component (in dependency order)
// 3. RegisterFuncStartAfter hooks

Features:

  • Components start in dependency order
  • Early termination on first error
  • Hooks execute before/after all components
  • State tracking (started/running)
Reload Phase
cfg.Reload() // Calls in order:
// 1. RegisterFuncReloadBefore hooks
// 2. Component.Reload() for each component
// 3. RegisterFuncReloadAfter hooks

Features:

  • Hot reload without restart
  • Component state preservation
  • Configuration refresh
  • No downtime
Stop Phase
cfg.Stop() // Calls in order:
// 1. RegisterFuncStopBefore hooks
// 2. Component.Stop() for each component (reverse order)
// 3. RegisterFuncStopAfter hooks

Features:

  • Graceful shutdown
  • Reverse dependency order
  • Resource cleanup
  • No error propagation (best effort)
Shutdown
cfg.Shutdown(exitCode) // Calls:
// 1. Custom cancel functions (CancelAdd)
// 2. cfg.Stop()
// 3. os.Exit(exitCode)

Use Case: Complete application termination with cleanup.


Dependency Management

The config system automatically resolves and orders component dependencies.

Declaring Dependencies
type DatabaseComponent struct {
    // ...
}

func (d *DatabaseComponent) Dependencies() []string {
    return []string{} // No dependencies
}

type CacheComponent struct {
    // ...
}

func (c *CacheComponent) Dependencies() []string {
    return []string{"database"} // Depends on database
}

type APIComponent struct {
    // ...
}

func (a *APIComponent) Dependencies() []string {
    return []string{"database", "cache"} // Depends on both
}
Automatic Ordering
cfg.ComponentSet("api", apiComponent)       // Registered in any order
cfg.ComponentSet("cache", cacheComponent)
cfg.ComponentSet("database", databaseComponent)

cfg.Start() // Starts in correct order:
// 1. database
// 2. cache
// 3. api
Deep Dependency Chains

The system handles complex dependency graphs:

database → cache → session → api
         ↘ logger ↗

Components are started in topological order and stopped in reverse order.


Event Hooks

Register custom functions to execute during lifecycle events:

Global Hooks
// Before starting any component
cfg.RegisterFuncStartBefore(func() error {
    fmt.Println("Preparing to start...")
    return nil
})

// After all components started
cfg.RegisterFuncStartAfter(func() error {
    fmt.Println("All components started successfully")
    return nil
})

// Before reloading
cfg.RegisterFuncReloadBefore(func() error {
    fmt.Println("Preparing to reload...")
    return nil
})

// After reloading
cfg.RegisterFuncReloadAfter(func() error {
    fmt.Println("Reload complete")
    return nil
})

// Before stopping
cfg.RegisterFuncStopBefore(func() error {
    fmt.Println("Preparing to stop...")
    return nil
})

// After all components stopped
cfg.RegisterFuncStopAfter(func() error {
    fmt.Println("Cleanup complete")
    return nil
})
Component-Level Hooks

Components can register their own hooks:

func (c *MyComponent) Init(key string, /* ... */) {
    // Hooks are set during initialization
}

// During registration, the component can set hooks
component.RegisterFuncStart(
    func(cpt Component) error {
        // Before this component starts
        return nil
    },
    func(cpt Component) error {
        // After this component starts
        return nil
    },
)
Hook Execution Order

For cfg.Start():

  1. RegisterFuncStartBefore
  2. For each component (in dependency order):
    • Component's before-start hook
    • Component's Start() method
    • Component's after-start hook
  3. RegisterFuncStartAfter

Shell Commands

The config system provides built-in shell commands for component management:

cmds := cfg.GetShellCommand()

// Returns commands: list, start, stop, restart
for _, cmd := range cmds {
    fmt.Printf("Command: %s - %s\n", cmd.Name(), cmd.Describe())
}
Available Commands
Command Description Usage
list List all components with status list
start Start all components start
stop Stop all components stop
restart Restart all components restart
Example Usage
import (
    "bytes"
    libcfg "github.com/nabbar/golib/config"
)

func main() {
    cfg := libcfg.New(version)
    
    // Register components
    cfg.ComponentSet("database", db)
    cfg.ComponentSet("cache", cache)
    
    // Get shell commands
    cmds := cfg.GetShellCommand()
    
    // Execute list command
    stdout := &bytes.Buffer{}
    stderr := &bytes.Buffer{}
    
    for _, cmd := range cmds {
        if cmd.Name() == "list" {
            cmd.Run(stdout, stderr, nil)
            fmt.Print(stdout.String())
        }
    }
}

Context Management

The config system provides a shared context for all components:

Basic Context Usage
// Get the context
ctx := cfg.Context()

// Store values
ctx.Store("key", "value")

// Load values
val, ok := ctx.Load("key")
if ok {
    fmt.Println(val) // "value"
}
Cancel Functions

Register functions to be called on application shutdown:

cfg.CancelAdd(func() {
    fmt.Println("Cleanup database connections")
})

cfg.CancelAdd(func() {
    fmt.Println("Flush caches")
})

// Clear all cancel functions
cfg.CancelClean()
Signal Handling

Graceful shutdown on system signals:

func main() {
    cfg := libcfg.New(version)
    
    // Start components
    if err := cfg.Start(); err != nil {
        panic(err)
    }
    
    // Wait for SIGINT, SIGTERM, or SIGQUIT
    libcfg.WaitNotify()
    
    // Cleanup happens automatically
}

Configuration Generation

Generate default configuration files for all components:

// Get default configuration as io.Reader
reader := cfg.DefaultConfig()

// Write to file
file, _ := os.Create("config.json")
defer file.Close()
io.Copy(file, reader)

Generated configuration includes all registered components with their default values.

Example output:

{
  "database": {
    "enabled": true,
    "host": "localhost",
    "port": 5432
  },
  "cache": {
    "enabled": true,
    "ttl": 300
  }
}

Creating Components

Component Interface

Components must implement this interface:

type Component interface {
    // Identification
    Type() string
    
    // Initialization
    Init(key string, ctx FuncContext, get FuncCptGet, 
         vpr FuncViper, vrs Version, log FuncLog)
    
    // Configuration
    DefaultConfig(indent string) []byte
    
    // Dependencies
    Dependencies() []string
    SetDependencies(d []string) error
    
    // Lifecycle
    Start() error
    Reload() error
    Stop()
    IsStarted() bool
    IsRunning() bool
    
    // Integration
    RegisterFlag(cmd *cobra.Command) error
    RegisterMonitorPool(p FuncPool)
    RegisterFuncStart(before, after FuncCptEvent)
    RegisterFuncReload(before, after FuncCptEvent)
}
Minimal Component Example
package mycomponent

import (
    cfgtps "github.com/nabbar/golib/config/types"
    libctx "github.com/nabbar/golib/context"
    liblog "github.com/nabbar/golib/logger"
    libver "github.com/nabbar/golib/version"
    libvpr "github.com/nabbar/golib/viper"
)

type MyComponent struct {
    key     string
    started bool
    running bool
    logger  liblog.FuncLog
}

func (c *MyComponent) Type() string {
    return "mycomponent"
}

func (c *MyComponent) Init(key string, ctx context.Context, 
    get cfgtps.FuncCptGet, vpr libvpr.FuncViper, 
    vrs libver.Version, log liblog.FuncLog) {
    c.key = key
    c.logger = log
}

func (c *MyComponent) DefaultConfig(indent string) []byte {
    return []byte(`{
    "enabled": true,
    "timeout": 30
}`)
}

func (c *MyComponent) Dependencies() []string {
    return []string{} // No dependencies
}

func (c *MyComponent) SetDependencies(d []string) error {
    return nil
}

func (c *MyComponent) Start() error {
    c.started = true
    c.running = true
    return nil
}

func (c *MyComponent) Reload() error {
    // Reload logic here
    return nil
}

func (c *MyComponent) Stop() {
    c.running = false
    c.started = false
}

func (c *MyComponent) IsStarted() bool { return c.started }
func (c *MyComponent) IsRunning() bool { return c.running }

func (c *MyComponent) RegisterFlag(cmd *cobra.Command) error {
    return nil
}

func (c *MyComponent) RegisterMonitorPool(p montps.FuncPool) {}

func (c *MyComponent) RegisterFuncStart(before, after cfgtps.FuncCptEvent) {}

func (c *MyComponent) RegisterFuncReload(before, after cfgtps.FuncCptEvent) {}
Using the Component
cfg := libcfg.New(version)

// Create and register component
comp := &MyComponent{}
cfg.ComponentSet("mycomp", comp)

// Start the application
if err := cfg.Start(); err != nil {
    panic(err)
}

Best Practices

1. Component Design
  • Keep components focused on a single responsibility
  • Use interfaces for flexibility and testing
  • Implement proper error handling
  • Use atomic values for thread-safe state management
2. Dependency Management
  • Declare all dependencies explicitly
  • Avoid circular dependencies
  • Keep dependency chains shallow when possible
3. Lifecycle Management
  • Always clean up resources in Stop()
  • Make Reload() idempotent
  • Handle errors gracefully in Start()
  • Track component state accurately
4. Configuration
  • Provide sensible defaults
  • Validate configuration before use
  • Support hot-reload when possible
  • Document configuration options
5. Logging
  • Use the provided logger
  • Log at appropriate levels
  • Include context in log messages
  • Don't log sensitive information
6. Testing
  • Write unit tests for each component
  • Test lifecycle transitions
  • Mock dependencies for isolation
  • Test error conditions

Testing

Comprehensive testing documentation is available in TESTING.md.

Quick Test:

cd config
go test -v

With Coverage:

go test -v -cover

Test Results:

  • 93 test specifications
  • 100% feature coverage
  • 6 focused test files
  • ~0.1 second execution time

Examples

See the Creating Components section and TESTING.md for detailed examples.


API Reference

Method Description
New(version) Create new config instance
Start() Start all components
Reload() Reload all components
Stop() Stop all components
Shutdown(code) Shutdown with exit code
ComponentSet(key, cpt) Register component
ComponentGet(key) Get component
ComponentDel(key) Delete component
ComponentList() List all components
Context() Get shared context
GetShellCommand() Get shell commands

Contributing

Contributions are welcome! Please follow these guidelines:

Code Contributions

  • Do not use AI to generate package implementation code
  • AI may assist with tests, documentation, and bug fixing
  • All contributions must pass existing tests
  • Maintain or improve test coverage
  • Follow existing code style and patterns

Documentation

  • Update README.md for new features
  • Add examples for common use cases
  • Keep TESTING.md synchronized with test changes
  • Document all public APIs with GoDoc comments

Testing

  • Write tests for all new features
  • Test edge cases and error conditions
  • Verify thread safety when applicable
  • Add comments explaining complex test scenarios

Pull Requests

  • Provide clear description of changes
  • Reference related issues
  • Include test results
  • Update documentation

See CONTRIBUTING.md for detailed guidelines.


Future Enhancements

Potential improvements for future versions:

Lifecycle Features

  • Parallel component startup (where dependencies allow)
  • Component health checks with automatic restart
  • Gradual rollout of configuration changes
  • Component state persistence and recovery

Dependency Management

  • Circular dependency detection with clear error messages
  • Optional dependencies (soft dependencies)
  • Dynamic dependency injection at runtime
  • Dependency visualization tools

Configuration

  • Multiple configuration sources (files, env vars, remote)
  • Configuration validation before apply
  • Configuration versioning and rollback
  • Encrypted configuration values

Monitoring & Observability

  • Built-in metrics for lifecycle events
  • Distributed tracing integration
  • Event streaming for external monitoring
  • Component dependency graph visualization

Developer Experience

  • Code generation for boilerplate components
  • Interactive component inspector
  • Configuration schema validation
  • Better error messages with suggestions

Suggestions and contributions are welcome via GitHub issues.


Core Packages
  • context - Thread-safe context storage used by config
  • viper - Configuration file loading and management
  • logger - Structured logging system
  • version - Application version management
Component Packages
External References

License

MIT License - See LICENSE file for details.

Copyright (c) 2022 Nicolas JUHEL


Resources


This package is part of the golib project.

Documentation

Index

Constants

View Source
const (
	// ErrorParamEmpty indicates that required parameters were not provided.
	ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgConfig

	// ErrorConfigMissingViper indicates that the Viper configuration provider is not registered.
	// Register one using Config.RegisterFuncViper() before component initialization.
	ErrorConfigMissingViper

	// ErrorComponentNotFound indicates that a requested component was not found in the registry.
	// Verify the component key and ensure the component is registered via ComponentSet().
	ErrorComponentNotFound

	// ErrorComponentFlagError indicates that at least one component failed during flag registration.
	// Check individual component RegisterFlag() implementations for specific errors.
	ErrorComponentFlagError

	// ErrorComponentConfigNotFound indicates that configuration keys for a component are missing.
	// Ensure the configuration file contains the required component section.
	ErrorComponentConfigNotFound

	// ErrorComponentConfigError indicates that a component's configuration is invalid or malformed.
	// Review the component's configuration structure and validation rules.
	ErrorComponentConfigError

	// ErrorComponentStart indicates that at least one component failed to start.
	// Check component logs for specific startup errors.
	ErrorComponentStart

	// ErrorComponentReload indicates that at least one component failed to reload.
	// Check component logs for specific reload errors.
	ErrorComponentReload
)

Error codes for the config package. These errors are used throughout the config package and its components to provide standardized error reporting with proper error chaining.

View Source
const (
	// MinErrorComponentAws is the starting error code for AWS component errors.
	MinErrorComponentAws = ErrorParamEmpty + 10

	// MinErrorComponentDatabase is the starting error code for Database component errors.
	MinErrorComponentDatabase = MinErrorComponentAws + 10

	// MinErrorComponentHead is the starting error code for Header component errors.
	MinErrorComponentHead = MinErrorComponentDatabase + 10

	// MinErrorComponentHttp is the starting error code for HTTP server component errors.
	MinErrorComponentHttp = MinErrorComponentHead + 10

	// MinErrorComponentHttpCli is the starting error code for HTTP client component errors.
	MinErrorComponentHttpCli = MinErrorComponentHttp + 10

	// MinErrorComponentLdap is the starting error code for LDAP component errors.
	MinErrorComponentLdap = MinErrorComponentHttpCli + 10

	// MinErrorComponentLog is the starting error code for Logger component errors.
	MinErrorComponentLog = MinErrorComponentLdap + 10

	// MinErrorComponentMail is the starting error code for Mail component errors.
	MinErrorComponentMail = MinErrorComponentLog + 10

	// MinErrorComponentNats is the starting error code for NATS component errors.
	MinErrorComponentNats = MinErrorComponentMail + 10

	// MinErrorComponentNutsDB is the starting error code for NutsDB component errors.
	MinErrorComponentNutsDB = MinErrorComponentNats + 10

	// MinErrorComponentRequest is the starting error code for Request component errors.
	MinErrorComponentRequest = MinErrorComponentNutsDB + 10

	// MinErrorComponentSmtp is the starting error code for SMTP component errors.
	MinErrorComponentSmtp = MinErrorComponentRequest + 10

	// MinErrorComponentTls is the starting error code for TLS component errors.
	MinErrorComponentTls = MinErrorComponentSmtp + 10
)

Error code ranges reserved for component-specific errors. Each component package has a reserved range of error codes to avoid collisions. Components should define their error codes starting from their MinError constant.

Variables

This section is empty.

Functions

func ShellCommandInfo added in v1.11.3

func ShellCommandInfo() []shlcmd.CommandInfo

ShellCommandInfo returns metadata for all available shell commands. This is used by shell integration packages to discover available commands without creating the full command implementations.

Returns:

  • Slice of CommandInfo containing name and description for each command

Available commands:

  • list: Display all registered components
  • start: Start components (optionally specify component keys as arguments)
  • stop: Stop components (optionally specify component keys as arguments)
  • restart: Restart components by stopping then starting them

Example usage in shell integration:

for _, info := range config.ShellCommandInfo() {
    fmt.Printf("%s: %s\n", info.Name(), info.Description())
}

func Shutdown added in v1.10.0

func Shutdown()

Shutdown cancels the main application context, triggering shutdown of all components. This is a package-level function that can be called from any goroutine to initiate a coordinated shutdown. It cancels the shared context, which is monitored by all Config instances.

Usage:

  • Call from signal handlers for graceful shutdown
  • Call from error handlers for emergency shutdown
  • Call from other goroutines to stop the application

Note: This only cancels the context. Components must handle the cancellation through their Config.Stop() method or by monitoring the context.

func WaitNotify added in v1.10.0

func WaitNotify()

WaitNotify blocks until an interrupt signal is received, then initiates shutdown. This function monitors OS signals (SIGINT, SIGTERM, SIGQUIT) and the application context. When either a signal is received or the context is cancelled, it calls Shutdown() to begin the graceful shutdown sequence.

Typical usage in main():

func main() {
    cfg := config.New(version)
    cfg.Start()
    config.WaitNotify()  // Blocks until signal received
}

Monitored signals:

  • SIGINT (Ctrl+C): User interrupt from terminal
  • SIGTERM: Termination signal (default for 'kill' command)
  • SIGQUIT: Quit signal with core dump request

The function returns immediately after calling Shutdown(), allowing the main function to perform final cleanup before exiting.

Types

type Config

type Config interface {
	// Context returns the shared application context instance.
	// All components receive access to this context for shared state management
	// and coordinated cancellation.
	Context() libctx.Config[string]

	// CancelAdd registers custom functions to be called on context cancellation.
	// These functions execute before Stop() when the application receives
	// termination signals (SIGINT, SIGTERM, SIGQUIT) or when Shutdown() is called.
	// Useful for cleanup tasks that need to happen before component shutdown.
	CancelAdd(fct ...func())

	// CancelClean removes all registered cancel functions.
	// Use this to reset cancellation handlers, typically during testing
	// or when reconfiguring the application.
	CancelClean()

	// Start initiates the startup sequence for all registered components.
	// Components are started in dependency order (topological sort).
	// The sequence is:
	//   1. Execute RegisterFuncStartBefore hooks
	//   2. Start each component in dependency order
	//   3. Execute RegisterFuncStartAfter hooks
	// Returns an error if any hook or component fails to start.
	// On error, the start sequence is aborted immediately.
	Start() error

	// Reload triggers a configuration reload for all registered components.
	// Components are reloaded in dependency order.
	// The sequence is:
	//   1. Execute RegisterFuncReloadBefore hooks
	//   2. Reload each component in dependency order
	//   3. Execute RegisterFuncReloadAfter hooks
	// Returns an error if any hook or component fails to reload.
	// Components should implement hot-reload without full restart.
	Reload() error

	// Stop gracefully shuts down all registered components.
	// Components are stopped in reverse dependency order.
	// The sequence is:
	//   1. Execute RegisterFuncStopBefore hooks
	//   2. Stop each component in reverse dependency order
	//   3. Execute RegisterFuncStopAfter hooks
	// This function does not return errors; components must stop cleanly.
	Stop()

	// Shutdown performs a complete application termination.
	// This function:
	//   1. Executes all registered cancel functions (CancelAdd)
	//   2. Calls Stop() to shutdown components
	//   3. Exits the process with the specified exit code
	// This is typically called on fatal errors or during graceful shutdown.
	// Note: This function does not return as it calls os.Exit().
	Shutdown(code int)

	// RegisterFuncViper registers a Viper configuration provider function.
	// Components use this to access their configuration sections.
	// The function is called when components need to load or reload their configuration.
	// Typically registered once during application initialization.
	RegisterFuncViper(fct libvpr.FuncViper)

	// RegisterFuncStartBefore registers a hook executed before component startup.
	// This hook runs before any component's Start() method is called.
	// Use for: pre-start validation, initialization logging, resource preparation.
	// If the hook returns an error, the start sequence is aborted.
	RegisterFuncStartBefore(fct FuncEvent)

	// RegisterFuncStartAfter registers a hook executed after component startup.
	// This hook runs after all components have started successfully.
	// Use for: post-start validation, ready notification, monitoring setup.
	// If the hook returns an error, it's treated as a start failure.
	RegisterFuncStartAfter(fct FuncEvent)

	// RegisterFuncReloadBefore registers a hook executed before component reload.
	// This hook runs before any component's Reload() method is called.
	// Use for: pre-reload backup, configuration validation, logging.
	// If the hook returns an error, the reload sequence is aborted.
	RegisterFuncReloadBefore(fct FuncEvent)

	// RegisterFuncReloadAfter registers a hook executed after component reload.
	// This hook runs after all components have reloaded successfully.
	// Use for: post-reload validation, cache clearing, notification.
	// If the hook returns an error, it's treated as a reload failure.
	RegisterFuncReloadAfter(fct FuncEvent)

	// RegisterFuncStopBefore registers a hook executed before component shutdown.
	// This hook runs before any component's Stop() method is called.
	// Use for: pre-shutdown logging, resource flushing, notification.
	// Errors from this hook are logged but do not prevent shutdown.
	RegisterFuncStopBefore(fct FuncEvent)

	// RegisterFuncStopAfter registers a hook executed after component shutdown.
	// This hook runs after all components have stopped.
	// Use for: cleanup verification, final logging, monitoring notification.
	// Errors from this hook are logged but ignored (shutdown continues).
	RegisterFuncStopAfter(fct FuncEvent)

	// RegisterDefaultLogger registers a logger provider function for components.
	// Components use this logger for operational logging.
	// The function is called each time a component needs a logger instance.
	// If not registered, components may not have logging capability.
	RegisterDefaultLogger(fct liblog.FuncLog)

	// ComponentList provides component registry operations.
	// Includes: ComponentSet, ComponentGet, ComponentDel, ComponentList,
	// ComponentKeys, ComponentStart, ComponentStop, ComponentReload.
	cfgtps.ComponentList

	// ComponentMonitor provides monitoring integration.
	// Allows components to register health checks and metrics.
	cfgtps.ComponentMonitor

	// GetShellCommand returns interactive shell commands for runtime management.
	// Commands include: list (show components), start (start components),
	// stop (stop components), restart (restart components).
	// These commands can be integrated into CLI applications or interactive shells.
	GetShellCommand() []shlcmd.Command
}

Config is the main interface for application lifecycle management. It provides component orchestration, dependency resolution, event hooks, context management, and shell command integration.

Lifecycle Operations:

  • Start(): Initialize and start all registered components in dependency order
  • Reload(): Hot-reload components without full restart
  • Stop(): Gracefully shutdown all components in reverse dependency order
  • Shutdown(code): Complete application termination with cleanup and exit

Component Management:

  • ComponentSet/Get/Del: Register and manage components
  • ComponentList/Keys: Enumerate registered components
  • ComponentStart/Stop/Reload: Lifecycle operations on components

Event Hooks:

  • RegisterFuncStartBefore/After: Hooks around start operations
  • RegisterFuncReloadBefore/After: Hooks around reload operations
  • RegisterFuncStopBefore/After: Hooks around stop operations

Context & Cancellation:

  • Context(): Shared application context for all components
  • CancelAdd/CancelClean: Custom cancellation handlers

Configuration:

  • RegisterFuncViper: Viper configuration provider
  • RegisterDefaultLogger: Logger provider for components
  • DefaultConfig(): Generate default configuration file

Shell Commands:

  • GetShellCommand(): Interactive commands for runtime management

func New

func New(vrs libver.Version) Config

New creates and initializes a new Config instance for application lifecycle management.

Parameters:

  • vrs: Version information for the application (can be nil)

Returns:

  • Config: A fully initialized configuration orchestrator

The returned Config instance:

  • Uses a shared application context for all components
  • Automatically monitors the context for cancellation
  • Provides thread-safe component registration and management
  • Supports dependency resolution and ordered lifecycle operations

Initialization:

  • Creates internal registries for components, hooks, and functions
  • Registers the provided version information
  • Starts a goroutine to monitor context cancellation

Example:

version := libver.NewVersion(...)
cfg := config.New(version)
defer cfg.Stop()

// Register components
cfg.ComponentSet("database", dbComponent)
cfg.ComponentSet("cache", cacheComponent)

// Start all components
if err := cfg.Start(); err != nil {
    log.Fatal(err)
}

Thread Safety: All operations on the returned Config instance are thread-safe and can be called concurrently from multiple goroutines.

type FuncEvent added in v1.10.0

type FuncEvent func() error

FuncEvent is a function type for lifecycle event hooks. It returns an error if the event handler fails. Used for before/after hooks in Start, Reload, and Stop operations.

Directories

Path Synopsis
components
aws
log
tls
Package _const provides constants used throughout the config package.
Package _const provides constants used throughout the config package.

Jump to

Keyboard shortcuts

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