Documentation
¶
Overview ¶
Package validate provides struct-tag-driven JSON request decoding and validation. It replaces the per-handler if/else chains that every fleet service currently hand-rolls.
Supported struct tags (all on the `validate` key):
required field must be non-zero min=N string min length / number minimum value max=N string max length / number maximum value email basic email format check url basic URL format check (must start with http:// or https://) oneof=a|b|c value must equal one of the pipe-separated options pattern=<regexp> the whole string must match the regexp (it is wrapped in ^(?:...)$)
Usage:
type CreateReq struct {
Name string `json:"name" validate:"required,max=64"`
Email string `json:"email" validate:"required,email"`
Role string `json:"role" validate:"oneof=admin|user|viewer"`
}
var req CreateReq
if err := validate.Bind(r, &req); err != nil {
// err is *errors.Error with Status=400 and Code="bad_request.validation"
http.Error(w, err.Error(), err.HTTPStatus())
return
}
Bind decodes JSON, then validates. Validation errors are aggregated into a single *errors.Error so the handler sees all failures at once.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Bind ¶
func Bind(r *http.Request, dst any) *fleetErrors.Error
Bind decodes the JSON body of r into dst (which must be a non-nil pointer to a struct), then validates all `validate` struct tags. Returns a *fleetErrors.Error with Status=400 on any decode or validation failure. Returns nil on success.
func BindBytes ¶
func BindBytes(b []byte, dst any) *fleetErrors.Error
BindBytes decodes b (raw JSON) into dst, then validates.
Example ¶
BindBytes decodes JSON and checks the validate tags in one step; every failure comes back as a single 400 error.
package main
import (
"fmt"
"github.com/baditaflorin/go-common/validate"
)
type createReq struct {
Name string `json:"name" validate:"required,max=8"`
Role string `json:"role" validate:"oneof=admin|user"`
}
// BindBytes decodes JSON and checks the validate tags in one step; every
// failure comes back as a single 400 error.
func main() {
var ok createReq
fmt.Println(validate.BindBytes([]byte(`{"name":"ada","role":"admin"}`), &ok) == nil)
var bad createReq
err := validate.BindBytes([]byte(`{"name":"","role":"root"}`), &bad)
fmt.Println(err.HTTPStatus(), err.Code)
}
Output: true 400 bad_request.validation
func Struct ¶
func Struct(dst any) *fleetErrors.Error
Struct validates the `validate` struct tags on dst without decoding. Returns a *fleetErrors.Error aggregating all field failures.
Types ¶
This section is empty.