config

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2025 License: Apache-2.0 Imports: 7 Imported by: 1

README

Config Package

Environment variable configuration loader with struct tag support, configurable prefixes, and automatic .env file loading.

Features

  • Load environment variables into Go structs using reflection
  • Configurable environment variable prefixes for multi-tenant applications
  • Support for default values via struct tags
  • Type conversion for string, int, int64, bool, and time.Duration fields
  • Automatic .env file loading (via github.com/joho/godotenv)
  • Debug mode for development environments
  • Zero configuration with sensible defaults

Usage

Basic Example
package main

import (
    "fmt"
    "time"
    "github.com/gobeaver/beaver-kit/config"
)

type AppConfig struct {
    DatabaseURL string        `env:"DATABASE_URL,default:postgres://localhost/myapp"`
    Port        int           `env:"PORT,default:8080"`
    Debug       bool          `env:"DEBUG,default:false"`
    Timeout     time.Duration `env:"TIMEOUT,default:30s"`
}

func main() {
    cfg := &AppConfig{}
    if err := config.Load(cfg); err != nil {
        panic(err)
    }
    
    fmt.Printf("Database: %s\n", cfg.DatabaseURL)
    fmt.Printf("Port: %d\n", cfg.Port)
    fmt.Printf("Debug: %t\n", cfg.Debug)
    fmt.Printf("Timeout: %v\n", cfg.Timeout)
}
Environment Variables (Default Prefix)

By default, all environment variables use the BEAVER_ prefix:

BEAVER_DATABASE_URL=postgres://prod-server/myapp
BEAVER_PORT=3000
BEAVER_DEBUG=true
BEAVER_TIMEOUT=60s
Custom Environment Variable Prefixes

For multi-tenant applications or custom configurations:

// Load with custom prefix
cfg := &AppConfig{}
if err := config.Load(cfg, config.LoadOptions{Prefix: "MYAPP_"}); err != nil {
    panic(err)
}

// Now it reads: MYAPP_DATABASE_URL, MYAPP_PORT, etc.

Struct Tag Format

type Config struct {
    Field string `env:"ENV_VAR_NAME,default:defaultvalue"`
}
  • ENV_VAR_NAME: Environment variable name (without prefix - prefix is applied automatically)
  • default:value: Optional default value if environment variable is not set

Supported Types

  • string: Direct assignment
  • int and int64: Parsed using strconv.ParseInt
  • bool: Parsed using strconv.ParseBool (accepts: true, false, 1, 0, t, f, TRUE, FALSE, True, False)
  • time.Duration: Parsed using time.ParseDuration (e.g., "10s", "5m", "1h30m")

Debug Mode

Enable debug output to see loaded configuration values:

BEAVER_CONFIG_DEBUG=true ./myapp

This will print all loaded configuration values in the format:

[BEAVER] BEAVER_DATABASE_URL=postgres://localhost/myapp
[BEAVER] BEAVER_PORT=8080
[BEAVER] BEAVER_DEBUG=false

Debug output is also automatically enabled when env is set to development, dev, or test.

Package Integration Pattern

Basic Package Configuration
package mypackage

type Config struct {
    APIKey string `env:"API_KEY"`     // Will be prefixed as BEAVER_API_KEY
    Host   string `env:"HOST,default:localhost"`
    Port   int    `env:"PORT,default:8080"`
}

func GetConfig() (*Config, error) {
    cfg := &Config{}
    if err := config.Load(cfg); err != nil {
        return nil, err
    }
    return cfg, nil
}
Multi-Tenant Package Configuration

For packages that support multiple instances with different configurations:

package database

// Builder pattern for configurable prefix
type Database struct {
    prefix string
}

func WithPrefix(prefix string) *Database {
    return &Database{prefix: prefix}
}

func (db *Database) Connect() (*Connection, error) {
    cfg := &Config{}
    if err := config.Load(cfg, config.LoadOptions{Prefix: db.prefix}); err != nil {
        return nil, err
    }
    // ... create connection
}

// Usage:
prodDB := database.WithPrefix("PROD_").Connect()
testDB := database.WithPrefix("TEST_").Connect()

Advanced Usage

.env File Support

The package automatically loads .env files if present in the working directory:

# .env file
BEAVER_DATABASE_URL=postgres://localhost/dev
BEAVER_DEBUG=true
Multiple Configuration Structs
type DatabaseConfig struct {
    URL      string `env:"DATABASE_URL"`
    MaxConns int    `env:"DATABASE_MAX_CONNS,default:10"`
}

type CacheConfig struct {
    RedisURL string        `env:"REDIS_URL,default:redis://localhost:6379"`
    TTL      time.Duration `env:"CACHE_TTL,default:5m"`
}

// Load multiple configs with same prefix
dbCfg := &DatabaseConfig{}
cacheCfg := &CacheConfig{}

config.Load(dbCfg)    // Uses BEAVER_ prefix by default
config.Load(cacheCfg) // Uses BEAVER_ prefix by default
Custom Prefix for Different Environments
// Determine prefix based on environment
prefix := "BEAVER_"
if env := os.Getenv("APP_ENV"); env == "production" {
    prefix = "PROD_"
}

cfg := &Config{}
config.Load(cfg, config.LoadOptions{Prefix: prefix})

Implementation Details

The config.Load() function:

  1. Automatically loads .env files if present (errors ignored)
  2. Iterates through struct fields using reflection
  3. Reads env tags to get environment variable names
  4. Applies the configured prefix to environment variable names
  5. Loads values from environment or uses defaults
  6. Converts string values to appropriate field types
  7. Supports debug output for development environments

Best Practices

  1. Use struct tags without prefixes - Let the config package handle prefixing
  2. Always provide defaults for optional configuration
  3. Use custom prefixes for multi-tenant applications
  4. Enable debug mode during development to verify configuration
  5. Keep sensitive values in environment variables, not in code
  6. Use .env files for local development only, not in production

Documentation

Overview

Package config provides flexible configuration loading from environment variables with support for custom prefixes, automatic type conversion, and .env file loading.

This package follows the twelve-factor app methodology for configuration management, allowing applications to be easily configured across different environments without code changes. It supports struct-based configuration with field tags and provides builder patterns for advanced usage scenarios.

Basic Usage

Define a configuration struct with environment variable tags:

type Config struct {
    DatabaseURL string `env:"DATABASE_URL"`
    Port        int    `env:"PORT" envDefault:"8080"`
    Debug       bool   `env:"DEBUG" envDefault:"false"`
    Timeout     time.Duration `env:"TIMEOUT" envDefault:"30s"`
}

Load configuration from environment variables:

import "github.com/gobeaver/beaver-kit/config"

var cfg Config
err := config.Load(&cfg)
if err != nil {
    log.Fatal(err)
}

Custom Prefixes

Use custom prefixes to avoid environment variable conflicts:

// Load with custom prefix (will look for MYAPP_DATABASE_URL, MYAPP_PORT, etc.)
err := config.Load(&cfg, config.LoadOptions{Prefix: "MYAPP_"})

Builder Pattern

Many beaver-kit packages support the builder pattern for prefix configuration:

// OAuth with custom prefix
err := oauth.WithPrefix("MYAPP_OAUTH_").Init()

// Database with custom prefix
err := database.WithPrefix("MYAPP_DB_").Init()

Supported Types

The config package automatically handles type conversion for:

  • string: Direct string values
  • int, int8, int16, int32, int64: Integer conversion with validation
  • uint, uint8, uint16, uint32, uint64: Unsigned integer conversion
  • float32, float64: Floating point conversion
  • bool: Boolean conversion ("true", "false", "1", "0", "yes", "no")
  • time.Duration: Duration parsing ("1h30m", "45s", etc.)
  • []string: Comma-separated values
  • Custom types implementing encoding.TextUnmarshaler

Field Tags

Configure field behavior using struct tags:

  • `env:"VAR_NAME"`: Specify environment variable name
  • `envDefault:"value"`: Set default value if environment variable is not set
  • `envRequired:"true"`: Mark field as required (will error if not provided)
  • `envSeparator:"|"`: Use custom separator for slice types (default: ",")

Example with all tags:

type DatabaseConfig struct {
    Host     string   `env:"DB_HOST" envRequired:"true"`
    Port     int      `env:"DB_PORT" envDefault:"5432"`
    Database string   `env:"DB_NAME" envRequired:"true"`
    Options  []string `env:"DB_OPTIONS" envSeparator:"|"`
}

Environment File Support

The package automatically loads .env files from the current directory:

# .env file
DATABASE_URL=postgres://localhost:5432/myapp
PORT=8080
DEBUG=true

Environment variables take precedence over .env file values.

Debug Mode

Enable debug logging to see configuration loading details:

// Enable debug via environment variable
export BEAVER_CONFIG_DEBUG=true

// Or programmatically
err := config.Load(&cfg, config.LoadOptions{Debug: true})

Debug mode shows:

  • Which .env files are loaded
  • Environment variable lookups and values
  • Type conversions and default value usage
  • Configuration validation results

Error Handling

The package provides detailed error information for:

  • Missing required environment variables
  • Type conversion failures
  • Invalid default values
  • Struct validation errors

Example error handling:

var cfg Config
if err := config.Load(&cfg); err != nil {
    fmt.Printf("Configuration error: %v\n", err)
    // Handle specific error types if needed
    return fmt.Errorf("failed to load config: %w", err)
}

Multi-Environment Support

Use different prefixes for different environments:

switch os.Getenv("ENVIRONMENT") {
case "production":
    err = config.Load(&cfg, config.LoadOptions{Prefix: "PROD_"})
case "staging":
    err = config.Load(&cfg, config.LoadOptions{Prefix: "STAGE_"})
default:
    err = config.Load(&cfg, config.LoadOptions{Prefix: "DEV_"})
}

Best Practices

  • Use descriptive environment variable names
  • Provide sensible defaults for non-critical settings
  • Mark security-sensitive variables as required
  • Use the builder pattern for package-specific prefixes
  • Enable debug mode during development
  • Validate loaded configuration before using

Integration with Beaver Kit

All beaver-kit packages use this config system internally:

  • OAuth: BEAVER_OAUTH_* variables with oauth.WithPrefix() support
  • Database: BEAVER_DB_* variables with database.WithPrefix() support
  • Cache: BEAVER_CACHE_* variables with cache.WithPrefix() support
  • Slack: BEAVER_SLACK_* variables with slack.WithPrefix() support

This ensures consistent configuration patterns across the entire toolkit.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(cfg interface{}, opts ...LoadOptions) error

Load populates a struct from .env file and environment variables using reflection. This function automatically loads .env files from the current directory and then reads environment variables to populate the provided struct.

The function uses struct field tags to determine environment variable names:

  • `env:"VAR_NAME"`: Maps the field to the specified environment variable
  • `env:"VAR_NAME,default:value"`: Provides a default value if env var is not set

Environment variable names are automatically prefixed with the value specified in LoadOptions.Prefix (defaults to "BEAVER_").

Parameters:

  • cfg: Pointer to a struct to populate with configuration values
  • opts: Optional LoadOptions to customize loading behavior

Returns an error if:

  • cfg is not a pointer to a struct
  • Type conversion fails for any field
  • Required environment variables are missing (if validation is implemented)

Example:

type Config struct {
    DatabaseURL string `env:"DATABASE_URL"`
    Port        int    `env:"PORT,default:8080"`
    Debug       bool   `env:"DEBUG,default:false"`
}

var cfg Config
err := config.Load(&cfg, config.LoadOptions{Prefix: "MYAPP_"})
// Will look for MYAPP_DATABASE_URL, MYAPP_PORT, MYAPP_DEBUG

Types

type LoadOptions

type LoadOptions struct {
	Prefix string // Prefix to prepend to environment variable names (default: "BEAVER_")
	Debug  bool   // Enable debug logging of configuration loading process
}

LoadOptions defines options for loading configuration from environment variables.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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