Documentation
¶
Index ¶
- Variables
- func Downcast[A any, B any](v B) (A, error)
- func Must[T any](v T, err error) T
- type Codec
- func Bool() Codec[bool]
- func Bytes() Codec[[]byte]
- func Date() Codec[time.Time]
- func Float64() Codec[float64]
- func Int() Codec[int]
- func Int64() Codec[int64]
- func MapCodecSafe[A, B any](c Codec[A], to func(A) B, from func(B) (A, error)) Codec[B]
- func MapCodecValidated[A, B any](ca Codec[A], cb Codec[B], to func(A) (B, error), from func(B) (A, error)) Codec[B]
- func Nullable[T any](inner Codec[T]) Codec[*T]
- func Refine[T any](c Codec[T], constraints ...Constraint[T]) Codec[T]
- func SliceOf[T any](elem Codec[T]) Codec[[]T]
- func String() Codec[string]
- func StringMap[V any](value Codec[V]) Codec[map[string]V]
- func Struct[T any](fields ...fieldCodec[T]) Codec[T]
- func TaggedUnion[T any](tag string, variants map[string]Codec[T], ...) Codec[T]
- func Time() Codec[time.Time]
- type Constraint
- type ConstraintError
- type ElementError
- type Field
- type KeyError
- type TypeMismatchError
- type UnknownVariantError
- type ValidationError
- type ValidationErrors
- type VariantError
Constants ¶
This section is empty.
Variables ¶
var ErrMissingField = errors.New("missing required field")
ErrMissingField is returned when a required struct field is absent from the input. Use errors.Is to check for this sentinel.
Functions ¶
func Downcast ¶
Downcast attempts to cast a value of type B to type A. Useful for tagged unions where variants share a common interface.
func Must ¶
Must returns v if err is nil, and panics with err otherwise.
It follows the same convention as template.Must and regexp.MustCompile: use it to wrap any (T, error) call where failure is a programming error, not a recoverable runtime condition.
Typical uses include package-level validated constants and test data setup:
var defaultEmail = codex.Must(emailCodec.New(Email("noreply@example.com")))
got := codex.Must(emailCodec.Decode("user@example.com"))
Types ¶
type Codec ¶
type Codec[T any] struct { Encode func(T) (any, error) Decode func(any) (T, error) Schema schema.Schema }
Codec encodes values of type T to an intermediate representation, decodes that representation back to T, and describes the schema.
func Bytes ¶
Bytes returns a Codec for []byte using base64 standard encoding. Encoded values are strings; schema format is "byte".
func Date ¶
Date returns a Codec for time.Time using date-only encoding (2006-01-02). The time component is ignored on encode. Decoded values have time set to midnight UTC. Schema format is "date".
func MapCodecSafe ¶
MapCodecSafe creates a new Codec[B] from Codec[A] using two mapping functions. from is the encode direction and must always succeed. to is the decode direction and may fail.
func MapCodecValidated ¶
func MapCodecValidated[A, B any]( ca Codec[A], cb Codec[B], to func(A) (B, error), from func(B) (A, error), ) Codec[B]
MapCodecValidated creates a Codec[B] from Codec[A] and Codec[B] using two fallible mapping functions.
Both directions may return an error. After mapping to B in the decode direction, cb.Validate is called to enforce all Refine constraints defined on cb. The resulting codec carries cb's schema.
Use MapCodecValidated when the mapping itself can fail and the target type B has its own validation constraints expressed via Refine. For a simpler case where only the encode direction can fail and no post-mapping validation is needed, use MapCodecSafe.
func Nullable ¶
Nullable wraps inner to produce a Codec[*T] that treats nil as JSON null. The generated schema inherits all fields from inner and sets Nullable to true.
func Refine ¶
func Refine[T any](c Codec[T], constraints ...Constraint[T]) Codec[T]
Refine applies multiple constraints to a codec.
func StringMap ¶
StringMap returns a Codec for map[string]V, using value to encode/decode each entry. The generated schema is an object with additionalProperties set to the value codec's schema.
func TaggedUnion ¶
func TaggedUnion[T any]( tag string, variants map[string]Codec[T], selectVariant func(T) (string, error), ) Codec[T]
TaggedUnion builds a Codec[T] for a discriminated union identified by a tag field.
func Time ¶
Time returns a Codec for time.Time using RFC 3339 (ISO 8601) encoding. Values are normalized to UTC on encode. Schema format is "date-time".
func (Codec[T]) New ¶
New validates v and returns it if all constraints pass.
It is a single-call smart constructor: call New to create a validated instance of T without separating construction from validation. On success it returns (v, nil); on failure it returns (zero, err) where err contains the first constraint that failed.
New delegates to Validate internally, so the same Refine constraints and encode-direction checks apply.
func (Codec[T]) Refine ¶
func (c Codec[T]) Refine(cons Constraint[T]) Codec[T]
Refine wraps the codec with a single constraint checked during Decode. If cons.Schema is non-nil, it is applied to the codec's schema.
func (Codec[T]) Validate ¶
It encodes v to the intermediate representation and decodes it back, running all Refine constraints defined on the codec. This reuses the exact same constraint logic as Decode — builtin constraints (via validate.*) and any self-defined Constraint[T] values work without modification.
The encode direction is intentionally unconstrained (you constructed the value yourself). Call Validate explicitly when you want bidirectional enforcement.
func (Codec[T]) WithDescription ¶
WithDescription returns a new Codec with Schema.Description set to desc.
type Constraint ¶
type Constraint[T any] struct { Name string Check func(T) bool Message func(T) string Schema func(schema.Schema) schema.Schema // optional: mutates schema when Refine is applied }
Constraint is a named validation predicate applied during decoding.
The optional Schema field annotates the codec's schema when the constraint is applied via Refine. Set it to propagate constraint metadata (e.g. minimum length, numeric bounds) into the schema for renderers such as render/openapi. Leaving Schema nil is a no-op and keeps all existing constraints unchanged.
type ConstraintError ¶
type ConstraintError struct {
Name string // constraint identifier
Message string // human-readable failure description
}
ConstraintError is returned when a Refine constraint check fails during Decode. Name identifies the constraint (e.g. "minLen(3)"); Message describes the failure.
func (ConstraintError) Error ¶
func (e ConstraintError) Error() string
func (ConstraintError) LogValue ¶
func (e ConstraintError) LogValue() slog.Value
LogValue implements slog.LogValuer for structured logging.
type ElementError ¶
ElementError wraps a decode error at a specific slice index.
func (ElementError) Error ¶
func (e ElementError) Error() string
func (ElementError) LogValue ¶
func (e ElementError) LogValue() slog.Value
LogValue implements slog.LogValuer for structured logging.
func (ElementError) Unwrap ¶
func (e ElementError) Unwrap() error
type Field ¶
type Field[T any, F any] struct { Name string Codec Codec[F] Get func(T) F Set func(*T, F) Required bool }
Field describes a single struct field and its codec.
type KeyError ¶
KeyError wraps a decode error at a specific map key.
type TypeMismatchError ¶
type TypeMismatchError struct {
Expected string // e.g. "object", "array", "string"
Got string // e.g. "int", "bool"
}
TypeMismatchError is returned when a codec receives a value of an unexpected type. Expected names the required type; Got names the actual type received.
func (TypeMismatchError) Error ¶
func (e TypeMismatchError) Error() string
func (TypeMismatchError) LogValue ¶
func (e TypeMismatchError) LogValue() slog.Value
LogValue implements slog.LogValuer for structured logging.
type UnknownVariantError ¶
type UnknownVariantError struct {
Tag string // discriminator field name
Variant string // unrecognised tag value
}
UnknownVariantError is returned when a tagged union receives a tag value that does not match any registered variant. Tag is the discriminator field name; Variant is the unrecognised tag value.
func (UnknownVariantError) Error ¶
func (e UnknownVariantError) Error() string
func (UnknownVariantError) LogValue ¶
func (e UnknownVariantError) LogValue() slog.Value
LogValue implements slog.LogValuer for structured logging.
type ValidationError ¶
type ValidationError struct {
Field string // name of the field that failed
Err error // underlying constraint or missing-field error
}
ValidationError is a single field-level validation failure returned from struct Decode.
func (ValidationError) Error ¶
func (e ValidationError) Error() string
func (ValidationError) LogValue ¶
func (e ValidationError) LogValue() slog.Value
LogValue implements slog.LogValuer for structured logging.
func (ValidationError) Unwrap ¶
func (e ValidationError) Unwrap() error
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors is a collection of field-level validation errors. It implements the error interface; callers can use errors.As to extract it. Unwrap returns the individual errors as a []error slice for errors.Is/As traversal.
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
func (ValidationErrors) LogValue ¶
func (ve ValidationErrors) LogValue() slog.Value
LogValue implements slog.LogValuer for structured logging. Each field name is the slog key; its value is the underlying error (which invokes LogValue on types like ConstraintError, preserving nested structure).
func (ValidationErrors) Unwrap ¶
func (ve ValidationErrors) Unwrap() []error
Unwrap returns the individual ValidationError values as a []error slice, enabling errors.Is and errors.As to traverse the full list.
type VariantError ¶
type VariantError struct {
Tag string // discriminator field name
Variant string // matched variant value
Err error // underlying encode or decode failure
}
VariantError is returned when a known tagged-union variant fails to encode or decode. Tag is the discriminator field name; Variant is the matched variant value. Err is always non-nil; use UnknownVariantError for unrecognised tag values.
func (VariantError) Error ¶
func (e VariantError) Error() string
func (VariantError) LogValue ¶
func (e VariantError) LogValue() slog.Value
LogValue implements slog.LogValuer for structured logging.
func (VariantError) Unwrap ¶
func (e VariantError) Unwrap() error