API Reference

Complete reference for confkit's public Go API.

func

Load

func Load[T any](sources ...Source) (T, error)

Loads configuration from the provided sources and returns a fully typed, validated config or an error.

ParameterTypeDescription
sources...SourceVariable number of Source instances to load from

Returns

  • T — The configuration struct (zero value on error)
  • error — An *ErrorReport if validation fails

Example

type Config struct {
    Port int    `env:"PORT" default:"8080"`
}

cfg, err := confkit.Load[Config](
    confkit.FromEnv(),
)
if err != nil {
    log.Fatal(confkit.Explain(err))
}
func

LoadWithOptions

func LoadWithOptions[T any](options ...Option) (T, error)

Advanced loading with functional options for custom validators, middleware, and interpolation configuration.

Options

OptionDescription
WithSource(source Source)Add a configuration source
WithValidator(name, fn)Register a custom per-field validator
WithModelValidator[T](fn)Register a cross-field validator
WithMiddleware(fn)Add a value transformation middleware
WithInterpolationMaxDepth(n)Set interpolation recursion limit
WithAuditLogger(fn)Receive a log of every field's resolved value and source
WithLoadHook(fn)Receive success/duration/errCount after every load

Example

cfg, err := confkit.LoadWithOptions[Config](
    confkit.WithSource(confkit.FromYAML("config.yaml")),
    confkit.WithSource(confkit.FromEnv()),
    // Cross-field validation
    confkit.WithModelValidator(func(cfg *Config) error {
        if cfg.TLSEnabled && cfg.CertPath == "" {
            return fmt.Errorf("cert_path required when tls_enabled is true")
        }
        return nil
    },
    // Audit trail
    confkit.WithAuditLogger(func(entries []confkit.AuditEntry) {
        for _, e := range entries {
            log.Printf("field=%s source=%s value=%s", e.Field, e.Source, e.Value)
        }
    },
)
func

LoadWithWatcher

func LoadWithWatcher[T any](filePath string, sources ...Source) (T, *ConfigWatcher, error)

Loads configuration and returns a watcher for hot-reloading when files change.

ParameterTypeDescription
filePathstringPath to watch for changes
sources...SourceConfiguration sources

Returns

  • T — Initial configuration struct
  • *ConfigWatcher — Watcher instance for subscribing to changes
  • error — Load or watcher creation error

Example

cfg, watcher, err := confkit.LoadWithWatcher[Config](
    "config.yaml",
    confkit.FromYAML("config.yaml"),
    confkit.FromEnv(),
)

// Subscribe to changes
go func() {
    for newCfg := range watcher.Changes() {
        log.Printf("Config reloaded: %+v\n", newCfg)
    }
}()
func

Explain

func Explain(err error) string

Formats an error report into a human-readable, colorized error message suitable for logging or stdout.

Example

cfg, err := confkit.Load[Config](confkit.FromEnv())
if err != nil {
    fmt.Println(confkit.Explain(err))
    // Invalid configuration:
    // 
    //   PORT
    //     error: must be between 1 and 65535
    //     got: 99999
    //     source: env (PORT)
}

Sources

source

FromEnv

func FromEnv() Source

Loads configuration from environment variables. Field names are uppercased and matched to env tags.

type Config struct {
    DatabaseURL string `env:"DATABASE_URL" validate:"required"`
    Port        int    `env:"PORT" default:"8080"`
}

// Reads from $DATABASE_URL and $PORT
cfg, _ := confkit.Load[Config](confkit.FromEnv())
source

FromYAML

func FromYAML(path string) Source

Loads configuration from a YAML file.

// config.yaml:
// databaseURL: postgres://localhost/db
// port: 3000

cfg, _ := confkit.Load[Config](confkit.FromYAML("config.yaml"))
source

FromJSON

func FromJSON(path string) Source

Loads configuration from a JSON file.

cfg, _ := confkit.Load[Config](confkit.FromJSON("config.json"))
source

FromTOML

func FromTOML(path string) Source

Loads configuration from a TOML file.

cfg, _ := confkit.Load[Config](confkit.FromTOML("config.toml"))
source

FromYAMLFiles / FromJSONFiles / FromTOMLFiles

func FromYAMLFiles(paths ...string) Source
func FromJSONFiles(paths ...string) Source
func FromTOMLFiles(paths ...string) Source

Merges multiple files of the same format into a single source. First file to provide a value wins; later files fill in only unset fields. Nested maps are deep-merged.

cfg, _ := confkit.Load[Config](
    confkit.FromYAMLFiles("base.yaml", "production.yaml", "local.yaml"),
    confkit.FromEnv(),
)
source

FromFlags

func FromFlags() Source

Loads configuration from command-line flags. Field names are converted to kebab-case flags.

Supported flag formats

  • --key=value — long flag with = separator
  • --key value — long flag with space separator
  • -k value — short flag with space separator
  • -k=value — short flag with = separator
  • --flag — boolean flag (sets field to "true")
// Run: go run main.go --database-url=... --port=3000 --verbose
cfg, _ := confkit.Load[Config](confkit.FromFlags())

Cloud & Enterprise Sources

cloud

FromK8sConfigMap

import "github.com/MimoJanra/confkit/k8s"

func FromK8sConfigMap(namespace, configMapName string) confkit.Source

Loads configuration from a Kubernetes ConfigMap.

cfg, err := confkit.Load[Config](
    k8s.FromK8sConfigMap("default", "app-config"),
)
cloud

FromAWSSSM

import "github.com/MimoJanra/confkit/aws"

func FromAWSSSM(parameterPath string) confkit.Source

Loads configuration from AWS Systems Manager Parameter Store.

cfg, err := confkit.Load[Config](
    aws.FromAWSSSM("/prod/app/config"),
)
cloud

FromVault

import "github.com/MimoJanra/confkit/vault"

func FromVault(addr, secretPath string) confkit.Source

Loads secrets from HashiCorp Vault KV store.

cfg, err := confkit.Load[Config](
    vault.FromVault("https://vault.example.com", "/secret/app"),
)
cloud

FromConsul

import "github.com/MimoJanra/confkit/consul"

func FromConsul(addr string) confkit.Source

Loads configuration from Consul KV store.

cfg, err := confkit.Load[Config](
    consul.FromConsul("consul.example.com:8500"),
)
cloud

FromEtcd

import "github.com/MimoJanra/confkit/etcd"

func FromEtcd(endpoints []string) confkit.Source

Loads configuration from etcd v3 key-value store.

cfg, err := confkit.Load[Config](
    etcd.FromEtcd([]string{"etcd1.example.com:2379"},),
)
cloud

FromAWSSecretsManager

import "github.com/MimoJanra/confkit/aws"

func FromAWSSecretsManager(secretName string) confkit.Source

Loads secrets from AWS Secrets Manager with automatic rotation support.

cfg, err := confkit.Load[Config](
    aws.FromAWSSecretsManager("prod/app-secrets"),
)

Observability

pkg

confkit/prometheus

import "github.com/MimoJanra/confkit/prometheus"

m := prometheus.NewMetrics(prometheus.DefaultRegisterer)

cfg, err := confkit.LoadWithOptions[Config](
    confkit.WithSource(confkit.FromEnv()),
    m.Hook(),
)

Metrics registered

  • confkit_loads_total{"status":"success|error"} — counter
  • confkit_load_duration_seconds — histogram
  • confkit_errors_total{"kind":"validation"} — counter
pkg

confkit/otel

import "github.com/MimoJanra/confkit/otel"

cfg, err := otel.Load[Config](ctx, tracer,
    confkit.FromEnv(),
    confkit.FromYAML("config.yaml"),
)
// Creates span "confkit.Load" with attributes:
// confkit.sources, confkit.success

Types

type

ErrorReport

The error type returned by Load(). Implements the error interface.

type ErrorReport struct {
    Errors []FieldError
}

func (e *ErrorReport) Error() string
func (e *ErrorReport) AddError(err FieldError)
func (e *ErrorReport) IsEmpty() bool
func (e *ErrorReport) Unwrap() []error
func (e *ErrorReport) Format() string
type

FieldError

Represents a single field validation or loading error.

type FieldError struct {
    Path    string
    Source  string
    Kind    ErrorKind  // parse | validation | io
    Rule    string
    Message string
    Value   string
    Secret  bool
}
type

Source

Interface for configuration sources. Implement to create custom sources.

type Source interface {
    Name() string
    Lookup(ctx context.Context, field *FieldInfo) (any, bool, error)
}

Custom Source Example

type MySource struct{}

func (s *MySource) Name() string { return "custom" }

func (s *MySource) Lookup(ctx context.Context, field *FieldInfo) (any, bool, error) {
    return "value", true, nil
}

cfg, _ := confkit.Load[Config](&MySource{})

Struct Tags & Validation

Struct Tags

Configuration is driven by struct tags. All tags are optional.

TagPurposeExample
envEnvironment variable nameenv:"DATABASE_URL"
yaml / jsonFile field nameyaml:"database_url"
defaultDefault value if not founddefault:"localhost"
validateValidation rules (comma-separated)validate:"required,min=1,max=65535"
secretMark as sensitive — auto-redactedsecret:"true"
descHelp text / descriptiondesc:"Database connection URL"
flagCLI long flag nameflag:"database-url"
shortCLI short flag (single char)short:"d"
envPrefixPrefix for nested struct env varsenvPrefix:"DB_"

Complete Example

type DatabaseConfig struct {
    Host     string `env:"DB_HOST" default:"localhost"`
    Port     int    `env:"DB_PORT" validate:"min=1,max=65535" default:"5432"`
    Username string `env:"DB_USER" validate:"required"`
    Password string `env:"DB_PASSWORD" validate:"required" secret:"true"`
}

type Config struct {
    Database DatabaseConfig
    LogLevel string `env:"LOG_LEVEL" validate:"oneof=debug,info,warn,error" default:"info"`
}

Validation Rules

All built-in validation rules — no external library required.

Presence & Range

RuleDescription
requiredField must be present and non-zero
min=NMinimum value (int/float) or minimum length (string)
max=NMaximum value (int/float) or maximum length (string)
oneof=a,b,cMust be one of the listed values
notemptyMust not be blank (non-whitespace)

Format Validators

RuleDescription
emailValid email address
urlValid URL (any scheme)
http_urlValid HTTP or HTTPS URL
ipValid IPv4 or IPv6 address
ipv4Valid IPv4 address
ipv6Valid IPv6 address
uuidValid UUID (v1–v5)
hostnameValid hostname per RFC 1123
portValid port number 1–65535 (int or string)
regex=patternMust match the regular expression

String Validators

RuleDescription
len=NMust be exactly N characters (Unicode-aware)
contains=strMust contain the substring
startswith=strMust start with the prefix
endswith=strMust end with the suffix
alphaLetters only
alphanumLetters and digits only
numericDigits only
lowercaseMust be all lowercase
uppercaseMust be all uppercase

Example

type Config struct {
    Port        int    `env:"PORT"    validate:"required,port"`
    AdminEmail  string `env:"EMAIL"   validate:"required,email"`
    APIKey      string `env:"API_KEY" validate:"required,len=32" secret:"true"`
    Environment string `env:"ENV"     validate:"oneof=dev,staging,prod"`
    ServiceURL  string `env:"SVC_URL" validate:"http_url"`
    ServiceID   string `env:"SVC_ID"  validate:"uuid"`
}