Documentation
¶
Overview ¶
Package z parses untrusted input into typed Go values with Zod-inspired schemas, and checks outgoing values against the same contracts.
var Login = z.Struct[LoginInput](z.Shape{
"email": z.String().Trim().Email(),
"password": z.String().Min(12),
})
in, err := Login.Parse(map[string]any{"email": "a@b.co", "password": "..."})
Schemas are immutable values: every modifier returns a new schema, so a schema can be shared by any number of goroutines.
Index ¶
- Constants
- func FieldError(path, message string) error
- func ParseJSON[T any](r io.Reader, s Schema[T]) (T, error)
- type AnySchema
- type BoolSchema
- func (s BoolSchema) Check(v bool) error
- func (s BoolSchema) Default(v bool) BoolSchema
- func (s BoolSchema) Describe(text string) BoolSchema
- func (BoolSchema) GoType() reflect.Type
- func (s BoolSchema) Message(code, message string) BoolSchema
- func (s BoolSchema) Nullable() BoolSchema
- func (s BoolSchema) Optional() BoolSchema
- func (s BoolSchema) Parse(in any) (bool, error)
- func (s BoolSchema) Refine(fn func(bool) error) BoolSchema
- type CustomSchema
- type EnumSchema
- func (s EnumSchema[T]) Check(v T) error
- func (s EnumSchema[T]) Default(v T) EnumSchema[T]
- func (s EnumSchema[T]) Describe(text string) EnumSchema[T]
- func (EnumSchema[T]) GoType() reflect.Type
- func (s EnumSchema[T]) Message(code, message string) EnumSchema[T]
- func (s EnumSchema[T]) Nullable() EnumSchema[T]
- func (s EnumSchema[T]) Optional() EnumSchema[T]
- func (s EnumSchema[T]) Parse(in any) (T, error)
- func (s EnumSchema[T]) Refine(fn func(T) error) EnumSchema[T]
- func (s EnumSchema[T]) Values() []T
- type Issue
- type Issues
- type MapSchema
- type Number
- type NumberSchema
- func (s NumberSchema[N]) Check(v N) error
- func (s NumberSchema[N]) Default(v N) NumberSchema[N]
- func (s NumberSchema[N]) Describe(text string) NumberSchema[N]
- func (NumberSchema[N]) GoType() reflect.Type
- func (s NumberSchema[N]) Max(n N) NumberSchema[N]
- func (s NumberSchema[N]) Message(code, message string) NumberSchema[N]
- func (s NumberSchema[N]) Min(n N) NumberSchema[N]
- func (s NumberSchema[N]) MultipleOf(m N) NumberSchema[N]
- func (s NumberSchema[N]) NonNegative() NumberSchema[N]
- func (s NumberSchema[N]) Nullable() NumberSchema[N]
- func (s NumberSchema[N]) Optional() NumberSchema[N]
- func (s NumberSchema[N]) Parse(in any) (N, error)
- func (s NumberSchema[N]) Positive() NumberSchema[N]
- func (s NumberSchema[N]) Refine(fn func(N) error) NumberSchema[N]
- func (s NumberSchema[N]) Transform(fn func(N) N) NumberSchema[N]
- type Schema
- type Shape
- type SliceSchema
- func (s SliceSchema) Default(v any) SliceSchema
- func (s SliceSchema) Describe(text string) SliceSchema
- func (s SliceSchema) GoType() reflect.Type
- func (s SliceSchema) Len(n int) SliceSchema
- func (s SliceSchema) Max(n int) SliceSchema
- func (s SliceSchema) Message(code, message string) SliceSchema
- func (s SliceSchema) Min(n int) SliceSchema
- func (s SliceSchema) NonEmpty() SliceSchema
- func (s SliceSchema) Nullable() SliceSchema
- func (s SliceSchema) Optional() SliceSchema
- func (s SliceSchema) Parse(in any) (any, error)
- func (s SliceSchema) Unique() SliceSchema
- type StringSchema
- func (s StringSchema) Alpha() StringSchema
- func (s StringSchema) Alphanum() StringSchema
- func (s StringSchema) Check(v string) error
- func (s StringSchema) Default(v string) StringSchema
- func (s StringSchema) Describe(text string) StringSchema
- func (s StringSchema) Email() StringSchema
- func (s StringSchema) EndsWith(suffix string) StringSchema
- func (StringSchema) GoType() reflect.Type
- func (s StringSchema) Includes(substring string) StringSchema
- func (s StringSchema) Len(n int) StringSchema
- func (s StringSchema) Max(n int) StringSchema
- func (s StringSchema) Message(code, message string) StringSchema
- func (s StringSchema) Min(n int) StringSchema
- func (s StringSchema) NonEmpty() StringSchema
- func (s StringSchema) Nullable() StringSchema
- func (s StringSchema) Numeric() StringSchema
- func (s StringSchema) OneOf(values ...string) StringSchema
- func (s StringSchema) Optional() StringSchema
- func (s StringSchema) Parse(in any) (string, error)
- func (s StringSchema) Refine(fn func(string) error) StringSchema
- func (s StringSchema) Regex(re *regexp.Regexp) StringSchema
- func (s StringSchema) StartsWith(prefix string) StringSchema
- func (s StringSchema) ToLower() StringSchema
- func (s StringSchema) ToUpper() StringSchema
- func (s StringSchema) Transform(fn func(string) string) StringSchema
- func (s StringSchema) Trim() StringSchema
- func (s StringSchema) ULID() StringSchema
- func (s StringSchema) URL() StringSchema
- func (s StringSchema) UUID() StringSchema
- type StructSchema
- func (s StructSchema[T]) Check(v T) error
- func (s StructSchema[T]) Describe(text string) StructSchema[T]
- func (StructSchema[T]) GoType() reflect.Type
- func (s StructSchema[T]) Keys() []string
- func (s StructSchema[T]) Nullable() StructSchema[T]
- func (s StructSchema[T]) Optional() StructSchema[T]
- func (s StructSchema[T]) Parse(in any) (T, error)
- func (s StructSchema[T]) Refine(fn func(T) error) StructSchema[T]
- func (s StructSchema[T]) Strict() StructSchema[T]
- func (s StructSchema[T]) Transform(fn func(T) T) StructSchema[T]
- type TimeSchema
- func (s TimeSchema) After(t time.Time) TimeSchema
- func (s TimeSchema) Before(t time.Time) TimeSchema
- func (s TimeSchema) Check(v time.Time) error
- func (s TimeSchema) Default(v time.Time) TimeSchema
- func (s TimeSchema) Describe(text string) TimeSchema
- func (TimeSchema) GoType() reflect.Type
- func (s TimeSchema) Layouts(layouts ...string) TimeSchema
- func (s TimeSchema) Message(code, message string) TimeSchema
- func (s TimeSchema) Nullable() TimeSchema
- func (s TimeSchema) Optional() TimeSchema
- func (s TimeSchema) Parse(in any) (time.Time, error)
- func (s TimeSchema) Refine(fn func(time.Time) error) TimeSchema
Constants ¶
const ( CodeRequired = "required" CodeInvalidType = "invalid_type" CodeTooSmall = "too_small" CodeTooBig = "too_big" CodeInvalidString = "invalid_string" CodeInvalidEnum = "invalid_enum" CodeUnrecognizedKeys = "unrecognized_keys" CodeNotMultiple = "not_multiple_of" CodeInvalidDate = "invalid_date" CodeNotUnique = "not_unique" CodeCustom = "custom" )
Issue codes.
Variables ¶
This section is empty.
Functions ¶
func FieldError ¶
FieldError returns an error for Refine callbacks that points at a field path relative to the refined value.
Types ¶
type AnySchema ¶
type AnySchema interface {
// GoType is the Go type the schema produces.
GoType() reflect.Type
// contains filtered or unexported methods
}
AnySchema is implemented by every schema in this package. Composite schemas (Slice, Map, Shape fields) accept any schema through it.
type BoolSchema ¶
type BoolSchema struct {
// contains filtered or unexported fields
}
BoolSchema parses booleans. From forms it accepts true/false, 1/0, on/off and yes/no (an unchecked checkbox is absent, so use Default(false)).
func (BoolSchema) Default ¶
func (s BoolSchema) Default(v bool) BoolSchema
Default uses v when the key is absent.
func (BoolSchema) Describe ¶
func (s BoolSchema) Describe(text string) BoolSchema
Describe sets a description used by schema exports.
func (BoolSchema) Message ¶
func (s BoolSchema) Message(code, message string) BoolSchema
Message overrides the message for an issue code.
func (BoolSchema) Optional ¶
func (s BoolSchema) Optional() BoolSchema
Optional allows the key to be absent.
func (BoolSchema) Refine ¶
func (s BoolSchema) Refine(fn func(bool) error) BoolSchema
Refine adds a custom check.
type CustomSchema ¶
type CustomSchema[T any] struct { // contains filtered or unexported fields }
CustomSchema parses with a user function.
func Custom ¶
func Custom[T any](fn func(in any) (T, error)) CustomSchema[T]
Custom returns a schema whose parsing is done by fn; a returned error becomes an issue with its message.
func (CustomSchema[T]) GoType ¶
func (CustomSchema[T]) GoType() reflect.Type
GoType implements AnySchema.
func (CustomSchema[T]) Optional ¶
func (s CustomSchema[T]) Optional() CustomSchema[T]
Optional allows the key to be absent.
func (CustomSchema[T]) Parse ¶
func (s CustomSchema[T]) Parse(in any) (T, error)
Parse implements Schema.
type EnumSchema ¶
type EnumSchema[T ~string] struct { // contains filtered or unexported fields }
EnumSchema parses one of a fixed set of string values into T.
func Enum ¶
func Enum(values ...string) EnumSchema[string]
Enum returns a schema accepting one of values.
func EnumOf ¶
func EnumOf[T ~string](values ...T) EnumSchema[T]
EnumOf returns an enum schema for a named string type:
type Status string z.EnumOf(StatusDraft, StatusPublished)
func (EnumSchema[T]) Default ¶
func (s EnumSchema[T]) Default(v T) EnumSchema[T]
Default uses v when the key is absent.
func (EnumSchema[T]) Describe ¶
func (s EnumSchema[T]) Describe(text string) EnumSchema[T]
Describe sets a description used by schema exports.
func (EnumSchema[T]) GoType ¶
func (EnumSchema[T]) GoType() reflect.Type
GoType implements AnySchema.
func (EnumSchema[T]) Message ¶
func (s EnumSchema[T]) Message(code, message string) EnumSchema[T]
Message overrides the message for an issue code.
func (EnumSchema[T]) Nullable ¶
func (s EnumSchema[T]) Nullable() EnumSchema[T]
Nullable allows null.
func (EnumSchema[T]) Optional ¶
func (s EnumSchema[T]) Optional() EnumSchema[T]
Optional allows the key to be absent.
func (EnumSchema[T]) Parse ¶
func (s EnumSchema[T]) Parse(in any) (T, error)
Parse implements Schema.
func (EnumSchema[T]) Refine ¶
func (s EnumSchema[T]) Refine(fn func(T) error) EnumSchema[T]
Refine adds a custom check.
func (EnumSchema[T]) Values ¶
func (s EnumSchema[T]) Values() []T
Values returns the allowed values.
type Issue ¶
type Issue struct {
// Path is the dotted path to the value: "author.email", "tags.2".
Path string `json:"path"`
// Code is a stable machine-readable code (see Code* constants).
Code string `json:"code"`
// Message is a human-readable message.
Message string `json:"message"`
// Params holds the values used by the message, e.g. {"min": 3}.
Params map[string]any `json:"params,omitempty"`
}
Issue is one problem found while parsing.
type Issues ¶
type Issues []Issue //nolint:errname // mirrors Zod; reads naturally as a list of issues
Issues is the error returned by Parse. It lists every issue found, not only the first.
type MapSchema ¶
type MapSchema struct {
// contains filtered or unexported fields
}
MapSchema parses objects into map[string]V.
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
Number is the set of numeric types NumberSchema produces.
type NumberSchema ¶
type NumberSchema[N Number] struct { // contains filtered or unexported fields }
NumberSchema parses numbers of type N. It accepts JSON numbers and, from forms and query strings, numeric strings. Integer schemas reject fractions and out-of-range values; float schemas reject NaN and ±Inf.
func NumberOf ¶
func NumberOf[N Number]() NumberSchema[N]
NumberOf returns a schema for any numeric type, e.g. a named type.
func (NumberSchema[N]) Default ¶
func (s NumberSchema[N]) Default(v N) NumberSchema[N]
Default uses v when the key is absent.
func (NumberSchema[N]) Describe ¶
func (s NumberSchema[N]) Describe(text string) NumberSchema[N]
Describe sets a description used by schema exports.
func (NumberSchema[N]) GoType ¶
func (NumberSchema[N]) GoType() reflect.Type
GoType implements AnySchema.
func (NumberSchema[N]) Message ¶
func (s NumberSchema[N]) Message(code, message string) NumberSchema[N]
Message overrides the message for an issue code or detailed key.
func (NumberSchema[N]) MultipleOf ¶
func (s NumberSchema[N]) MultipleOf(m N) NumberSchema[N]
MultipleOf requires v to be a multiple of m.
func (NumberSchema[N]) NonNegative ¶
func (s NumberSchema[N]) NonNegative() NumberSchema[N]
NonNegative requires v >= 0.
func (NumberSchema[N]) Nullable ¶
func (s NumberSchema[N]) Nullable() NumberSchema[N]
Nullable allows null.
func (NumberSchema[N]) Optional ¶
func (s NumberSchema[N]) Optional() NumberSchema[N]
Optional allows the key to be absent (the zero value is used). An empty string from a form counts as absent.
func (NumberSchema[N]) Parse ¶
func (s NumberSchema[N]) Parse(in any) (N, error)
Parse implements Schema.
func (NumberSchema[N]) Positive ¶
func (s NumberSchema[N]) Positive() NumberSchema[N]
Positive requires v > 0.
func (NumberSchema[N]) Refine ¶
func (s NumberSchema[N]) Refine(fn func(N) error) NumberSchema[N]
Refine adds a custom check.
func (NumberSchema[N]) Transform ¶
func (s NumberSchema[N]) Transform(fn func(N) N) NumberSchema[N]
Transform maps the parsed value.
type Schema ¶
type Schema[T any] interface { AnySchema // Parse converts untrusted input (decoded JSON, form maps, strings) // into T. The error is an Issues value listing every problem. Parse(in any) (T, error) // Check validates an already typed value, e.g. data about to be sent // in a response. It uses the same rules as Parse. Check(v T) error }
Schema is a schema that produces values of type T.
type SliceSchema ¶
type SliceSchema struct {
// contains filtered or unexported fields
}
SliceSchema parses arrays into []E where E is the element schema's type. From forms, a single value is accepted as a one-element list.
func Slice ¶
func Slice(elem AnySchema) SliceSchema
Slice returns a schema for a list whose elements match elem.
func (SliceSchema) Default ¶
func (s SliceSchema) Default(v any) SliceSchema
Default uses v (a slice of the element type) when the key is absent.
func (SliceSchema) Describe ¶
func (s SliceSchema) Describe(text string) SliceSchema
Describe sets a description used by schema exports.
func (SliceSchema) Message ¶
func (s SliceSchema) Message(code, message string) SliceSchema
Message overrides the message for an issue code.
func (SliceSchema) Optional ¶
func (s SliceSchema) Optional() SliceSchema
Optional allows the key to be absent (nil slice).
func (SliceSchema) Parse ¶
func (s SliceSchema) Parse(in any) (any, error)
Parse returns the parsed slice as any ([]E).
func (SliceSchema) Unique ¶
func (s SliceSchema) Unique() SliceSchema
Unique rejects duplicate items.
type StringSchema ¶
type StringSchema struct {
// contains filtered or unexported fields
}
StringSchema parses strings. It rejects invalid UTF-8 and control characters other than tab, newline and carriage return (A05).
func String ¶
func String() StringSchema
String returns a schema for string values. The empty string is a valid string; use Min(1) (or the "required" tag) to reject it.
func (StringSchema) Alphanum ¶
func (s StringSchema) Alphanum() StringSchema
Alphanum requires letters and digits only.
func (StringSchema) Default ¶
func (s StringSchema) Default(v string) StringSchema
Default uses v when the key is absent.
func (StringSchema) Describe ¶
func (s StringSchema) Describe(text string) StringSchema
Describe sets a description used by schema exports.
func (StringSchema) Email ¶
func (s StringSchema) Email() StringSchema
Email requires an email address (addr-spec, no display name).
func (StringSchema) EndsWith ¶
func (s StringSchema) EndsWith(suffix string) StringSchema
EndsWith requires suffix.
func (StringSchema) Includes ¶
func (s StringSchema) Includes(substring string) StringSchema
Includes requires substring.
func (StringSchema) Len ¶
func (s StringSchema) Len(n int) StringSchema
Len requires exactly n characters (runes).
func (StringSchema) Max ¶
func (s StringSchema) Max(n int) StringSchema
Max allows at most n characters (runes).
func (StringSchema) Message ¶
func (s StringSchema) Message(code, message string) StringSchema
Message overrides the message for an issue code (or a detailed key such as "too_small.string"). Placeholders: {field}, {min}, {max}, ...
func (StringSchema) Min ¶
func (s StringSchema) Min(n int) StringSchema
Min requires at least n characters (runes).
func (StringSchema) Numeric ¶
func (s StringSchema) Numeric() StringSchema
Numeric requires a decimal number written as a string.
func (StringSchema) OneOf ¶
func (s StringSchema) OneOf(values ...string) StringSchema
OneOf requires one of values (see also Enum).
func (StringSchema) Optional ¶
func (s StringSchema) Optional() StringSchema
Optional allows the key to be absent (the zero value is used).
func (StringSchema) Parse ¶
func (s StringSchema) Parse(in any) (string, error)
Parse implements Schema.
func (StringSchema) Refine ¶
func (s StringSchema) Refine(fn func(string) error) StringSchema
Refine adds a custom check; return FieldError for nested paths.
func (StringSchema) Regex ¶
func (s StringSchema) Regex(re *regexp.Regexp) StringSchema
Regex requires a match of re.
func (StringSchema) StartsWith ¶
func (s StringSchema) StartsWith(prefix string) StringSchema
StartsWith requires prefix.
func (StringSchema) ToLower ¶
func (s StringSchema) ToLower() StringSchema
ToLower lower-cases the value before checks.
func (StringSchema) ToUpper ¶
func (s StringSchema) ToUpper() StringSchema
ToUpper upper-cases the value before checks.
func (StringSchema) Transform ¶
func (s StringSchema) Transform(fn func(string) string) StringSchema
Transform maps the parsed value.
func (StringSchema) Trim ¶
func (s StringSchema) Trim() StringSchema
Trim removes leading and trailing white space before checks.
func (StringSchema) URL ¶
func (s StringSchema) URL() StringSchema
URL requires an absolute http or https URL.
func (StringSchema) UUID ¶
func (s StringSchema) UUID() StringSchema
UUID requires a UUID in canonical form.
type StructSchema ¶
type StructSchema[T any] struct { // contains filtered or unexported fields }
StructSchema parses objects into T.
func For ¶
func For[T any]() StructSchema[T]
For returns the tag-derived schema for T, built once and cached.
func FromTags ¶
func FromTags[T any]() StructSchema[T]
FromTags builds a schema for T from `validate` struct tags, e.g.
type Login struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=12"`
}
Rules: required, min=N, max=N, len=N, email, url, uuid, ulid, alpha, alphanum, numeric, oneof=a b c, regex=PATTERN (last rule), startswith=, endswith=, contains=, positive, unique, dive (rules after it apply to slice elements). Fields without "required" are optional; pointers are optional and nullable; nested structs are parsed recursively. It panics on unknown rules or bad arguments, so mistakes surface at boot.
func Struct ¶
func Struct[T any](shape Shape) StructSchema[T]
Struct returns a schema producing T from an object whose keys are described by shape. Keys map to fields by json, form or query tag, or by field name. It panics when a key has no field or the schema's type does not fit the field, so mistakes surface at boot.
func (StructSchema[T]) Describe ¶
func (s StructSchema[T]) Describe(text string) StructSchema[T]
Describe sets a description used by schema exports.
func (StructSchema[T]) GoType ¶
func (StructSchema[T]) GoType() reflect.Type
GoType implements AnySchema.
func (StructSchema[T]) Keys ¶
func (s StructSchema[T]) Keys() []string
Keys returns the shape keys in order.
func (StructSchema[T]) Nullable ¶
func (s StructSchema[T]) Nullable() StructSchema[T]
Nullable allows null.
func (StructSchema[T]) Optional ¶
func (s StructSchema[T]) Optional() StructSchema[T]
Optional allows the key to be absent.
func (StructSchema[T]) Parse ¶
func (s StructSchema[T]) Parse(in any) (T, error)
Parse implements Schema.
func (StructSchema[T]) Refine ¶
func (s StructSchema[T]) Refine(fn func(T) error) StructSchema[T]
Refine adds a cross-field check; return FieldError to point at a field.
func (StructSchema[T]) Strict ¶
func (s StructSchema[T]) Strict() StructSchema[T]
Strict rejects keys that are not in the shape.
func (StructSchema[T]) Transform ¶
func (s StructSchema[T]) Transform(fn func(T) T) StructSchema[T]
Transform maps the parsed value.
type TimeSchema ¶
type TimeSchema struct {
// contains filtered or unexported fields
}
TimeSchema parses times from RFC 3339 strings (plus the HTML datetime-local and date formats by default).
func (TimeSchema) After ¶
func (s TimeSchema) After(t time.Time) TimeSchema
After requires the time to be strictly after t.
func (TimeSchema) Before ¶
func (s TimeSchema) Before(t time.Time) TimeSchema
Before requires the time to be strictly before t.
func (TimeSchema) Default ¶
func (s TimeSchema) Default(v time.Time) TimeSchema
Default uses v when the key is absent.
func (TimeSchema) Describe ¶
func (s TimeSchema) Describe(text string) TimeSchema
Describe sets a description used by schema exports.
func (TimeSchema) Layouts ¶
func (s TimeSchema) Layouts(layouts ...string) TimeSchema
Layouts replaces the accepted layouts.
func (TimeSchema) Message ¶
func (s TimeSchema) Message(code, message string) TimeSchema
Message overrides the message for an issue code.
func (TimeSchema) Optional ¶
func (s TimeSchema) Optional() TimeSchema
Optional allows the key to be absent.
func (TimeSchema) Parse ¶
func (s TimeSchema) Parse(in any) (time.Time, error)
Parse implements Schema.
func (TimeSchema) Refine ¶
func (s TimeSchema) Refine(fn func(time.Time) error) TimeSchema
Refine adds a custom check.