API Reference
Complete reference for confkit's public Go API.
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.
| Parameter | Type | Description |
|---|---|---|
sources | ...Source | Variable number of Source instances to load from |
Returns
T— The configuration struct (zero value on error)error— An*ErrorReportif 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)) }
LoadWithOptions
func LoadWithOptions[T any](options ...Option) (T, error)
Advanced loading with functional options for custom validators, middleware, and interpolation configuration.
Options
| Option | Description |
|---|---|
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) } }, )
LoadWithWatcher
func LoadWithWatcher[T any](filePath string, sources ...Source) (T, *ConfigWatcher, error)
Loads configuration and returns a watcher for hot-reloading when files change.
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path to watch for changes |
sources | ...Source | Configuration sources |
Returns
T— Initial configuration struct*ConfigWatcher— Watcher instance for subscribing to changeserror— 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) } }()
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
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())
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"))
FromJSON
func FromJSON(path string) Source
Loads configuration from a JSON file.
cfg, _ := confkit.Load[Config](confkit.FromJSON("config.json"))
FromTOML
func FromTOML(path string) Source
Loads configuration from a TOML file.
cfg, _ := confkit.Load[Config](confkit.FromTOML("config.toml"))
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(), )
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
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"), )
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"), )
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"), )
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"), )
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"},), )
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
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"}— counterconfkit_load_duration_seconds— histogramconfkit_errors_total{"kind":"validation"}— counter
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
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
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 }
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
Validation Rules
All built-in validation rules — no external library required.
Presence & Range
| Rule | Description |
|---|---|
required | Field must be present and non-zero |
min=N | Minimum value (int/float) or minimum length (string) |
max=N | Maximum value (int/float) or maximum length (string) |
oneof=a,b,c | Must be one of the listed values |
notempty | Must not be blank (non-whitespace) |
Format Validators
| Rule | Description |
|---|---|
email | Valid email address |
url | Valid URL (any scheme) |
http_url | Valid HTTP or HTTPS URL |
ip | Valid IPv4 or IPv6 address |
ipv4 | Valid IPv4 address |
ipv6 | Valid IPv6 address |
uuid | Valid UUID (v1–v5) |
hostname | Valid hostname per RFC 1123 |
port | Valid port number 1–65535 (int or string) |
regex=pattern | Must match the regular expression |
String Validators
| Rule | Description |
|---|---|
len=N | Must be exactly N characters (Unicode-aware) |
contains=str | Must contain the substring |
startswith=str | Must start with the prefix |
endswith=str | Must end with the suffix |
alpha | Letters only |
alphanum | Letters and digits only |
numeric | Digits only |
lowercase | Must be all lowercase |
uppercase | Must 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"` }