configura

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2025 License: MIT Imports: 5 Imported by: 0

README

Configura - Go Shared Configuration Management

Codacy Badge Codacy Badge GoDoc MIT License Tag Version

configura is a Go package designed to simplify application configuration management. It provides a type-safe way to define, load, and access configuration variables from environment variables, and to share these configurations across modules or subpackages in your Go application.

Description

Managing configuration variables, especially across different environments (development, staging, production), can be error-prone. configura addresses this by:

  • Type Safety: Defining configuration variables with specific Go types (e.g., string, int, bool). This helps catch errors at compile-time or during setup rather than runtime.
  • Centralized Definition: Encouraging the definition of all expected configuration variables.
  • Environment Variable Loading: Easily loading values from environment variables with fallbacks for missing ones.
  • Validation: Allowing components or subpackages to declare their required configuration keys and verify their presence.

Usage

1. Define Your Configuration Variables

It's good practice to define your configuration Variable constants in a dedicated package or a specific part of your application.

package config

import "github.com/Kansuler/configura"

// Define your application's configuration variables
const (
	DATABASE_URL     configura.Variable[string] = "DATABASE_URL"
	PORT             configura.Variable[int]    = "PORT"
	API_KEY          configura.Variable[string] = "API_KEY"
	ENABLE_FEATURE_X configura.Variable[bool]   = "ENABLE_FEATURE_X"
	TIMEOUT_SECONDS  configura.Variable[int64]  = "TIMEOUT_SECONDS"
)
2. Initialize and Load Configuration

In your application's main setup (e.g., main.go), you'll initialize a ConfigImpl and load the environment variables.

package main

import (
	"os"

	"github.com/Kansuler/configura"
	"github.com/Kansuler/configura/_example/config"
	"github.com/Kansuler/configura/_example/subpackage"
)

func main() {
	// --- Simulate setting environment variables (for example purposes) ---
	// In a real scenario, these would be set in your shell, Dockerfile, K8s manifest, etc.
	os.Setenv(string(config.DATABASE_URL), "postgres://user:pass@host:port/dbname")
	os.Setenv(string(config.PORT), "8080")
	os.Setenv(string(config.API_KEY), "supersecretapikey")
	os.Setenv(string(config.ENABLE_FEATURE_X), "true")
	os.Setenv(string(subpackage.SUBPACKAGE_DEFINED_CONFIG), "some_value")
	// TIMEOUT_SECONDS is not set, so its fallback will be used.

	// --- Initialize Configura ---
	cfg := configura.New()

	// Load environment variables with fallbacks
	configura.Load(cfg, config.DATABASE_URL, "postgres://fallback_user:fallback_pass@localhost:5432/fallback_db")
	configura.Load(cfg, config.PORT, 3000)  // Fallback port 3000
	configura.Load(cfg, config.API_KEY, "") // Fallback empty string if not set
	configura.Load(cfg, config.ENABLE_FEATURE_X, false)
	configura.Load(cfg, config.TIMEOUT_SECONDS, int64(30)) // Fallback 30 seconds
	configura.Load(cfg, subpackage.SUBPACKAGE_DEFINED_CONFIG, "default_value")

	// Set the configuration by yourself
	configura.Write(cfg, map[configura.Variable[int64]]int64{config.TIMEOUT_SECONDS: 25})

	err := subpackage.Initialize(cfg)
	if err != nil {
		panic(err) // Handle error appropriately in your application
	}
}
3. Subpackage Configuration Validation

A subpackage (e.g., subpackage) can ensure that all configuration variables it depends on are present in the configura.Config instance it receives.

// File: _example/subpackage.go
package subpackage

import (
	"fmt"

	"github.com/Kansuler/configura"
	"github.com/Kansuler/configura/_example/config"
)

const (
	SUBPACKAGE_DEFINED_CONFIG configura.Variable[string] = "SUBPACKAGE_DEFINED_CONFIG"
)

// RequiredUserServiceKeys lists the configuration variables this service needs.
var RequiredUserServiceKeys = []any{
	SUBPACKAGE_DEFINED_CONFIG,
	config.DATABASE_URL,
	config.API_KEY,
}

// Initialize sets up the user service with the given configuration.
// It validates that all required configuration keys are registered.
func Initialize(cfg configura.Config) error {
	// Validate that the config instance has all the keys our service needs
	if err := cfg.Exists(RequiredUserServiceKeys...); err != nil {
		return fmt.Errorf("user service configuration validation failed: %w", err)
	}

	// Access the validated configuration
	dbURL := cfg.String(config.DATABASE_URL)
	apiKey := cfg.String(config.API_KEY)
	definedConfig := cfg.String(SUBPACKAGE_DEFINED_CONFIG)

	fmt.Printf("UserService: Initializing with DB URL: %s and API Key (present: %t), and has subpackage defined key (present: %s)\n", dbURL, apiKey != "", definedConfig)
	// ... further initialization logic for the user service ...

	return nil
}
How Exists Works

The Exists method iterates through the provided keys. If any key is not found in the Config's internal maps (meaning Load was not called for it, or it wasn't otherwise set), it returns a ErrMissingVariable. This error contains a list of all the missing keys.

This allows for robust startup checks, ensuring your application components have the configuration they need before they start running.

Contributing

Contributions are welcome! Please feel free to open a pull request with any improvements, bug fixes, or new features.

  1. Fork the repository.
  2. Create your feature branch (git checkout -b feature/AmazingFeature).
  3. Commit your changes (git commit -m 'Add some AmazingFeature').
  4. Push to the branch (git push origin feature/AmazingFeature).
  5. Open a Pull Request.

Please ensure your code is well-tested and follows Go best practices.

License

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMissingVariable = errors.New("missing configuration variables")

Functions

func Bool

func Bool(key Variable[bool], fallback bool) bool

Bool takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Bytes

func Bytes(key Variable[[]byte], fallback []byte) []byte

Bytes takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Fallback

func Fallback[T comparable](value T, fallback T) T

Fallback is a helper function that returns the fallback value if the provided value is empty. Only works on comparable types, which includes basic types like int, string, bool, etc.

func Float32

func Float32(key Variable[float32], fallback float32) float32

Float32 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Float64

func Float64(key Variable[float64], fallback float64) float64

Float64 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Int

func Int(key Variable[int], fallback int) int

Int takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Int8

func Int8(key Variable[int8], fallback int8) int8

Int8 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Int16

func Int16(key Variable[int16], fallback int16) int16

Int16 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Int32

func Int32(key Variable[int32], fallback int32) int32

Int32 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Int64

func Int64(key Variable[int64], fallback int64) int64

Int64 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Load added in v1.0.1

func Load[T constraint](cfg *Config, key Variable[T], fallback T)

Load is a generic function that loads an environment variable into the provided configuration, using the specified key and fallback value. It uses type assertions to determine the type of the key and fallback value, and registers the variable in the appropriate map of the configuration struct.

func Runes

func Runes(key Variable[[]rune], fallback []rune) []rune

Runes takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func String

func String(key Variable[string], fallback string) string

String takes an environment key, and a fallback value. Returns environment value if it isn't unset.

func Uint

func Uint(key Variable[uint], fallback uint) uint

Uint takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Uint8

func Uint8(key Variable[uint8], fallback uint8) uint8

Uint8 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Uint16

func Uint16(key Variable[uint16], fallback uint16) uint16

Uint16 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Uint32

func Uint32(key Variable[uint32], fallback uint32) uint32

Uint32 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Uint64

func Uint64(key Variable[uint64], fallback uint64) uint64

Uint64 takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Uintptr

func Uintptr(key Variable[uintptr], fallback uintptr) uintptr

Uintptr takes an environment key, and a fallback value. Returns environment variable with converted type, or fallback value if it fails.

func Write added in v1.0.1

func Write[T constraint](cfg *Config, values map[Variable[T]]T) error

Write is a generic function that writes configuration values to the provided configuration struct. It uses type assertions to determine the type of the values and writes them to the appropriate map in the configuration struct.

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

config is a concrete implementation of the Config interface, holding maps for each type of configuration variable. It provides methods to retrieve values for each type and checks if all required keys are registered.

func Merge

func Merge(cfgs ...*Config) *Config

Merge combines multiple Config instances into a single Config instance. To ensure a consistent view of the source configurations, it locks all configuration types for reading during the merge operation.

func New added in v1.0.1

func New() *Config

func (*Config) Bool

func (c *Config) Bool(key Variable[bool]) bool

func (*Config) Bytes

func (c *Config) Bytes(key Variable[[]byte]) []byte

func (*Config) Exists added in v1.0.1

func (c *Config) Exists(keys ...any) error

Exists checks if all provided keys are registered in the configuration. To ensure that the client of the package have taken all required keys into consideration when building the configuration object.

func (*Config) Float32

func (c *Config) Float32(key Variable[float32]) float32

func (*Config) Float64

func (c *Config) Float64(key Variable[float64]) float64

func (*Config) Int

func (c *Config) Int(key Variable[int]) int

func (*Config) Int8

func (c *Config) Int8(key Variable[int8]) int8

func (*Config) Int16

func (c *Config) Int16(key Variable[int16]) int16

func (*Config) Int32

func (c *Config) Int32(key Variable[int32]) int32

func (*Config) Int64

func (c *Config) Int64(key Variable[int64]) int64

func (*Config) Runes

func (c *Config) Runes(key Variable[[]rune]) []rune

func (*Config) String

func (c *Config) String(key Variable[string]) string

func (*Config) Uint

func (c *Config) Uint(key Variable[uint]) uint

func (*Config) Uint8

func (c *Config) Uint8(key Variable[uint8]) uint8

func (*Config) Uint16

func (c *Config) Uint16(key Variable[uint16]) uint16

func (*Config) Uint32

func (c *Config) Uint32(key Variable[uint32]) uint32

func (*Config) Uint64

func (c *Config) Uint64(key Variable[uint64]) uint64

func (*Config) Uintptr

func (c *Config) Uintptr(key Variable[uintptr]) uintptr

type MissingVariableError added in v1.0.1

type MissingVariableError struct {
	Keys []string
}

MissingVariableError is an error type that holds a list of missing configuration variable keys.

func (MissingVariableError) Error added in v1.0.1

func (e MissingVariableError) Error() string

Error implements the error interface for missingVariableError.

func (MissingVariableError) Unwrap added in v1.0.1

func (e MissingVariableError) Unwrap() error

Unwrap implements the Unwrap method for the error interface, allowing the error to be unwrapped to ErrMissingVariable.

type Variable

type Variable[T constraint] string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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