konform

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 18 Imported by: 0

README

konform logo

Go Reference CI Release Coverage Go Report Card License

konform

konform is a schema-first configuration library for Go. Define typed config structs once, then load from files and environment with defaults, validation, strict checks, and load reporting.

Why konform

Configuration in Go often ends up split across multiple libraries and custom glue code. That usually leads to duplicated mapping logic, unclear precedence, and inconsistent validation.

konform keeps this explicit and predictable by using struct tags as the schema and a small loading API.

Konform vs Viper and Koanf

konform is not trying to be the most feature-rich configuration framework. It is optimized for strict, typed, schema-first loading with explainable outcomes.

Capability Konform Viper Koanf
Schema-first from Go structs Strong default Possible, but often extra wiring Possible, often parser/provider composition
Strict unknown-key handling with suggestions Built-in (ModeWarn / ModeError / ModeOff) Usually custom validation needed Usually custom validation needed
Built-in load explainability report Built-in (LoadReport) Not a core built-in concept Not a core built-in concept
Strict mapping conflict checks (key/env) Built-in (Strict) Usually manual Usually manual
Secret masking in report Built-in (secret tag) Usually manual Usually manual
Dynamic/reload-heavy provider ecosystem Limited by design Strong Strong

Use konform when you want predictable, typed config behavior and explicit failure modes. Use Viper/Koanf when you need broader provider ecosystems, dynamic config workflows, or more runtime flexibility.

Key features

  • Schema-first configuration from typed Go structs
  • Multiple sources: environment variables, .env files, YAML/JSON/TOML files, YAML/JSON/TOML bytes
  • Environment prefixing for env and .env lookups via konform.WithEnvPrefix(...)
  • Defaults via struct tags
  • Custom decoding via encoding.TextUnmarshaler (including pointer fields)
  • Validation rules (required, min, max, len, minlen, maxlen, regex, oneof, nonzero, url, email)
  • Custom validators via konform.WithCustomValidator(...)
  • Strict mode (konform.Strict()) for unknown structured keys and mapping conflicts
  • Unknown-key handling modes: konform.ModeWarn, konform.ModeError, konform.ModeOff
  • Load report with field values and value sources
  • Secret masking in reports using secret:"true"
  • Nested struct support
  • Deterministic precedence through explicit source order
  • Clear, human-friendly validation and decode errors

Installation

go get github.com/nzhussup/konform

Quick start

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/nzhussup/konform"
)

type Config struct {
	Server struct {
		Host string `key:"server.host" default:"127.0.0.1"`
		Port int    `key:"server.port" default:"8080" env:"PORT"`
	}
	Database struct {
		URL string `key:"database.url" env:"DATABASE_URL" validate:"required" secret:"true"`
	}
	Log struct {
		Level string `key:"log.level" default:"info"`
	}
}

func main() {
	var cfg Config

	report, err := konform.Load(
		&cfg,
		konform.FromYAMLFile("config.yaml"),
		konform.FromDotEnvFile(".env"),
		konform.FromEnv(),
		konform.WithEnvPrefix("APP_"),
		konform.WithUnknownKeySuggestionMode(konform.ModeWarn),
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", cfg)
	report.Print(os.Stdout)
}

Precedence

konform applies values in this order:

defaults < file < .env < env

This behavior is controlled by the order of options passed to Load. If multiple sources set the same field, the later source wins.

Strict mode

Use konform.Strict() to enforce:

  • unknown keys in structured sources are errors
  • decode/type mismatches are errors
  • invalid mapped env values are errors
  • duplicate/conflicting key or env mappings are errors
  • unrelated environment variables are ignored

Tags

  • key: path used for YAML/JSON lookup (defaults to struct field path when omitted)
  • env: environment variable name
  • default: default value used when the field is zero-valued before source loading
  • validate: validation rules after all sources are applied
  • secret: if truthy (true, 1, yes, on), report value is masked as ***

Unknown key modes

  • konform.ModeWarn (default): print warning, continue load
  • konform.ModeError: return decode error
  • konform.ModeOff: ignore unknown keys

Set mode with:

konform.WithUnknownKeySuggestionMode(konform.ModeError)

Load report

Load returns (*LoadReport, error).

Report entries include:

  • resolved path
  • final value (masked for secret fields)
  • source (default, file path, env:VAR_NAME, or zero)

Print formatted report:

report.Print(os.Stdout)

Examples

See runnable examples in examples/:

  • examples/basic
  • examples/env
  • examples/yaml
  • examples/json
  • examples/toml
  • examples/report

Documentation

More docs:

Philosophy

  • Minimal magic
  • Explicit behavior
  • Idiomatic Go APIs and errors

Stability

Konform follows semantic versioning and a documented compatibility policy. See Stability and Support Policy.

License

MIT. See LICENSE.

Documentation

Index

Constants

View Source
const Version = "v0.4.0"

Version is the current module version. It is updated by the release workflow from the release tag.

Variables

View Source
var (
	// ErrInvalidTarget indicates target passed to Load is invalid.
	ErrInvalidTarget = errs.InvalidTarget
	// ErrInvalidSchema indicates schema configuration or tags are invalid.
	ErrInvalidSchema = errs.InvalidSchema
	// ErrDecode indicates source decode or type conversion failure.
	ErrDecode = errs.Decode
	// ErrValidation indicates one or more validation rules failed.
	ErrValidation = errs.Validation
)

Functions

This section is empty.

Types

type CustomValidatorFunc added in v0.4.0

type CustomValidatorFunc func(value any, ruleValue string) error

CustomValidatorFunc validates a field value using the optional rule value from the validate tag (for example: validate:"myrule=arg").

Return nil when valid, or a non-nil error to report a validation failure.

type FieldError

type FieldError struct {
	Path string
	Err  error
}

FieldError represents an error for a specific configuration field path.

func (FieldError) Error

func (e FieldError) Error() string

type LoadReport added in v0.3.1

type LoadReport struct {
	Entries []ReportEntry
}

LoadReport describes resolved values and their sources after loading.

func Load

func Load(target any, opts ...Option) (*LoadReport, error)

Load builds a schema from target and applies defaults, configured sources, and validations in order.

target must be a non-nil pointer to a struct.

func (*LoadReport) Print added in v0.3.1

func (r *LoadReport) Print(w io.Writer)

Print writes a tabular report to w.

type Option

type Option func(*loadOptions) error

Option configures Load behavior.

func FromDotEnvFile added in v0.4.0

func FromDotEnvFile(path string) Option

FromDotEnvFile loads values from a .env file using field env tags.

func FromEnv

func FromEnv() Option

FromEnv loads values from process environment variables using field env tags.

func FromJSONBytes added in v0.4.0

func FromJSONBytes(data []byte) Option

FromJSONBytes loads values from JSON bytes.

func FromJSONFile

func FromJSONFile(path string) Option

FromJSONFile loads values from a JSON file.

func FromTOMLBytes added in v0.4.0

func FromTOMLBytes(data []byte) Option

FromTOMLBytes loads values from TOML bytes.

func FromTOMLFile added in v0.2.0

func FromTOMLFile(path string) Option

FromTOMLFile loads values from a TOML file.

func FromYAMLBytes added in v0.4.0

func FromYAMLBytes(data []byte) Option

FromYAMLBytes loads values from YAML bytes.

func FromYAMLFile

func FromYAMLFile(path string) Option

FromYAMLFile loads values from a YAML file.

func Strict added in v0.3.1

func Strict() Option

Strict enables strict schema loading and mapping checks.

func WithCustomValidator added in v0.4.0

func WithCustomValidator(name string, fn CustomValidatorFunc) Option

WithCustomValidator registers a custom validator by rule name. The rule can then be used in validate tags (for example: validate:"myrule=arg").

func WithEnvPrefix added in v0.4.0

func WithEnvPrefix(prefix string) Option

WithEnvPrefix prepends prefix to all env-tag lookups for env and .env sources.

func WithUnknownKeySuggestionMode added in v0.3.0

func WithUnknownKeySuggestionMode(mode UnknownKeySuggestionMode) Option

WithUnknownKeySuggestionMode sets handling mode for unknown structured keys.

type ReportEntry added in v0.3.1

type ReportEntry struct {
	Path   string
	Value  string
	Source string
}

ReportEntry is a single resolved field in a LoadReport.

type UnknownKeySuggestionMode added in v0.3.0

type UnknownKeySuggestionMode = common.UnknownKeySuggestionMode

UnknownKeySuggestionMode controls how unknown structured keys are handled.

const (
	// ModeWarn prints a warning for unknown keys and continues.
	ModeWarn UnknownKeySuggestionMode = common.UnknownKeySuggestionWarn
	// ModeError returns a decode error for unknown keys.
	ModeError UnknownKeySuggestionMode = common.UnknownKeySuggestionError
	// ModeOff ignores unknown keys.
	ModeOff UnknownKeySuggestionMode = common.UnknownKeySuggestionOff
)

type ValidationError

type ValidationError struct {
	Fields []FieldError
}

ValidationError contains all field-level validation failures.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Directories

Path Synopsis
examples
basic command
env command
json command
report command
toml command
validation command
yaml command
internal

Jump to

Keyboard shortcuts

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