validate

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Validate

func Validate[T any](opts ...Option) middleware.MiddlewareFunc

Validate creates a middleware that validates the request body as the specified type T

The middleware performs the following processes: 1. If type T implements RequestUnmarshaler interface, it uses UnmarshalFromRequest method 2. Otherwise, it automatically detects if the request body is JSON or XML based on the first non-whitespace character:

  • '{' or '[' for JSON (unmarshals using json.Unmarshal)
  • '<' for XML (unmarshals using xml.Unmarshal)
  • Other characters default to JSON

3. Performs validation of type T using validator/v10 (tags must be set) 4. Returns a 400 Bad Request error if validation fails 5. If validation succeeds, sets the value of type T in the context

The key to set in the context defaults to CtxKey{}, but can be changed with the WithCtxKey option The response in case of an error can be customized with the WithResponse option

Examples: ```

type User struct {
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"gte=0,lte=130"`
}

// Validates the request body as User type and sets the validated User object in the context Validate[User]()

// Use a custom context key type UserKey string Validate[User](WithCtxKey(UserKey("user")))

// Set a custom error response Validate[User](WithResponse("application/json", `{"error": "Validation failed"}`)) ```

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config is the configuration for the Validate middleware

type CtxKey

type CtxKey struct{}

CtxKey is the default key type for the validated request value stored in the context

type Option

type Option func(*Config)

Option is a function type that modifies the Validate middleware settings

func WithCtxKey

func WithCtxKey(ctxKey any) Option

WithCtxKey specifies the key for the validated request value to be set in the context

func WithResponse

func WithResponse(contentType string, body string) Option

WithResponse customizes the Content-Type header and body of the response when a validation error occurs

type RequestUnmarshaler

type RequestUnmarshaler interface {
	UnmarshalRequest([]byte) error
}

RequestUnmarshaler is an interface that allows custom unmarshaling from request body

type Validator added in v0.2.0

type Validator interface {
	Validate() error
}

Validator is an interface that allows custom validation logic

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL