Documentation
¶
Overview ¶
Package validator is the runtime that code generated by kanna-validator calls, and what the code inspecting its result works with.
A generated Validate method checks each field with plain Go and collects what broke into Errors: every broken rule rather than the first, each under the path its JSON names spell. The codes and params follow Rails' ActiveModel::Validations (blank, too_long with a count, ...), and Errors encodes as Rails encodes errors.details.
The generator itself is the command in cmd/kanna-validator.
Index ¶
- Variables
- func DecodeJSON(r io.Reader, v interface{ ... }) error
- type Coded
- type DecodeError
- type DecodeReason
- type Error
- func Blank() *Error
- func Confirmation(attribute string) *Error
- func EqualTo[N number](count N) *Error
- func Fail(code string) *Error
- func FailWith(code string, params map[string]any) *Error
- func GreaterThan[N number](count N) *Error
- func GreaterThanOrEqualTo[N number](count N) *Error
- func Inclusion() *Error
- func Invalid() *Error
- func LessThan[N number](count N) *Error
- func LessThanOrEqualTo[N number](count N) *Error
- func OtherThan[N number](count N) *Error
- func TooFew(count int) *Error
- func TooLong(count int) *Error
- func TooMany(count int) *Error
- func TooShort(count int) *Error
- func WrongCount(count int) *Error
- func WrongLength(count int) *Error
- type Errors
- type FieldError
- type Path
- type Segment
- type SegmentKind
Constants ¶
This section is empty.
Variables ¶
var Base = Field("base")
Base is the path of an error that concerns the struct as a whole rather than one of its fields, "base" as in Rails.
Functions ¶
func DecodeJSON ¶
DecodeJSON decodes the JSON value r holds into v, which must be a non-nil pointer, and reports everything wrong with it at once. v has to validate itself, as a struct marked //kanna:validate does, so that a struct left unmarked does not pass unchecked.
A value whose type rejects it with a Coded error, as the value types of kanna-value do, does not stop the decoding: the error is recorded at the value's path and decoding goes on. The rejection may come from any method encoding/json/v2 decodes a type with: UnmarshalJSONFrom, UnmarshalJSON, or UnmarshalText. Then what the Validate method of v finds is added, except at and under the paths decoding rejected. Those values were never set, and checking them would only report the absence of a value that was in fact sent.
The result is the Errors of both, or nil. A request that cannot be read, rather than one that breaks a rule, fails with a *DecodeError instead: JSON that is malformed, holds more than one value, or does not fit the Go types, a rejection that is not Coded or that falls on a map key, and a failure to read r.
Decoding follows encoding/json/v2, which, unlike encoding/json, matches names case-sensitively, rejects duplicate names, and skips unknown names. r is read to its end, so a limit on its size, such as http.MaxBytesReader sets, is the caller's to set.
Types ¶
type Coded ¶
Coded is an error that names the rule a value broke.
The code is stable enough to key a translated message or an API response, and the params carry what such a message needs. *rule.Error from github.com/go-kanna/value/rule is Coded too, which is how a rule held in a value type and one checked by a tag end up in the same Errors without either package importing the other.
type DecodeError ¶ added in v0.0.28
type DecodeError struct {
// Pointer is the JSON pointer to where reading failed, such as
// "/address/zip", or "" for the top-level value.
Pointer jsontext.Pointer `json:"pointer"`
Reason DecodeReason `json:"reason"`
// contains filtered or unexported fields
}
DecodeError is why DecodeJSON could not read a request. It says where and why, but never what was sent or what Go type it was meant for, so that it can answer the request as it is, in its message or encoded as JSON, unlike the error it wraps.
func (*DecodeError) Error ¶ added in v0.0.28
func (e *DecodeError) Error() string
Error says why and where, such as `validator: cannot decode JSON at "/address": value`. The pointer is quoted, as the names in it come from the request.
func (*DecodeError) Unwrap ¶ added in v0.0.28
func (e *DecodeError) Unwrap() error
Unwrap returns the error behind e, which errors.As can tell apart, such as a *json.SemanticError or an *http.MaxBytesError.
type DecodeReason ¶ added in v0.0.28
type DecodeReason string
DecodeReason is what kind of request DecodeJSON could not read.
const ( // ReasonSyntax is JSON that is malformed or cut short. ReasonSyntax DecodeReason = "syntax" // ReasonTrailing is anything after the JSON value but white space. ReasonTrailing DecodeReason = "trailing" // ReasonDuplicateName is a name an object already has. ReasonDuplicateName DecodeReason = "duplicate_name" // ReasonValue is a JSON value, or a name for a map key, that the Go type // does not take: one of the wrong kind, such as a string for a struct, a // number out of range, a string that is no time, or one a type rejects // without a Coded error. ReasonValue DecodeReason = "value" // ReasonRead is a failure to read the request, such as one // http.MaxBytesReader cuts off. ReasonRead DecodeReason = "read" )
The reasons DecodeJSON could not read a request.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is the Coded error the built-in rules report. A validate hook reports its own through Fail and FailWith.
Error is used through a pointer: its params make it incomparable, so comparing two Error values with == would panic, while pointers compare by identity.
func Confirmation ¶
Confirmation reports a value that does not match the field it confirms, whose JSON name is attribute.
func EqualTo ¶
func EqualTo[N number](count N) *Error
EqualTo reports a number other than count. N is any integer or floating-point type, or one defined on it.
func FailWith ¶
FailWith is Fail with params for the message. params is copied, so the caller may go on to change it.
func GreaterThan ¶
func GreaterThan[N number](count N) *Error
GreaterThan reports a number that is not greater than count. N is any integer or floating-point type, or one defined on it.
func GreaterThanOrEqualTo ¶
func GreaterThanOrEqualTo[N number](count N) *Error
GreaterThanOrEqualTo reports a number below count. N is any integer or floating-point type, or one defined on it.
func LessThan ¶
func LessThan[N number](count N) *Error
LessThan reports a number that is not less than count. N is any integer or floating-point type, or one defined on it.
func LessThanOrEqualTo ¶
func LessThanOrEqualTo[N number](count N) *Error
LessThanOrEqualTo reports a number above count. N is any integer or floating-point type, or one defined on it.
func OtherThan ¶
func OtherThan[N number](count N) *Error
OtherThan reports a number equal to count. N is any integer or floating-point type, or one defined on it.
func WrongCount ¶ added in v0.0.28
WrongCount reports a slice or a map of other than count elements.
func WrongLength ¶
WrongLength reports a string of other than count characters.
type Errors ¶
type Errors []FieldError
Errors collects every rule broken while validating a value, in the order they were found. A generated Validate method returns it through Err.
func (*Errors) Add ¶
Add records err as broken at p. A nil err is ignored, so that the result of a rule can be passed as it is. Errors, such as what another Validate returns, move under p, as Nest moves them.
func (Errors) Err ¶
Err returns e, or nil when nothing broke. Returning e itself would hand the caller a non-nil error holding nothing.
func (Errors) Error ¶
Error lists every broken rule, such as "validator: name: blank; tags[2]: too_long (count=20)".
func (Errors) MarshalJSON ¶
MarshalJSON is MarshalJSONTo for an encoder that knows only json.Marshaler. encoding/json itself calls MarshalJSONTo.
func (Errors) MarshalJSONTo ¶
MarshalJSONTo encodes e as Rails encodes errors.details: an object keyed by field, in the order the fields first broke, each holding a list with the code under "error" and the params beside it, in key order.
{"name":[{"error":"blank"}],"tags[2]":[{"error":"too_long","count":20}]}
A param named "error" would hide the code, so it is left out.
func (*Errors) Nest ¶
Nest records what validating the value at p reported. The errors of Errors move under p ("address" and "zip" make "address.zip"), and the zero Path leaves them where they are, as for an embedded struct. Any other error is recorded at p itself, or at Base for the zero Path. A nil err is ignored.
type FieldError ¶
type FieldError struct {
// Field is the path to the field, spelled with JSON names, such as
// "address.zip" or "tags[2]"; or "base".
Field string
// Segments are the steps of the path, which tell a field from a map key:
// "notes.first" may be either.
Segments []Segment
// Err is the rule's error. It is usually Coded; one that is not reports the
// code "invalid", Rails' catch-all.
Err error
}
FieldError is a broken rule together with the field it broke on.
func (FieldError) Code ¶
func (e FieldError) Code() string
Code returns the code of Err, or "invalid" when Err carries none.
func (FieldError) Error ¶
func (e FieldError) Error() string
Error formats the field followed by the code and params, such as "tags[2]: too_long (count=20)". An error that is not Coded contributes its own text instead.
func (FieldError) FieldNames ¶ added in v0.0.28
func (e FieldError) FieldNames() []string
FieldNames returns the names of the field segments of the path, in order, leaving out map keys and indexes: "items[2].notes.first" gives items and notes when first is a key. It returns nil without Segments. It lets a package such as go-kanna/i18n name the field without importing validator.
func (FieldError) Params ¶
func (e FieldError) Params() map[string]any
Params returns the params of Err, or nil when Err carries none.
func (FieldError) Path ¶
func (e FieldError) Path() string
Path returns Field. It is the method go-kanna/i18n renders an error by, together with Code and Params, to name the field in a message.
type Path ¶ added in v0.0.28
type Path struct {
// contains filtered or unexported fields
}
Path is where in a value an error is: the fields, map keys, and slice indexes leading to it. Field starts one, and its methods go on with it. Its zero value is the value itself.
func Field ¶ added in v0.0.28
Field returns the path through the fields named name and then names, each by its JSON name, such as Field("address", "zip") for "address.zip". The methods of Path go on with it.
func (Path) Field ¶ added in v0.0.28
Field returns the path through the fields named name and then names below p, such as Field("items").Index(2).Field("sku") for "items[2].sku".
func (Path) Index ¶ added in v0.0.28
Index returns the path to element i of the slice at p, such as "tags[2]".
func (Path) Key ¶ added in v0.0.28
Key returns the path to the value under key in the map at p, such as "labels.primary": a map is a JSON object, so its keys are spelled as the names of an object are, as DecodeJSON reports them. key is a key of the map, of a type a map can have keys of.
type Segment ¶ added in v0.0.28
type Segment struct {
Kind SegmentKind
// Name is the field's JSON name, or the key spelled as encoding/json names
// it in an object, for a FieldSegment and a KeySegment.
Name string
// Index is the element's index, for an IndexSegment.
Index int
}
Segment is one step of a path.
type SegmentKind ¶ added in v0.0.28
type SegmentKind int
SegmentKind is what a segment of a path steps into.
const ( // FieldSegment is a field of a struct. FieldSegment SegmentKind = iota + 1 // KeySegment is the value under a key of a map. KeySegment // IndexSegment is an element of a slice or an array. IndexSegment )
The kinds of segments.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
kanna-validator
command
Command kanna-validator generates Validate methods from the validate tags of structs marked //kanna:validate.
|
Command kanna-validator generates Validate methods from the validate tags of structs marked //kanna:validate. |
|
Package impl is what the code kanna-validator generates runs on: the order it walks a map in.
|
Package impl is what the code kanna-validator generates runs on: the order it walks a map in. |
|
internal
|
|
|
gen
Package gen generates Validate methods from the validate tags of structs marked //kanna:validate.
|
Package gen generates Validate methods from the validate tags of structs marked //kanna:validate. |