config

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2025 License: LGPL-3.0 Imports: 23 Imported by: 0

README

Go Config Library

[!CAUTION] This is highly experimental 🧪 and expect breaking changes

Go Reference

A comprehensive, feature-rich configuration management library for Go applications that supports multiple file formats, environment variables, command-line flags, and advanced validation.

Overview

This library provides a unified interface for managing application configuration from multiple sources with intelligent merging, validation, and binding capabilities. It's designed to handle complex configuration scenarios while maintaining simplicity for basic use cases.

Key Features

  • Multi-format support: JSON, YAML, TOML, and more via extensible codecs
  • Multiple sources: Files, environment variables, command-line flags
  • Intelligent merging: Deep merging of configuration with override support
  • Validation: Comprehensive validation with built-in and custom rules
  • Struct binding: Automatic mapping to Go structs with tags
  • XDG compliance: Proper support for XDG Base Directory Specification
  • Recursive includes: Configuration files can include other files
  • Type-safe access: Extensive getter methods with error handling variants

Installation

go get github.com/Nadim147c/go-config

Quick Start

package main

import (
    "fmt"
    "github.com/Nadim147c/go-config"
)

type AppConfig struct {
    Port     int    `config:"port" check:"required,min=1024,max=65535"`
    Env      string `config:"env" check:"default=production"`
    Database struct {
        Host     string `config:"host" check:"required"`
        Port     int    `config:"port" check:"default=5432"`
        SSL      bool   `config:"ssl" check:"default=true"`
    } `config:"database"`
}

func main() {
    // Add configuration paths
    config.AddPath("/etc/myapp")
    config.AddPath("$XDG_CONFIG_HOME/myapp")
    config.AddPath("./config")

    // Load configuration
    if err := config.ReadConfig(); err != nil {
        panic(err)
    }

    // Bind to struct
    var appConfig AppConfig
    if err := config.Bind("app", &appConfig); err != nil {
        panic(err)
    }

    fmt.Printf("Server running on port %d in %s environment\n",
        appConfig.Port, appConfig.Env)
}

Configuration Sources

File-based Configuration
cfg := config.New()

// Add specific files
cfg.AddFile("/etc/app/config.yaml")
cfg.AddFile("~/.config/app/config.json")

// Add search directories
cfg.AddPath("/etc/app/conf.d")
cfg.AddPath("$XDG_CONFIG_HOME/app")
cfg.AddPath("./config")

// Load all configuration
err := cfg.ReadConfig()

Supported file extensions: .json, .yaml, .yml, .toml.

Environment Variables
cfg := config.New()
cfg.SetEnvPrefix("APP_") // Sets prefix for environment variables

// Environment variable APP_DATABASE__HOST maps to database.host
Command-line Flags
import "github.com/spf13/pflag"

func main() {
    flags := pflag.NewFlagSet("app", pflag.ContinueOnError)
    flags.Int("port", 8080, "server port")
    flags.String("env", "development", "environment")

    cfg := config.New()
    cfg.SetPflagSet(flags)

    // Now --port and --env flags will be available in configuration
}

Configuration Structure

File Format Examples

JSON:

{
  "app": {
    "port": 8080,
    "env": "production",
    "include": ["database.json", "cache.yaml"]
  }
}

YAML:

app:
  port: 8080
  env: production
  include:
    - database.json
    - cache.yaml

database:
  host: localhost
  port: 5432
  ssl: true
Recursive Includes

Configuration files can include other files using the include key:

{
  "include": ["base-config.yaml", "secrets.json"],
  "app": {
    "port": 8080
  }
}

Files are loaded in order, with later files overriding earlier ones.

Accessing Configuration

Basic Access Methods
// Get values with different error handling approaches
port := cfg.GetInt("app.port")                    // Returns 0 if missing
port := cfg.GetIntMust("app.port")                // Panics if missing
port, err := cfg.GetIntE("app.port")              // Returns error if missing

// Type-specific getters
str := cfg.GetString("app.name")
num := cfg.GetInt("app.workers")
flag := cfg.GetBool("app.debug")
Map Access
// Get maps of various types
settings := cfg.GetStringMap("app.settings")
users := cfg.GetStringMapString("app.users")
counts := cfg.GetStringMapInt("app.counts")
flags := cfg.GetStringMapBool("app.features")
Advanced Access
// Get reflect.Value for advanced manipulation
value := cfg.GetReflection("app.complexSetting")

// Check if key exists
if _, err := cfg.GetE("app.optional"); err != nil {
    // Key doesn't exist
}

// Get all top-level keys
keys := cfg.Keys()

Struct Binding

Basic Binding
type Config struct {
    Port    int    `config:"port"`
    Env     string `config:"env"`
    Debug   bool   `config:"debug"`
    Timeout int    `config:"timeout"`
}

var appConfig Config
err := cfg.Bind("app", &appConfig)
Nested Structures
type DatabaseConfig struct {
    Host     string `config:"host"`
    Port     int    `config:"port"`
    Username string `config:"username"`
    Password string `config:"password"`
}

type AppConfig struct {
    Name     string        `config:"name"`
    Port     int           `config:"port"`
    Database DatabaseConfig `config:"database"`
}

var config AppConfig
err := cfg.Bind("", &config) // Bind to root
Validation with Tags
type UserConfig struct {
    Email    string `config:"email" check:"required,email"`
    Age      int    `config:"age" check:"min=18,max=120"`
    Password string `config:"password" check:"required,min=8"`
    APIKey   string `config:"api_key" check:"uuid"`
    Theme    string `config:"theme" check:"default=light"`
}

Available validation rules:

  • required - Field must be non-zero
  • default=value - Set default value if empty
  • min, max - Numeric/string length bounds
  • email - Valid email format
  • uuid - Valid UUID format
  • alpha - Alphabetic characters only
  • alphanumeric - Alphanumeric characters only
  • number - Digits only
  • base64 - Valid base64 encoding
  • match=regex - Custom regex pattern

Advanced Features

Deep Merging
// Manual deep merging of maps
result := config.DeepMerge(
    map[string]any{"a": 1, "b": map[string]any{"x": 1}},
    map[string]any{"b": map[string]any{"y": 2}, "c": 3}
)
// Result: {"a": 1, "b": {"x": 1, "y": 2}, "c": 3}
Path Resolution
// Resolve paths with environment variables
path, err := config.FindPath("/base/path", "$HOME/config/app.yaml")
// Expands to: /home/user/config/app.yaml

// Supported variables:
// - $HOME, ~
// - $XDG_CONFIG_HOME, $XDG_CACHE_HOME, $XDG_DATA_HOME
// - $TMPDIR, $PWD
// - XDG user directories: Desktop, Documents, Downloads, etc.

Error Handling

The library provides multiple error handling patterns:

// Method variants for different error handling needs
val := cfg.GetString("key")          // Returns zero value on error
val := cfg.GetStringMust("key")      // Panics on error
val, err := cfg.GetStringE("key")    // Returns error

// Helper functions for concise error handling
val := config.Must(cfg.GetStringE("key"))     // Panics on error
val := config.Should(cfg.GetStringE("key"))   // Ignores error, returns zero value

Best Practices

Configuration Organization
  1. Leverage includes for environment-specific configurations
  2. Use XDG directories for proper filesystem organization
  3. Validate early with comprehensive validation rules
  4. Provide sensible defaults for all configuration options
Performance
  • Load configuration once at application startup
  • Use struct binding for frequently accessed values
  • Cache computed configuration values if needed

Examples

Web Server Configuration
type ServerConfig struct {
    Addr         string        `config:"addr" check:"default=:8080"`
    ReadTimeout  time.Duration `config:"read_timeout" check:"default=30s"`
    WriteTimeout time.Duration `config:"write_timeout" check:"default=30s"`
    TLS          struct {
        Enabled bool   `config:"enabled" check:"default=false"`
        Cert    string `config:"cert"`
        Key     string `config:"key"`
    } `config:"tls"`
}

func LoadConfig() (*ServerConfig, error) {
    cfg := config.New()
    cfg.AddPath("/etc/myserver")
    cfg.AddPath("$XDG_CONFIG_HOME/myserver")

    if err := cfg.ReadConfig(); err != nil {
        return nil, err
    }

    var serverConfig ServerConfig
    if err := cfg.Bind("server", &serverConfig); err != nil {
        return nil, err
    }

    return &serverConfig, nil
}
Database Configuration with Validation
type DBConfig struct {
    Host     string `config:"host" check:"required"`
    Port     int    `config:"port" check:"default=5432,min=1,max=65535"`
    Name     string `config:"name" check:"required"`
    User     string `config:"user" check:"required"`
    Password string `config:"password" check:"required"`
    SSLMode  string `config:"ssl_mode" check:"default=require"`
    Pool     struct {
        MaxConns    int           `config:"max_conns" check:"default=10,min=1"`
        MaxIdleTime time.Duration `config:"max_idle_time" check:"default=5m"`
    } `config:"pool"`
}

API Reference

See the generated documentation at the top of this file for complete API details. The library provides extensive methods for configuration access, manipulation, and validation.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes with tests
  4. Ensure all tests pass
  5. Submit a pull request

License

This project is licensed under the GNU-LGPL-3.0 License.

Documentation

Overview

This file is auto generated; DO NOT EDIT IT.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFile

func AddFile(p string)

AddFile adds a specific file path to the Config instance, marking it to be loaded as a configuration file. The file is added to both the fullPath map (to track specific files) and the general paths list (for search purposes). This allows for both explicit file loading and path-based searching.

func AddPath

func AddPath(p string)

AddPath adds a file path to the Config instance's list of search paths. These paths will be used when looking for configuration files to load. Duplicate paths may be added.

func AddPflag

func AddPflag(name string, f *pflag.Flag)

AddPflag adds *pflag.FlagSet

func Bind

func Bind(prefix string, v any) error

Bind maps configuration values from the Config instance into a structured Go type. It uses struct tags to determine how to bind the data and can also perform validation.

Parameters:

  • prefix: The prefix to prepend to all configuration keys
  • v: A pointer to a struct where the configuration values will be populated

Returns:

  • error: If the input is not a non-nil pointer, or if binding fails

func Changed

func Changed(key string) bool

Changed checks if a value is changed.

func DeepMerge

func DeepMerge(dst, src map[string]any) map[string]any

DeepMerge recursively merges src into dst, combining nested maps rather than replacing them. Non-map values in src overwrite those in dst. Both maps must have string keys. Returns the updated dst.

Example:

dst = { "a": { "x": 1 }, "b": 2 }
src = { "a": { "y": 3 }, "b": 4 }
DeepMerge(dst, src) → { "a": { "x": 1, "y": 3 }, "b": 4 }

func FindPath

func FindPath(base, input string) (string, error)

FindPath expands environment-aware variables and returns an absolute path from a given base path (not CWD). Path Prefix Expands:

  • $HOME or ~ : xdg.Home
  • $XDG_CONFIG_HOME : xdg.ConfigHome
  • $XDG_CACHE_HOME : xdg.CacheHome
  • $XDG_DATA_HOME : xdg.DataHome
  • $TMPDIR : os.TempDir()
  • $PWD : Current Working Directorie
  • $XDG_DESKTOP_DIR : xdg.UserDirs.Desktop
  • $XDG_DOCUMENTS_DIR : xdg.UserDirs.Documents
  • $XDG_DOWNLOAD_DIR : xdg.UserDirs.Download
  • $XDG_MUSIC_DIR : xdg.UserDirs.Music
  • $XDG_PICTURES_DIR : xdg.UserDirs.Pictures
  • $XDG_PUBLICSHARE_DIR : xdg.UserDirs.PublicShare
  • $XDG_TEMPLATES_DIR : xdg.UserDirs.Templates
  • $XDG_VIDEOS_DIR : xdg.UserDirs.Videos

func Get

func Get(key string) any

Get returns the value for the key. Returns default if missing/invalid.

func GetBool

func GetBool(key string) bool

GetBool returns the bool value for the key. Returns default if missing/invalid.

func GetBoolE

func GetBoolE(key string) (bool, error)

GetBoolE returns the bool value for the key, or error if missing/invalid.

func GetBoolMust

func GetBoolMust(key string) bool

GetBoolMust returns the bool value for the key. Panics if missing/invalid.

func GetConfigFiles

func GetConfigFiles() []string

GetConfigFiles returns all config file paths to be loaded by ReadConfig. It resolves registered files (AddFile) and directories (AddPath), matching the config filename across supported extensions. Missing or invalid paths are skipped with debug logs. Paths are returned in registration order.

Example: fileName "config", path "/etc/app" → matches "/etc/app/config.json", "/etc/app/config.yaml", etc.

func GetE

func GetE(key string) (any, error)

GetE returns the value for the key, or error if missing/invalid.

func GetInt

func GetInt(key string) int

GetInt returns the int value for the key. Returns default if missing/invalid.

func GetInt64

func GetInt64(key string) int64

GetInt64 returns the int64 value for the key. Returns default if missing/invalid.

func GetInt64E

func GetInt64E(key string) (int64, error)

GetInt64E returns the int64 value for the key, or error if missing/invalid.

func GetInt64Must

func GetInt64Must(key string) int64

GetInt64Must returns the int64 value for the key. Panics if missing/invalid.

func GetIntE

func GetIntE(key string) (int, error)

GetIntE returns the int value for the key, or error if missing/invalid.

func GetIntMust

func GetIntMust(key string) int

GetIntMust returns the int value for the key. Panics if missing/invalid.

func GetLogger

func GetLogger() *slog.Logger

GetLogger returns the configured logger, or a no-op logger if none is set.

func GetMust

func GetMust(key string) any

GetMust returns the value for the key. Panics if missing/invalid.

func GetReflection

func GetReflection(key string) reflect.Value

GetReflection returns the reflection value for the key. Returns default if missing/invalid.

func GetReflectionE

func GetReflectionE(key string) (reflect.Value, error)

GetReflectionE returns the reflection value for the key, or error if missing/invalid.

func GetReflectionMust

func GetReflectionMust(key string) reflect.Value

GetReflectionMust returns the reflection value for the key. Panics if missing/invalid.

func GetString

func GetString(key string) string

GetString returns the string value for the key. Returns default if missing/invalid.

func GetStringE

func GetStringE(key string) (string, error)

GetStringE returns the string value for the key, or error if missing/invalid.

func GetStringMap

func GetStringMap(key string) map[string]any

GetStringMap returns the stringmap value for the key. Returns default if missing/invalid.

func GetStringMapBool

func GetStringMapBool(key string) map[string]bool

GetStringMapBool returns the stringmapbool value for the key. Returns default if missing/invalid.

func GetStringMapBoolE

func GetStringMapBoolE(key string) (map[string]bool, error)

GetStringMapBoolE returns the stringmapbool value for the key, or error if missing/invalid.

func GetStringMapBoolMust

func GetStringMapBoolMust(key string) map[string]bool

GetStringMapBoolMust returns the stringmapbool value for the key. Panics if missing/invalid.

func GetStringMapE

func GetStringMapE(key string) (map[string]any, error)

GetStringMapE returns the stringmap value for the key, or error if missing/invalid.

func GetStringMapInt

func GetStringMapInt(key string) map[string]int

GetStringMapInt returns the stringmapint value for the key. Returns default if missing/invalid.

func GetStringMapInt64

func GetStringMapInt64(key string) map[string]int64

GetStringMapInt64 returns the stringmapint64 value for the key. Returns default if missing/invalid.

func GetStringMapInt64E

func GetStringMapInt64E(key string) (map[string]int64, error)

GetStringMapInt64E returns the stringmapint64 value for the key, or error if missing/invalid.

func GetStringMapInt64Must

func GetStringMapInt64Must(key string) map[string]int64

GetStringMapInt64Must returns the stringmapint64 value for the key. Panics if missing/invalid.

func GetStringMapIntE

func GetStringMapIntE(key string) (map[string]int, error)

GetStringMapIntE returns the stringmapint value for the key, or error if missing/invalid.

func GetStringMapIntMust

func GetStringMapIntMust(key string) map[string]int

GetStringMapIntMust returns the stringmapint value for the key. Panics if missing/invalid.

func GetStringMapMust

func GetStringMapMust(key string) map[string]any

GetStringMapMust returns the stringmap value for the key. Panics if missing/invalid.

func GetStringMapString

func GetStringMapString(key string) map[string]string

GetStringMapString returns the stringmapstring value for the key. Returns default if missing/invalid.

func GetStringMapStringE

func GetStringMapStringE(key string) (map[string]string, error)

GetStringMapStringE returns the stringmapstring value for the key, or error if missing/invalid.

func GetStringMapStringMust

func GetStringMapStringMust(key string) map[string]string

GetStringMapStringMust returns the stringmapstring value for the key. Panics if missing/invalid.

func GetStringMapStringSlice

func GetStringMapStringSlice(key string) map[string][]string

GetStringMapStringSlice returns the stringmapstringslice value for the key. Returns default if missing/invalid.

func GetStringMapStringSliceE

func GetStringMapStringSliceE(key string) (map[string][]string, error)

GetStringMapStringSliceE returns the stringmapstringslice value for the key, or error if missing/invalid.

func GetStringMapStringSliceMust

func GetStringMapStringSliceMust(key string) map[string][]string

GetStringMapStringSliceMust returns the stringmapstringslice value for the key. Panics if missing/invalid.

func GetStringMapUint

func GetStringMapUint(key string) map[string]uint

GetStringMapUint returns the stringmapuint value for the key. Returns default if missing/invalid.

func GetStringMapUint64

func GetStringMapUint64(key string) map[string]uint64

GetStringMapUint64 returns the stringmapuint64 value for the key. Returns default if missing/invalid.

func GetStringMapUint64E

func GetStringMapUint64E(key string) (map[string]uint64, error)

GetStringMapUint64E returns the stringmapuint64 value for the key, or error if missing/invalid.

func GetStringMapUint64Must

func GetStringMapUint64Must(key string) map[string]uint64

GetStringMapUint64Must returns the stringmapuint64 value for the key. Panics if missing/invalid.

func GetStringMapUintE

func GetStringMapUintE(key string) (map[string]uint, error)

GetStringMapUintE returns the stringmapuint value for the key, or error if missing/invalid.

func GetStringMapUintMust

func GetStringMapUintMust(key string) map[string]uint

GetStringMapUintMust returns the stringmapuint value for the key. Panics if missing/invalid.

func GetStringMust

func GetStringMust(key string) string

GetStringMust returns the string value for the key. Panics if missing/invalid.

func GetUint

func GetUint(key string) uint

GetUint returns the uint value for the key. Returns default if missing/invalid.

func GetUint64

func GetUint64(key string) uint64

GetUint64 returns the uint64 value for the key. Returns default if missing/invalid.

func GetUint64E

func GetUint64E(key string) (uint64, error)

GetUint64E returns the uint64 value for the key, or error if missing/invalid.

func GetUint64Must

func GetUint64Must(key string) uint64

GetUint64Must returns the uint64 value for the key. Panics if missing/invalid.

func GetUintE

func GetUintE(key string) (uint, error)

GetUintE returns the uint value for the key, or error if missing/invalid.

func GetUintMust

func GetUintMust(key string) uint

GetUintMust returns the uint value for the key. Panics if missing/invalid.

func Keys

func Keys() []string

Keys returns top-level keys of config

func Must

func Must[T any](v T, err error) T

Must indicates that there Must not be any error; it panics if an error occurs.

func ReadConfig

func ReadConfig() error

ReadConfig loads config files from GetConfigFiles(), following any "include" directives to merge additional files recursively. Later values override earlier ones.

Example:

main.json:
  { "include": ["a.yaml"], "app": { "port": "8080" } }
a.yaml:
  app: { "port": 9000, "env": "prod" }

Result:

app.port = "8080"   // overridden by main.json
app.env  = "prod"   // merged from a.yaml

func Set

func Set(key string, v any) error

Set sets a value in the configuration under the specified key.

func SetDefault

func SetDefault(key string, v any) error

SetDefault sets a value in the configuration's default values under the specified key.

func SetEnvPrefix

func SetEnvPrefix(p string)

SetEnvPrefix sets the environment variable prefix for the configuration. All underscores in the provided string are removed before assignment.

For example, calling SetEnvPrefix("APP_") will set the prefix to "APP".

func SetFormat

func SetFormat(f string)

SetFormat sets the default configuration format for this Config instance. The format will be used when no specific encoder/decoder is available for a requested format. Typical formats include "json", "yaml", "toml", etc.

func SetLogger

func SetLogger(l *slog.Logger)

SetLogger sets logger

func SetPflagSet

func SetPflagSet(fs *pflag.FlagSet)

SetPflagSet adds *pflag.FlagSet

func Settings

func Settings() map[string]any

Settings returns the settings map

func Should

func Should[T any](v T, _ error) T

Should indicates that there should not be any error; it ignores the error.

func Validate

func Validate(sf reflect.StructField, sfv reflect.Value, changed bool) error

Validate applies validation rules to a given struct field based on its "check" tag.

It supports the following rules:

  • required: Field must be changed from its zero value (checked via the `changed` flag).
  • default: If the field is zero-valued, sets it to the specified default value (supports string, int, uint, float, bool).
  • enum: Ensures the field is a one of the given comma (,) sperated enum. Note: enum must be inside a qoute. enum='a,b,c'
  • base64: Ensures the field is a valid base64-encoded string (length, character set, padding).
  • email: Ensures the field is a valid email address without a display name.
  • uuid: Ensures the field is a valid UUID.
  • alpha: Field must contain only alphabetic letters (A-Z, a-z).
  • alphanumeric: Field must contain only letters or digits.
  • number: Field must contain only digits (0-9).
  • match: Field must match the provided regular expression pattern.
  • min: For strings, arrays, slices, channels, and maps, enforces a minimum length; for integers/unsigned integers, enforces a minimum numeric value.
  • max: For strings, arrays, slices, channels, and maps, enforces a maximum length; for integers/unsigned integers, enforces a maximum numeric value.

Parameters:

  • sf: The struct field metadata.
  • sfv: The reflect.Value of the struct field.
  • changed: Indicates whether the field value has been modified from its original state.

Returns:

  • error: A descriptive error if validation fails, or nil if all rules pass.

Panics if:

  • An unknown validation rule is provided.
  • A rule is applied to an unsupported type.
  • "default" rule is applied to an unsupported kind.
  • Type mismatches occur for rules like base64, email, uuid, alpha, alphanumeric, number, or match.

Types

type Config

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

Config represents an application configuration container. It holds configuration values loaded from files, environment variables, or other sources. The struct also manages metadata and encoding/decoding behavior for configuration data.

func Default

func Default() *Config

Default returns default *Config

func New

func New() *Config

New creates Config instance.

func (*Config) AddFile

func (c *Config) AddFile(p string)

AddFile adds a specific file path to the Config instance, marking it to be loaded as a configuration file. The file is added to both the fullPath map (to track specific files) and the general paths list (for search purposes). This allows for both explicit file loading and path-based searching.

func (*Config) AddPath

func (c *Config) AddPath(p string)

AddPath adds a file path to the Config instance's list of search paths. These paths will be used when looking for configuration files to load. Duplicate paths may be added.

func (*Config) AddPflag

func (c *Config) AddPflag(name string, f *pflag.Flag)

AddPflag adds *pflag.FlagSet

func (*Config) Bind

func (c *Config) Bind(prefix string, v any) error

Bind maps configuration values from the Config instance into a structured Go type. It uses struct tags to determine how to bind the data and can also perform validation.

Parameters:

  • prefix: The prefix to prepend to all configuration keys
  • v: A pointer to a struct where the configuration values will be populated

Returns:

  • error: If the input is not a non-nil pointer, or if binding fails

func (*Config) Changed

func (c *Config) Changed(key string) bool

Changed checks if a value is changed.

func (*Config) Get

func (c *Config) Get(key string) any

Get returns the value for the key. Returns default if missing/invalid.

func (*Config) GetBool

func (c *Config) GetBool(key string) bool

GetBool returns the bool value for the key. Returns default if missing/invalid.

func (*Config) GetBoolE

func (c *Config) GetBoolE(key string) (bool, error)

GetBoolE returns the bool value for the key, or error if missing/invalid.

func (*Config) GetBoolMust

func (c *Config) GetBoolMust(key string) bool

GetBoolMust returns the bool value for the key. Panics if missing/invalid.

func (*Config) GetConfigFiles

func (c *Config) GetConfigFiles() []string

GetConfigFiles returns all config file paths to be loaded by ReadConfig. It resolves registered files (AddFile) and directories (AddPath), matching the config filename across supported extensions. Missing or invalid paths are skipped with debug logs. Paths are returned in registration order.

Example: fileName "config", path "/etc/app" → matches "/etc/app/config.json", "/etc/app/config.yaml", etc.

func (*Config) GetE

func (c *Config) GetE(key string) (any, error)

GetE returns the value for the key, or error if missing/invalid.

func (*Config) GetInt

func (c *Config) GetInt(key string) int

GetInt returns the int value for the key. Returns default if missing/invalid.

func (*Config) GetInt64

func (c *Config) GetInt64(key string) int64

GetInt64 returns the int64 value for the key. Returns default if missing/invalid.

func (*Config) GetInt64E

func (c *Config) GetInt64E(key string) (int64, error)

GetInt64E returns the int64 value for the key, or error if missing/invalid.

func (*Config) GetInt64Must

func (c *Config) GetInt64Must(key string) int64

GetInt64Must returns the int64 value for the key. Panics if missing/invalid.

func (*Config) GetIntE

func (c *Config) GetIntE(key string) (int, error)

GetIntE returns the int value for the key, or error if missing/invalid.

func (*Config) GetIntMust

func (c *Config) GetIntMust(key string) int

GetIntMust returns the int value for the key. Panics if missing/invalid.

func (*Config) GetLogger

func (c *Config) GetLogger() *slog.Logger

GetLogger returns the configured logger, or a no-op logger if none is set.

func (*Config) GetMust

func (c *Config) GetMust(key string) any

GetMust returns the value for the key. Panics if missing/invalid.

func (*Config) GetReflection

func (c *Config) GetReflection(key string) reflect.Value

GetReflection returns the reflection value for the key. Returns default if missing/invalid.

func (*Config) GetReflectionE

func (c *Config) GetReflectionE(key string) (reflect.Value, error)

GetReflectionE returns the reflect.Value for the key, or error if missing/invalid.

func (*Config) GetReflectionMust

func (c *Config) GetReflectionMust(key string) reflect.Value

GetReflectionMust returns the reflection value for the key. Panics if missing/invalid.

func (*Config) GetString

func (c *Config) GetString(key string) string

GetString returns the string value for the key. Returns default if missing/invalid.

func (*Config) GetStringE

func (c *Config) GetStringE(key string) (string, error)

GetStringE returns the string value for the key, or error if missing/invalid.

func (*Config) GetStringMap

func (c *Config) GetStringMap(key string) map[string]any

GetStringMap returns the stringmap value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapBool

func (c *Config) GetStringMapBool(key string) map[string]bool

GetStringMapBool returns the stringmapbool value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapBoolE

func (c *Config) GetStringMapBoolE(key string) (map[string]bool, error)

GetStringMapBoolE returns the map[string]bool value for the key, or error if missing/invalid.

func (*Config) GetStringMapBoolMust

func (c *Config) GetStringMapBoolMust(key string) map[string]bool

GetStringMapBoolMust returns the stringmapbool value for the key. Panics if missing/invalid.

func (*Config) GetStringMapE

func (c *Config) GetStringMapE(key string) (map[string]any, error)

GetStringMapE returns the map[string]any value for the key, or error if missing/invalid.

func (*Config) GetStringMapInt

func (c *Config) GetStringMapInt(key string) map[string]int

GetStringMapInt returns the stringmapint value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapInt64

func (c *Config) GetStringMapInt64(key string) map[string]int64

GetStringMapInt64 returns the stringmapint64 value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapInt64E

func (c *Config) GetStringMapInt64E(key string) (map[string]int64, error)

GetStringMapInt64E returns the map[string]int64 value for the key, or error if missing/invalid.

func (*Config) GetStringMapInt64Must

func (c *Config) GetStringMapInt64Must(key string) map[string]int64

GetStringMapInt64Must returns the stringmapint64 value for the key. Panics if missing/invalid.

func (*Config) GetStringMapIntE

func (c *Config) GetStringMapIntE(key string) (map[string]int, error)

GetStringMapIntE returns the map[string]any value for the key, or error if missing/invalid.

func (*Config) GetStringMapIntMust

func (c *Config) GetStringMapIntMust(key string) map[string]int

GetStringMapIntMust returns the stringmapint value for the key. Panics if missing/invalid.

func (*Config) GetStringMapMust

func (c *Config) GetStringMapMust(key string) map[string]any

GetStringMapMust returns the stringmap value for the key. Panics if missing/invalid.

func (*Config) GetStringMapString

func (c *Config) GetStringMapString(key string) map[string]string

GetStringMapString returns the stringmapstring value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapStringE

func (c *Config) GetStringMapStringE(key string) (map[string]string, error)

GetStringMapStringE returns the map[string]string value for the key, or error if missing/invalid.

func (*Config) GetStringMapStringMust

func (c *Config) GetStringMapStringMust(key string) map[string]string

GetStringMapStringMust returns the stringmapstring value for the key. Panics if missing/invalid.

func (*Config) GetStringMapStringSlice

func (c *Config) GetStringMapStringSlice(key string) map[string][]string

GetStringMapStringSlice returns the stringmapstringslice value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapStringSliceE

func (c *Config) GetStringMapStringSliceE(key string) (map[string][]string, error)

GetStringMapStringSliceE returns the map[string][]string value for the key, or error if missing/invalid.

func (*Config) GetStringMapStringSliceMust

func (c *Config) GetStringMapStringSliceMust(key string) map[string][]string

GetStringMapStringSliceMust returns the stringmapstringslice value for the key. Panics if missing/invalid.

func (*Config) GetStringMapUint

func (c *Config) GetStringMapUint(key string) map[string]uint

GetStringMapUint returns the stringmapuint value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapUint64

func (c *Config) GetStringMapUint64(key string) map[string]uint64

GetStringMapUint64 returns the stringmapuint64 value for the key. Returns default if missing/invalid.

func (*Config) GetStringMapUint64E

func (c *Config) GetStringMapUint64E(key string) (map[string]uint64, error)

GetStringMapUint64E returns the map[string]uint64 value for the key, or error if missing/invalid.

func (*Config) GetStringMapUint64Must

func (c *Config) GetStringMapUint64Must(key string) map[string]uint64

GetStringMapUint64Must returns the stringmapuint64 value for the key. Panics if missing/invalid.

func (*Config) GetStringMapUintE

func (c *Config) GetStringMapUintE(key string) (map[string]uint, error)

GetStringMapUintE returns the map[string]uint value for the key, or error if missing/invalid.

func (*Config) GetStringMapUintMust

func (c *Config) GetStringMapUintMust(key string) map[string]uint

GetStringMapUintMust returns the stringmapuint value for the key. Panics if missing/invalid.

func (*Config) GetStringMust

func (c *Config) GetStringMust(key string) string

GetStringMust returns the string value for the key. Panics if missing/invalid.

func (*Config) GetUint

func (c *Config) GetUint(key string) uint

GetUint returns the uint value for the key. Returns default if missing/invalid.

func (*Config) GetUint64

func (c *Config) GetUint64(key string) uint64

GetUint64 returns the uint64 value for the key. Returns default if missing/invalid.

func (*Config) GetUint64E

func (c *Config) GetUint64E(key string) (uint64, error)

GetUint64E returns the uint64 value for the key, or error if missing/invalid.

func (*Config) GetUint64Must

func (c *Config) GetUint64Must(key string) uint64

GetUint64Must returns the uint64 value for the key. Panics if missing/invalid.

func (*Config) GetUintE

func (c *Config) GetUintE(key string) (uint, error)

GetUintE returns the uint value for the key, or error if missing/invalid.

func (*Config) GetUintMust

func (c *Config) GetUintMust(key string) uint

GetUintMust returns the uint value for the key. Panics if missing/invalid.

func (*Config) Keys

func (c *Config) Keys() []string

Keys returns top-level keys of config

func (*Config) ReadConfig

func (c *Config) ReadConfig() error

ReadConfig loads config files from GetConfigFiles(), following any "include" directives to merge additional files recursively. Later values override earlier ones.

Example:

main.json:
  { "include": ["a.yaml"], "app": { "port": "8080" } }
a.yaml:
  app: { "port": 9000, "env": "prod" }

Result:

app.port = "8080"   // overridden by main.json
app.env  = "prod"   // merged from a.yaml

func (*Config) Set

func (c *Config) Set(key string, v any) error

Set sets a value in the configuration under the specified key.

func (*Config) SetDefault

func (c *Config) SetDefault(key string, v any) error

SetDefault sets a value in the configuration's default values under the specified key.

func (*Config) SetEnvPrefix

func (c *Config) SetEnvPrefix(p string)

SetEnvPrefix sets the environment variable prefix for the configuration. All underscores in the provided string are removed before assignment.

For example, calling SetEnvPrefix("APP_") will set the prefix to "APP".

func (*Config) SetFormat

func (c *Config) SetFormat(f string)

SetFormat sets the default configuration format for this Config instance. The format will be used when no specific encoder/decoder is available for a requested format. Typical formats include "json", "yaml", "toml", etc.

func (*Config) SetLogger

func (c *Config) SetLogger(l *slog.Logger)

SetLogger sets logger

func (*Config) SetPflagSet

func (c *Config) SetPflagSet(fs *pflag.FlagSet)

SetPflagSet adds *pflag.FlagSet

func (*Config) Settings

func (c *Config) Settings() map[string]any

Settings returns the settings map

type DecodeFunc

type DecodeFunc func([]byte) (map[string]any, error)

DecodeFunc decodes raw bytes into a generic map representation of a config file.

func DecoderFromUnmarshal

func DecoderFromUnmarshal(unmarshall UnmarshalFunc) DecodeFunc

DecoderFromUnmarshal wraps a standard UnmarshalFunc (e.g., YAML, JSON) into a DecodeFunc that produces a map[string]any suitable for generic config handling.

type EncodeFunc

type EncodeFunc func(map[string]any) ([]byte, error)

EncodeFunc encodes a generic config map into raw bytes for storage or transmission.

func EncoderFromMarshal

func EncoderFromMarshal(marshall MarshalFunc) EncodeFunc

EncoderFromMarshal wraps a standard MarshalFunc into an EncodeFunc that serializes a map[string]any into raw bytes.

type Key

type Key struct {
	Raw   string
	Parts []KeyPart
}

Key parsed key for easy uses

func KeySplit

func KeySplit(key string) (Key, error)

KeySplit parses a dotted key path into parts, respecting quotes. Example:

"a.b.c" -> {"a", "b", "c"} "a.'b.c'.\"c\"" -> {"a", "b.c", "c"} "'a.b'.c" -> {"a.b", "c"}

func (Key) EnvKey

func (k Key) EnvKey(prefix string) string

EnvKey return list of possible env key

func (Key) LastIndex

func (k Key) LastIndex() int

LastIndex returns last index of key parts. Returns -1 if length is 0.

func (Key) Len

func (k Key) Len() int

Len returns length of the key

type KeyError

type KeyError struct {
	Key string
}

KeyError indicates value for key doesn't exists

func (KeyError) Error

func (ke KeyError) Error() string

type KeyKind

type KeyKind int

KeyKind is...

const (
	// SelfKey is name of the key
	SelfKey KeyKind = iota
	// StringKey is name of the key
	StringKey
	// IndexKey is the index of a slice
	IndexKey
)

type KeyPart

type KeyPart struct {
	Kind      KeyKind
	Interface any
}

KeyPart is a single key

func (KeyPart) Int

func (kp KeyPart) Int() int

Int converts the KeyPart in an int for array index use

func (KeyPart) String

func (kp KeyPart) String() string

type MarshalFunc

type MarshalFunc func(any) ([]byte, error)

MarshalFunc encodes a Go value into raw bytes (like json.Marshal).

type UnmarshalFunc

type UnmarshalFunc func([]byte, any) error

UnmarshalFunc decodes raw bytes into a provided Go value (like json.Unmarshal).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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