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 ¶
- Variables
- func IsBindError(err error) bool
- func IsValidationError(err error) bool
- type BindError
- type Binder
- type FieldMapper
- func (m *FieldMapper) FlatMapToStruct(data map[string]any, prefix string, target any) error
- func (m *FieldMapper) MapToStruct(data map[string]any, target any) error
- func (m *FieldMapper) StructToFlatMap(v any, prefix string) (map[string]any, error)
- func (m *FieldMapper) StructToMap(v any) (map[string]any, error)
- type Option
- type StructConfig
- type TagValidator
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( ErrValidationFailed = errors.New("config: validation failed") ErrBindingFailed = errors.New("config: binding failed") )
Sentinel errors for validation
Functions ¶
func IsValidationError ¶
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.
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 (*Binder) Bind ¶
func (b *Binder) Bind() StructConfig
Bind returns a StructConfig with struct binding capabilities.
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 ¶
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 ¶
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 WithCustomTagValidation ¶
WithCustomTagValidation enables struct tag validation with a custom tag name.
func WithFieldTag ¶
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