Documentation
¶
Overview ¶
Package config provides enterprise-standard configuration management wrapping Viper.
This package offers typed configuration with automatic .env file loading, environment variable precedence, and comprehensive validation.
Package config provides enterprise-standard configuration management wrapping Viper.
Package config provides enterprise-standard configuration management wrapping Viper.
Index ¶
- func ExpandEnvStrict(value string) (string, error)
- func FindProjectRoot(markerFiles ...string) string
- func LoadEnvFile(paths ...string) error
- func LoadEnvFiles(env string, searchPaths ...string) error
- func ValidateDuration(field string, duration time.Duration) error
- func ValidatePort(field string, port int) error
- func ValidatePositive(field string, value int) error
- func ValidateRange[T int | float64](field string, value, min, max T) error
- func ValidateRequired(field, value string) error
- type Config
- type DatabaseConfig
- type LoadOption
- type OpenAIConfig
- type Option
- type ResilienceConfig
- type ServerConfig
- type Standard
- func (s *Standard) AllKeys() []string
- func (s *Standard) BindEnv(key string, envVars ...string) error
- func (s *Standard) Get(key string) interface{}
- func (s *Standard) GetBool(key string) bool
- func (s *Standard) GetDuration(key string) interface{}
- func (s *Standard) GetInt(key string) int
- func (s *Standard) GetString(key string) string
- func (s *Standard) IsSet(key string) bool
- func (s *Standard) Set(key string, value interface{})
- func (s *Standard) Unmarshal(rawVal interface{}) error
- func (s *Standard) Viper() *viper.Viper
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExpandEnvStrict ¶ added in v0.3.0
ExpandEnvStrict expands ${VAR} patterns in value, returning error if VAR is not set. Unlike os.ExpandEnv, this function:
- Fails if any referenced environment variable is not set
- Does NOT support ${VAR:-default} syntax (ignores default values)
- Forces explicit configuration to prevent production surprises
IMPORTANT: Call AFTER LoadEnvFile() so .env values are available.
Example:
// Given DATABASE_URL is set in environment
value := "postgres://${DB_HOST}:${DB_PORT}/mydb"
expanded, err := ExpandEnvStrict(value)
if err != nil {
// Error: environment variable DB_HOST not set
}
func FindProjectRoot ¶ added in v0.3.0
FindProjectRoot searches parent directories for project root markers. Looks for directories containing ALL specified markerFiles. Returns empty string if no root found or if no markers specified.
Example:
// Find directory containing both CLAUDE.md and config.yaml
root := FindProjectRoot("CLAUDE.md", "config.yaml")
if root != "" {
configPath := root + "/config.yaml"
}
func LoadEnvFile ¶
LoadEnvFile loads environment variables from a .env file. Does not override existing environment variables. Silently succeeds if the file doesn't exist.
func LoadEnvFiles ¶ added in v0.3.0
LoadEnvFiles loads .env and optional .env.{env} in correct order. Environment-specific file overrides base .env values. Returns nil if files are missing (this is expected in production).
Search paths are checked in order; first existing file in each category is used. If env is empty, only loads base .env file.
Example:
// Load .env then .env.test for test environment
if err := LoadEnvFiles("test", ".", ".."); err != nil {
log.Printf("Warning: failed to load env files: %v", err)
}
// Load only base .env
_ = LoadEnvFiles("", ".", "..")
func ValidateDuration ¶
ValidateDuration validates that a duration is positive
func ValidatePort ¶
ValidatePort validates that a port number is in the valid range (1-65535)
func ValidatePositive ¶
ValidatePositive validates that an integer is positive (> 0)
func ValidateRange ¶
ValidateRange validates that a value is within a range (inclusive)
func ValidateRequired ¶
ValidateRequired validates that a string field is not empty
Types ¶
type Config ¶ added in v0.4.0
type Config struct {
// contains filtered or unexported fields
}
Config holds all application configuration loaded via Load(). Access typed configs via accessor methods like Database(), Server(), etc.
func Load ¶ added in v0.4.0
func Load(opts ...LoadOption) (*Config, error)
Load creates a fully configured Config by auto-discovering and loading .env and config.yaml files from the current directory or project root.
Discovery order (first found wins):
- Current working directory
- Go module root (directory containing go.mod)
- Git repository root (directory containing .git)
This supports monorepos and git worktrees where config files are at the repository root but the Go module is in a subdirectory.
Files loaded:
- .env: Environment variables (does not override existing)
- config.yaml: Configuration values
Use WithEnvPath/WithConfigPath to override auto-discovery.
Example:
cfg, err := config.Load()
if err != nil {
log.Fatal(err)
}
db := cfg.Database()
func (*Config) Database ¶ added in v0.4.0
func (c *Config) Database() (*DatabaseConfig, error)
Database returns the database configuration. Validates on first access and caches the result.
func (*Config) OpenAI ¶ added in v0.4.0
func (c *Config) OpenAI() (*OpenAIConfig, error)
OpenAI returns the OpenAI configuration. Validates on first access and caches the result.
func (*Config) Resilience ¶ added in v0.4.0
func (c *Config) Resilience() (*ResilienceConfig, error)
Resilience returns the resilience configuration. Validates on first access and caches the result.
func (*Config) Server ¶ added in v0.4.0
func (c *Config) Server() (*ServerConfig, error)
Server returns the server configuration. Validates on first access and caches the result.
func (*Config) Standard ¶ added in v0.4.0
Standard returns the underlying Standard config for advanced usage.
func (*Config) ValidateAll ¶ added in v0.4.0
ValidateAll validates all configuration types and returns the first error. Validation order: database, server, openai, resilience. Use this method for fail-fast behavior when all configs are required.
Example:
cfg, err := config.Load()
if err != nil {
log.Fatal(err)
}
if err := cfg.ValidateAll(); err != nil {
log.Fatal(err)
}
type DatabaseConfig ¶
type DatabaseConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Database string `mapstructure:"database"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
SSLMode string `mapstructure:"ssl_mode"`
// Connection pool settings
MaxConns int `mapstructure:"max_conns"`
MinConns int `mapstructure:"min_conns"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time"`
// Retry settings
RetryAttempts int `mapstructure:"retry_attempts"`
RetryDelay time.Duration `mapstructure:"retry_delay"`
// Health check
HealthCheckPeriod time.Duration `mapstructure:"health_check_period"`
}
DatabaseConfig holds PostgreSQL database configuration with connection pooling settings.
func DatabaseConfigFromViper ¶
func DatabaseConfigFromViper(s *Standard) DatabaseConfig
DatabaseConfigFromViper creates a DatabaseConfig from a Standard config loader.
Environment variable mappings:
- DATABASE_URL -> full connection URL (takes precedence over individual vars)
- DB_HOST -> host (default: localhost)
- DB_PORT -> port (default: 5432)
- DB_NAME -> database (default: postgres)
- DB_USER -> user (default: postgres)
- DB_PASSWORD -> password
- DB_SSLMODE -> ssl_mode (default: disable)
- DB_MAX_CONNS -> max_conns (default: 25)
- DB_MIN_CONNS -> min_conns (default: 5)
- DB_CONN_MAX_LIFETIME -> conn_max_lifetime (default: 1h)
- DB_CONN_MAX_IDLE_TIME -> conn_max_idle_time (default: 10m)
- DB_RETRY_ATTEMPTS -> retry_attempts (default: 3)
- DB_RETRY_DELAY -> retry_delay (default: 2s)
- DB_HEALTH_CHECK_PERIOD -> health_check_period (default: 30s)
When DATABASE_URL is set, it takes precedence over individual connection variables (DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD, DB_SSLMODE). Pool settings (DB_MAX_CONNS, etc.) are always read from individual env vars and applied regardless of whether DATABASE_URL is used.
func ParseDatabaseURL ¶ added in v0.4.0
func ParseDatabaseURL(rawURL string) (*DatabaseConfig, error)
ParseDatabaseURL parses a PostgreSQL connection URL into a DatabaseConfig.
Supported URL schemes: postgres://, postgresql://
URL format: postgres://user:password@host:port/database?sslmode=value
The function extracts:
- host: from URL host
- port: from URL port (default: 5432)
- database: from URL path (without leading slash)
- user: from URL userinfo
- password: from URL userinfo
- sslmode: from query parameter (default: disable)
Returns an error for invalid URLs or unsupported schemes.
Example:
cfg, err := config.ParseDatabaseURL("postgres://user:pass@localhost:5432/mydb?sslmode=require")
if err != nil {
log.Fatal(err)
}
func (*DatabaseConfig) ConnectionString ¶
func (c *DatabaseConfig) ConnectionString() string
ConnectionString returns a PostgreSQL connection string
func (*DatabaseConfig) Validate ¶
func (c *DatabaseConfig) Validate() error
Validate validates the database configuration
type LoadOption ¶ added in v0.4.0
type LoadOption func(*loadOptions)
LoadOption configures the Load function using the functional options pattern.
func WithConfigPath ¶ added in v0.4.0
func WithConfigPath(path string) LoadOption
WithConfigPath specifies an explicit config file path, disabling auto-discovery.
func WithEnvPath ¶ added in v0.4.0
func WithEnvPath(path string) LoadOption
WithEnvPath specifies an explicit .env file path, disabling auto-discovery.
func WithLogger ¶ added in v0.4.0
func WithLogger(logger *slog.Logger) LoadOption
WithLogger sets a custom slog logger for discovery events.
func WithPrefix ¶ added in v0.4.0
func WithPrefix(prefix string) LoadOption
WithPrefix sets the environment variable prefix (default: APP).
type OpenAIConfig ¶
type OpenAIConfig struct {
APIKey string `mapstructure:"api_key"`
Model string `mapstructure:"model"`
Temperature float64 `mapstructure:"temperature"`
MaxTokens int `mapstructure:"max_tokens"`
Timeout time.Duration `mapstructure:"timeout"`
}
OpenAIConfig holds OpenAI API configuration
func OpenAIConfigFromViper ¶
func OpenAIConfigFromViper(s *Standard) OpenAIConfig
OpenAIConfigFromViper creates an OpenAIConfig from a Standard config loader.
Environment variable mappings:
- OPENAI_API_KEY -> api_key (required)
- OPENAI_MODEL -> model (default: gpt-3.5-turbo)
- OPENAI_TEMPERATURE -> temperature (default: 0.7)
- OPENAI_MAX_TOKENS -> max_tokens (default: 2000)
- OPENAI_TIMEOUT -> timeout (default: 30s)
func (*OpenAIConfig) Validate ¶
func (c *OpenAIConfig) Validate() error
Validate validates the OpenAI configuration
type Option ¶
Option configures the Standard config loader using the functional options pattern.
func WithConfigFile ¶
WithConfigFile specifies a config file to load (YAML, JSON, TOML, etc.)
func WithConfigName ¶
WithConfigName sets the name of the config file to search for (without extension)
func WithConfigPaths ¶
WithConfigPaths adds paths to search for the config file
func WithConfigType ¶
WithConfigType sets the type of the config file (yaml, json, toml, etc.)
func WithEnvFile ¶
WithEnvFile loads environment variables from a specific .env file
func WithEnvPrefix ¶
WithEnvPrefix sets the environment variable prefix (default: APP_)
func WithoutEnvFile ¶
func WithoutEnvFile() Option
WithoutEnvFile disables automatic .env file loading
type ResilienceConfig ¶ added in v0.1.2
type ResilienceConfig struct {
// Retry settings
MaxRetries int `mapstructure:"max_retries"`
InitialDelay time.Duration `mapstructure:"initial_delay"`
MaxDelay time.Duration `mapstructure:"max_delay"`
Multiplier float64 `mapstructure:"multiplier"`
// Circuit breaker settings
MaxRequests uint32 `mapstructure:"max_requests"`
Interval time.Duration `mapstructure:"interval"`
Timeout time.Duration `mapstructure:"timeout"`
FailureThreshold float64 `mapstructure:"failure_threshold"`
}
ResilienceConfig holds retry and circuit breaker configuration. This provides standardized resilience settings that can be used across all packages that implement retry and circuit breaker patterns.
func ResilienceConfigFromViper ¶ added in v0.1.2
func ResilienceConfigFromViper(s *Standard) ResilienceConfig
ResilienceConfigFromViper creates a ResilienceConfig from a Standard config loader.
Environment variable mappings:
- RESILIENCE_MAX_RETRIES -> max_retries (default: 3)
- RESILIENCE_INITIAL_DELAY -> initial_delay (default: 1s)
- RESILIENCE_MAX_DELAY -> max_delay (default: 30s)
- RESILIENCE_MULTIPLIER -> multiplier (default: 2.0)
- RESILIENCE_MAX_REQUESTS -> max_requests (default: 10)
- RESILIENCE_INTERVAL -> interval (default: 10s)
- RESILIENCE_TIMEOUT -> timeout (default: 60s)
- RESILIENCE_FAILURE_THRESHOLD -> failure_threshold (default: 0.6)
func (*ResilienceConfig) Validate ¶ added in v0.1.2
func (c *ResilienceConfig) Validate() error
Validate validates the resilience configuration
type ServerConfig ¶
type ServerConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
ReadTimeout time.Duration `mapstructure:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
}
ServerConfig holds HTTP server configuration
func ServerConfigFromViper ¶
func ServerConfigFromViper(s *Standard) ServerConfig
ServerConfigFromViper creates a ServerConfig from a Standard config loader.
Environment variable mappings:
- SERVER_HOST -> host (default: localhost)
- SERVER_PORT -> port (default: 8080)
- SERVER_READ_TIMEOUT -> read_timeout (default: 15s)
- SERVER_WRITE_TIMEOUT -> write_timeout (default: 15s)
- SERVER_IDLE_TIMEOUT -> idle_timeout (default: 60s)
func (*ServerConfig) Address ¶
func (c *ServerConfig) Address() string
Address returns the server address in host:port format
func (*ServerConfig) Validate ¶
func (c *ServerConfig) Validate() error
Validate validates the server configuration
type Standard ¶
type Standard struct {
// contains filtered or unexported fields
}
Standard wraps Viper to provide enterprise-standard configuration loading with automatic .env file support, environment variable precedence, and validation.
func NewStandard ¶
NewStandard creates a new Standard config loader with the given options.
By default: - Loads .env files from current directory (silently ignored if missing) - Reads environment variables with APP_ prefix - Replaces dots and hyphens with underscores in env var names
Options can override any of these defaults.
func (*Standard) BindEnv ¶
BindEnv binds a config key to environment variables. With no envVars argument, it uses the key as the env var name. With one or more envVars, it checks each in order until finding a set value.
func (*Standard) GetDuration ¶
GetDuration retrieves a duration value