bind

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package bind provides struct binding and validation for the config library. It wraps the Config interface without modifying it, adding struct binding capabilities.

Package bind provides struct binding with custom tag support.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrValidationFailed = errors.New("config: validation failed")
	ErrBindingFailed    = errors.New("config: binding failed")
)

Sentinel errors for validation

Functions

func IsBindError

func IsBindError(err error) bool

IsBindError returns true if err is a BindError.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError returns true if err is a ValidationError.

Types

type BindError

type BindError struct {
	Key string // Config key
	Op  string // Operation (marshal, unmarshal)
	Err error  // Underlying error
}

BindError represents a binding/unmarshaling failure.

func (*BindError) Error

func (e *BindError) Error() string

func (*BindError) Unwrap

func (e *BindError) Unwrap() error

type Binder

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

Binder wraps Config with struct binding capabilities. It does NOT modify the Config interface - purely additive.

func New

func New(cfg config.Config, opts ...Option) *Binder

New creates a new Binder wrapping the given Config.

func (*Binder) Bind

func (b *Binder) Bind() StructConfig

Bind returns a StructConfig with struct binding capabilities.

func (*Binder) Config

func (b *Binder) Config() config.Config

Config returns the underlying Config interface.

func (*Binder) Validate

func (b *Binder) Validate(value any) error

Validate validates a struct using tag-based validation. Returns nil if validation passes or no validator is configured.

type FieldMapper

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

FieldMapper handles struct-to-map and map-to-struct conversions with support for custom struct tags and field ignoring.

func NewFieldMapper

func NewFieldMapper(tagName string) *FieldMapper

NewFieldMapper creates a new mapper with the specified tag name. If tagName is empty, defaults to "json".

func (*FieldMapper) FlatMapToStruct

func (m *FieldMapper) FlatMapToStruct(data map[string]any, prefix string, target any) error

FlatMapToStruct converts a flat map with path-based keys to a struct. Keys are expected to use "/" as separator for nested fields.

func (*FieldMapper) MapToStruct

func (m *FieldMapper) MapToStruct(data map[string]any, target any) error

MapToStruct converts a map to a struct using the configured tag name. Fields tagged with `tagname:"-"` are ignored.

func (*FieldMapper) StructToFlatMap

func (m *FieldMapper) StructToFlatMap(v any, prefix string) (map[string]any, error)

StructToFlatMap converts a struct to a flat map with path-based keys. Nested structs are flattened using "/" as separator. Example: {Database: {Host: "localhost"}} -> {"database/host": "localhost"}

func (*FieldMapper) StructToMap

func (m *FieldMapper) StructToMap(v any) (map[string]any, error)

StructToMap converts a struct to a map using the configured tag name. Fields tagged with `tagname:"-"` are ignored.

type Option

type Option func(*Binder)

Option configures the Binder.

func WithCodec

func WithCodec(c codec.Codec) Option

WithCodec sets the codec for encoding/decoding values.

func WithCustomTagValidation

func WithCustomTagValidation(tagName string) Option

WithCustomTagValidation enables struct tag validation with a custom tag name.

func WithFieldTag

func WithFieldTag(tagName string) Option

WithFieldTag sets the struct tag name used for field mapping. Default is "json". Common alternatives: "yaml", "config", "mapstructure".

Supported tag options:

  • "-": Field is ignored during both marshalling and unmarshalling
  • "omitempty": Field is omitted if it has a zero value
  • "nonrecursive": Nested struct is stored as a single value (not flattened)

Example:

binder := bind.New(cfg, bind.WithFieldTag("config"))

type DatabaseConfig struct {
    Host     string      `config:"host"`
    Port     int         `config:"port"`
    Password string      `config:"-"`            // ignored
    Creds    Credentials `config:"creds,nonrecursive"` // stored as single JSON
}

func WithTagValidation

func WithTagValidation() Option

WithTagValidation enables struct tag validation. Tags are specified using the "validate" tag name.

Supported tags:

  • required: field must not be zero value
  • min=N: minimum value (for numbers) or length (for strings/slices)
  • max=N: maximum value (for numbers) or length (for strings/slices)
  • enum=a|b|c: value must be one of the listed options
  • pattern=regex: value must match the regex pattern

Example:

type Config struct {
    Host string `validate:"required"`
    Port int    `validate:"required,min=1,max=65535"`
}

type StructConfig

type StructConfig interface {
	config.Config // Embed original interface

	// GetStruct reads all keys with the given prefix and maps them to the target struct.
	// For example, GetStruct(ctx, "database", &cfg) reads database/host, database/port, etc.
	// and maps them to the corresponding struct fields.
	// Validates the result if validators are configured.
	GetStruct(ctx context.Context, key string, target any) error

	// GetStructDigest is like GetStruct but also returns an FNV-64a digest
	// computed from the raw config values. Two calls that return the same
	// digest populated the target with identical data. This allows callers
	// to detect changes without comparing structs via reflection.
	GetStructDigest(ctx context.Context, key string, target any) (uint64, error)

	// SetStruct flattens the struct into individual keys and stores them.
	// For example, SetStruct(ctx, "database", cfg) where cfg has Host and Port fields
	// will set database/host and database/port keys.
	// Validates before storing if validators are configured.
	SetStruct(ctx context.Context, key string, value any, opts ...config.SetOption) error
}

StructConfig extends Config with struct binding methods. This interface embeds config.Config so it can be used as a drop-in replacement.

type TagValidator

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

TagValidator validates structs using struct tags.

func NewTagValidator

func NewTagValidator(tagName string) *TagValidator

NewTagValidator creates a new tag-based validator. tagName is the struct tag to look for (e.g., "validate").

func (*TagValidator) Validate

func (v *TagValidator) Validate(value any) error

Validate validates a struct using its tags.

type ValidationError

type ValidationError struct {
	Key    string // Config key
	Field  string // Struct field (if applicable)
	Value  any    // The value that failed validation
	Reason string // Human-readable reason
	Err    error  // Underlying error
}

ValidationError represents a validation failure.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Jump to

Keyboard shortcuts

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