validate

package
v0.0.85 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2025 License: BSD-3-Clause Imports: 8 Imported by: 2

README

Validate

URLSearchParamsInto

URLSearchParamsInto is a method of the Validate struct that parses URL query parameters from an HTTP request into a destination struct and validates the resulting struct.

Signature
func (v Validate) URLSearchParamsInto(r *http.Request, destStructPtr any) error
Parameters
  • r *http.Request: The HTTP request containing the URL query parameters to be parsed.
  • destStructPtr any: A pointer to the destination struct where the parsed values will be stored.
Return Value

Returns an error if parsing or validation fails, otherwise returns nil.

Usage Examples
Basic Types
type BasicForm struct {
    Name    string  `json:"name"`
    Age     int     `json:"age"`
    Height  float64 `json:"height"`
    IsAdmin bool    `json:"isAdmin"`
}

// URL: /?name=John&age=30&height=1.75&isAdmin=true
func handleBasicForm(r *http.Request) {
    var form BasicForm
    err := v.URLSearchParamsInto(r, &form)
    if err != nil {
        // Handle error
    }
    // form is now populated with:
    // {Name: "John", Age: 30, Height: 1.75, IsAdmin: true}
}
Slices
type SliceForm struct {
    Tags []string `json:"tags"`
    Scores []int  `json:"scores"`
}

// URL: /?tags=go&tags=programming&scores=85&scores=90&scores=95
func handleSliceForm(r *http.Request) {
    var form SliceForm
    err := v.URLSearchParamsInto(r, &form)
    if err != nil {
        // Handle error
    }
    // form is now populated with:
    // {Tags: ["go", "programming"], Scores: [85, 90, 95]}
}
Nested Structs
type Address struct {
    Street string `json:"street"`
    City   string `json:"city"`
    ZIP    string `json:"zip"`
}

type UserForm struct {
    Name    string  `json:"name"`
    Address Address `json:"address"`
}

// URL: /?name=Alice&address.street=123 Main St&address.city=Anytown&address.zip=12345
func handleNestedForm(r *http.Request) {
    var form UserForm
    err := v.URLSearchParamsInto(r, &form)
    if err != nil {
        // Handle error
    }
    // form is now populated with:
    // {Name: "Alice", Address: {Street: "123 Main St", City: "Anytown", ZIP: "12345"}}
}
Maps
type MapForm struct {
    Attributes map[string]string `json:"attributes"`
}

// URL: /?attributes.color=blue&attributes.size=large&attributes.material=cotton
func handleMapForm(r *http.Request) {
    var form MapForm
    err := v.URLSearchParamsInto(r, &form)
    if err != nil {
        // Handle error
    }
    // form is now populated with:
    // {Attributes: {"color": "blue", "size": "large", "material": "cotton"}}
}
Pointer Fields
type PointerForm struct {
    Name     *string  `json:"name"`
    Age      *int     `json:"age"`
    IsActive *bool    `json:"isActive"`
}

// URL: /?name=Bob&age=25&isActive=true
func handlePointerForm(r *http.Request) {
    var form PointerForm
    err := v.URLSearchParamsInto(r, &form)
    if err != nil {
        // Handle error
    }
    // form is now populated with pointers to values:
    // {Name: &"Bob", Age: &25, IsActive: &true}
}
Mixed Types
type ComplexForm struct {
    Name       string            `json:"name"`
    Age        int               `json:"age"`
    Hobbies    []string          `json:"hobbies"`
    Address    Address           `json:"address"`
    Attributes map[string]string `json:"attributes"`
    IsStudent  *bool             `json:"isStudent"`
}

// URL: /?name=Eve&age=22&hobbies=reading&hobbies=painting&address.city=Springfield&address.zip=67890&attributes.department=Art&attributes.year=2nd&isStudent=true
func handleComplexForm(r *http.Request) {
    var form ComplexForm
    err := v.URLSearchParamsInto(r, &form)
    if err != nil {
        // Handle error
    }
    // form is now populated with a mix of types
}
Notes
  • Empty values for non-pointer fields are ignored and leave the field unchanged.
  • Pointer fields are set to nil for empty values in URL parameters.
  • Multiple values with the same key are collected into slices.
  • Nested struct fields are accessed using dot notation in URL parameters.
  • Map keys use dot notation after the map field name, but don't support further nesting.
  • The function uses json tags to map URL parameter names to struct fields, falling back to field names if no tag is present.
  • Validation errors will be returned if the struct has validation tags and the parsed data doesn't meet the criteria.

Documentation

Overview

Package validate provides a simple way to validate and parse data from HTTP requests.

Index

Constants

View Source
const ValidationErrorPrefix = "validation error: "

Variables

This section is empty.

Functions

func IsValidationError added in v0.0.42

func IsValidationError(err error) bool

IsValidationError returns true if the error is a validation error.

Types

type Validate

type Validate struct {
	Instance *validator.Validate
}

Validate is a wrapper around the go-playground/validator package. It provides methods for validating and parsing data from HTTP requests.

func New added in v0.0.49

func New() *Validate

New creates a new Validate instance.

func (Validate) JSONBodyInto added in v0.0.34

func (v Validate) JSONBodyInto(body io.ReadCloser, destStructPtr any) error

JSONBodyInto decodes the JSON body of an HTTP request into a struct and validates it.

func (Validate) JSONBytesInto added in v0.0.34

func (v Validate) JSONBytesInto(data []byte, destStructPtr any) error

JSONBytesInto decodes a byte slice containing JSON data into a struct and validates it.

func (Validate) JSONStrInto added in v0.0.34

func (v Validate) JSONStrInto(data string, destStructPtr any) error

JSONStrInto decodes a string containing JSON data into a struct and validates it.

func (Validate) URLSearchParamsInto added in v0.0.34

func (v Validate) URLSearchParamsInto(r *http.Request, destStructPtr any) error

URLSearchParamsInto parses the URL parameters of an HTTP request into a struct and validates it.

func (Validate) UnmarshalFromBytes deprecated added in v0.0.17

func (v Validate) UnmarshalFromBytes(data []byte, destStructPtr any) error

Deprecated: UnmarshalFromBytes is deprecated. Use JSONBytesInto instead.

func (Validate) UnmarshalFromRequest deprecated

func (v Validate) UnmarshalFromRequest(r *http.Request, destStructPtr any) error

Deprecated: UnmarshalFromRequest is deprecated. Use `v.JSONBodyInto(r.Body, dest)` instead.

func (Validate) UnmarshalFromResponse deprecated added in v0.0.9

func (v Validate) UnmarshalFromResponse(r *http.Response, destStructPtr any) error

Deprecated: UnmarshalFromResponse is deprecated. Use `v.JSONBodyInto(r.Body, dest)` instead.

func (Validate) UnmarshalFromString deprecated

func (v Validate) UnmarshalFromString(data string, destStructPtr any) error

Deprecated: UnmarshalFromString is deprecated. Use JSONStrInto instead.

Jump to

Keyboard shortcuts

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