Documentation
¶
Overview ¶
Package validate checks handler input after binding. A Schema does the checking; Pipe and Use plug it into the pipeline:
app, err := dygo.Create(ctx, AppModule, validate.Use(validate.Methods()))
Methods needs no dependency: it calls Validate(ctx) on input types that have one. The sub-module validate/playground adapts go-playground/validator for `validate:"required,email"` struct tags.
A failed check is a *ValidationError, written as a 400 that lists every failing field in the same shape as binding errors:
{"statusCode":400,"error":"Bad Request","message":"validation failed",
"details":[{"source":"body","name":"email","reason":"must be a valid email"}]}
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Responses ¶
func Responses(s Schema) dygo.Interceptor
Responses returns an interceptor that validates handler results with s. A result that fails is a bug on the server, so it becomes a 500 and the details are logged, not sent.
Types ¶
type Errors ¶
type Errors []FieldError
Errors collects field errors inside a Validate method:
func (in *CreateIn) Validate(ctx context.Context) error {
var v validate.Errors
if in.Body.Name == "" {
v.Add("body", "name", "is required")
}
return v.Err()
}
type FieldError ¶
type FieldError = dygo.FieldError
FieldError is one failing field: source ("body", "query", "path", ...), name, the value when it is safe to echo, and the reason.
type Option ¶
type Option func(*config)
Option configures Pipe and Use.
func WithErrorShape ¶
func WithErrorShape(fn func([]FieldError) any) Option
WithErrorShape changes what is sent as "details" for a validation error, for example a list of messages:
validate.WithErrorShape(func(fs []validate.FieldError) any {
msgs := make([]string, len(fs))
for i, f := range fs {
msgs[i] = f.Name + " " + f.Reason
}
return msgs
})
type Schema ¶
Schema validates a value, usually a pointer to a handler's input struct. It returns nil, a *ValidationError, or another error (which is passed on as is).
func Methods ¶
func Methods() Schema
Methods returns a Schema that calls Validate(ctx) on the value and on each of its direct fields (such as the Body field) that implement Validatable. An embedded struct's Validate is promoted, so it runs once, as the value's. Errors from several fields are merged into one *ValidationError.
type SchemaFunc ¶
SchemaFunc is a function used as a Schema.
type Validatable ¶
Validatable is implemented by input types that check themselves.
type ValidationError ¶
type ValidationError struct {
Fields []FieldError
// contains filtered or unexported fields
}
ValidationError lists every failing field. It maps to a 400.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) HTTPError ¶
func (e *ValidationError) HTTPError() *errs.HTTPError
HTTPError returns the 400 response, implementing errs.Converter.