config

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2025 License: MIT Imports: 0 Imported by: 0

README

Configuration Package

The config package provides a flexible configuration system that supports multiple sources and formats for Go applications. It allows you to manage application configuration in a hierarchical manner with support for various data sources.

Features

  • Multiple Sources:

    • YAML and JSON files
    • Environment variables
    • Command-line flags
    • In-memory values
  • Hierarchical Configuration: Access nested values using dot notation

  • Default Values: Specify fallback values when configuration is missing

  • Type Conversion: Automatic conversion to the appropriate type

  • Configuration Reloading: Watch for changes and reload configuration

  • Validation: Validate configuration against schemas

  • Adapters: Easily create custom adapters for different configuration sources

Installation

go get github.com/abitofhelp/servicelib/config

Usage

Basic Usage
package main

import (
    "fmt"
    "log"
    "github.com/abitofhelp/servicelib/config"
)

func main() {
    // Create a new configuration from files
    cfg, err := config.New("config.yaml", "env.yaml")
    if err != nil {
        log.Fatalf("Failed to load configuration: %v", err)
    }

    // Get a string value
    apiKey := cfg.GetString("api.key")
    fmt.Println("API Key:", apiKey)

    // Get an int value with default
    port := cfg.GetInt("server.port", 8080)
    fmt.Println("Server Port:", port)

    // Get a nested value
    dbURL := cfg.GetString("database.url")
    fmt.Println("Database URL:", dbURL)

    // Get a boolean value
    debug := cfg.GetBool("logging.debug", false)
    fmt.Println("Debug Mode:", debug)

    // Get a duration value
    timeout := cfg.GetDuration("server.timeout", "30s")
    fmt.Println("Server Timeout:", timeout)
}
Binding to Structs
package main

import (
    "fmt"
    "log"
    "github.com/abitofhelp/servicelib/config"
)

// Example configuration struct
type AppConfig struct {
    Server struct {
        Port    int    `yaml:"port"`
        Host    string `yaml:"host"`
        Timeout int    `yaml:"timeout"`
    } `yaml:"server"`
    Database struct {
        URL      string `yaml:"url"`
        Username string `yaml:"username"`
        Password string `yaml:"password"`
        Pool     int    `yaml:"pool"`
    } `yaml:"database"`
    API struct {
        Key      string `yaml:"key"`
        Endpoint string `yaml:"endpoint"`
        Version  string `yaml:"version"`
    } `yaml:"api"`
    Logging struct {
        Level  string `yaml:"level"`
        Format string `yaml:"format"`
        Path   string `yaml:"path"`
    } `yaml:"logging"`
}

func main() {
    // Create a new configuration
    cfg, err := config.New("config.yaml")
    if err != nil {
        log.Fatalf("Failed to load configuration: %v", err)
    }

    // Bind configuration to a struct
    var appConfig AppConfig
    if err := cfg.Unmarshal(&appConfig); err != nil {
        log.Fatalf("Failed to unmarshal configuration: %v", err)
    }

    fmt.Printf("Server Configuration: %+v\n", appConfig.Server)
    fmt.Printf("Database Configuration: %+v\n", appConfig.Database)
}
Watching for Changes
package main

import (
    "log"
    "github.com/abitofhelp/servicelib/config"
)

func main() {
    // Create a new configuration
    cfg, err := config.New("config.yaml")
    if err != nil {
        log.Fatalf("Failed to load configuration: %v", err)
    }

    // Watch for configuration changes
    cfg.Watch(func() {
        // Reload configuration when changes are detected
        var appConfig AppConfig
        if err := cfg.Unmarshal(&appConfig); err != nil {
            log.Printf("Failed to reload configuration: %v", err)
            return
        }
        log.Println("Configuration reloaded successfully")
        
        // Apply the new configuration
        applyConfiguration(appConfig)
    })
    
    // Keep the application running
    select {}
}

func applyConfiguration(config AppConfig) {
    // Apply the configuration to your application
    // For example, update database connections, change log levels, etc.
}
Environment Variables

The config package can also load configuration from environment variables:

// Create a configuration that includes environment variables
cfg, err := config.NewWithOptions(config.Options{
    Files: []string{"config.yaml"},
    EnvPrefix: "APP_",
    EnvReplacer: "_",
})

// This will look for environment variables like:
// APP_SERVER_PORT, APP_DATABASE_URL, etc.

Configuration File Example

Here's an example of a YAML configuration file:

server:
  port: 8080
  host: "localhost"
  timeout: 30

database:
  url: "postgres://user:password@localhost:5432/mydb"
  username: "user"
  password: "password"
  pool: 10

api:
  key: "your-api-key"
  endpoint: "https://api.example.com"
  version: "v1"

logging:
  level: "info"
  format: "json"
  path: "/var/log/app.log"

Best Practices

  1. Use Environment Variables for Secrets: Never store sensitive information like API keys or passwords in configuration files. Use environment variables instead.

  2. Default Values: Always provide sensible default values for configuration that might be missing.

  3. Validation: Validate configuration values to ensure they meet your requirements.

  4. Configuration Hierarchy: Use a hierarchical approach to organize your configuration.

  5. Documentation: Document all configuration options, including their purpose, type, and default values.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package config provides generic configuration interfaces and adapters.

Package config provides generic configuration interfaces that can be used across different applications.

Package config provides generic configuration interfaces that can be used across different applications.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AppConfig

type AppConfig interface {
	// GetVersion returns the application version
	GetVersion() string

	// GetName returns the application name
	GetName() string

	// GetEnvironment returns the application environment (e.g., "development", "production")
	GetEnvironment() string
}

AppConfig is a generic interface for application configuration

type AppConfigProvider

type AppConfigProvider interface {
	// GetAppVersion returns the application version
	GetAppVersion() string

	// GetAppName returns the application name (optional)
	GetAppName() string

	// GetAppEnvironment returns the application environment (optional)
	GetAppEnvironment() string
}

AppConfigProvider defines the interface for accessing application configuration

type Config

type Config interface {
	// GetApp returns the application configuration
	GetApp() AppConfig

	// GetDatabase returns the database configuration
	GetDatabase() DatabaseConfig
}

Config is a generic interface for application configuration

type ConfigInterface

type ConfigInterface interface {
	// GetApp returns the App configuration
	GetApp() interface{}

	// GetDatabase returns the Database configuration
	GetDatabase() interface{}
}

ConfigInterface is an interface for configuration Deprecated: Use Config interface instead

type DatabaseConfig

type DatabaseConfig interface {
	// GetType returns the database type (e.g., "mongodb", "postgres", "sqlite")
	GetType() string

	// GetConnectionString returns the database connection string
	GetConnectionString() string

	// GetDatabaseName returns the database name
	GetDatabaseName() string

	// GetCollectionName returns the collection/table name for a given entity type
	GetCollectionName(entityType string) string
}

DatabaseConfig is a generic interface for database configuration

type DatabaseConfigProvider

type DatabaseConfigProvider interface {
	// GetDatabaseType returns the database type
	GetDatabaseType() string

	// GetDatabaseConnectionString returns the database connection string
	GetDatabaseConnectionString(dbType string) string
}

DatabaseConfigProvider defines the interface for accessing database configuration

type GenericAppConfigAdapter

type GenericAppConfigAdapter[T any] struct {
	// contains filtered or unexported fields
}

GenericAppConfigAdapter is a generic adapter for application configuration

func (*GenericAppConfigAdapter[T]) GetEnvironment

func (a *GenericAppConfigAdapter[T]) GetEnvironment() string

GetEnvironment returns the application environment

func (*GenericAppConfigAdapter[T]) GetName

func (a *GenericAppConfigAdapter[T]) GetName() string

GetName returns the application name

func (*GenericAppConfigAdapter[T]) GetVersion

func (a *GenericAppConfigAdapter[T]) GetVersion() string

GetVersion returns the application version

type GenericConfigAdapter

type GenericConfigAdapter[T any] struct {
	// contains filtered or unexported fields
}

GenericConfigAdapter is a generic adapter for any config type that provides the necessary methods

func NewGenericConfigAdapter

func NewGenericConfigAdapter[T any](cfg T) *GenericConfigAdapter[T]

NewGenericConfigAdapter creates a new GenericConfigAdapter with default values

func (*GenericConfigAdapter[T]) GetApp

func (a *GenericConfigAdapter[T]) GetApp() AppConfig

GetApp returns the application configuration

func (*GenericConfigAdapter[T]) GetDatabase

func (a *GenericConfigAdapter[T]) GetDatabase() DatabaseConfig

GetDatabase returns the database configuration

func (*GenericConfigAdapter[T]) WithAppEnvironment

func (a *GenericConfigAdapter[T]) WithAppEnvironment(env string) *GenericConfigAdapter[T]

WithAppEnvironment sets the application environment

func (*GenericConfigAdapter[T]) WithAppName

func (a *GenericConfigAdapter[T]) WithAppName(name string) *GenericConfigAdapter[T]

WithAppName sets the application name

func (*GenericConfigAdapter[T]) WithDatabaseName

func (a *GenericConfigAdapter[T]) WithDatabaseName(name string) *GenericConfigAdapter[T]

WithDatabaseName sets the database name

type GenericDatabaseConfigAdapter

type GenericDatabaseConfigAdapter[T any] struct {
	// contains filtered or unexported fields
}

GenericDatabaseConfigAdapter is a generic adapter for database configuration

func (*GenericDatabaseConfigAdapter[T]) GetCollectionName

func (a *GenericDatabaseConfigAdapter[T]) GetCollectionName(entityType string) string

GetCollectionName returns the collection/table name for a given entity type

func (*GenericDatabaseConfigAdapter[T]) GetConnectionString

func (a *GenericDatabaseConfigAdapter[T]) GetConnectionString() string

GetConnectionString returns the database connection string

func (*GenericDatabaseConfigAdapter[T]) GetDatabaseName

func (a *GenericDatabaseConfigAdapter[T]) GetDatabaseName() string

GetDatabaseName returns the database name

func (*GenericDatabaseConfigAdapter[T]) GetType

func (a *GenericDatabaseConfigAdapter[T]) GetType() string

GetType returns the database type

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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