request

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package request provides helpers for parsing, binding, and validating HTTP request data.

The core function is Bind[T], which decodes the request body into a typed struct, enforces size limits, and validates content types:

type CreateUserReq struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func handler(w http.ResponseWriter, r *http.Request) error {
    req, err := request.Bind[CreateUserReq](r)
    if err != nil { return err }
    // req is CreateUserReq, fully decoded and typed
}

Index

Constants

View Source
const (
	FilterOpEq  = "eq"
	FilterOpNeq = "neq"
	FilterOpGt  = "gt"
	FilterOpGte = "gte"
	FilterOpLt  = "lt"
	FilterOpLte = "lte"
	FilterOpIn  = "in"
)

Standard filter operators.

View Source
const (
	DefaultMaxBodySize = 1 << 20 // 1 MB
)

Default limits

Variables

This section is empty.

Functions

func APIKey

func APIKey(r *http.Request, headerName string) string

APIKey extracts an API key from the specified header (commonly "X-API-Key").

func APIKeyRequired

func APIKeyRequired(r *http.Request, headerName string) (string, error)

APIKeyRequired extracts an API key or returns an error.

func AcceptsJSON

func AcceptsJSON(r *http.Request) bool

AcceptsJSON checks if the client accepts JSON responses.

func BearerToken

func BearerToken(r *http.Request) string

BearerToken extracts the Bearer token from the Authorization header. Returns empty string if not present or not a Bearer token.

func BearerTokenRequired

func BearerTokenRequired(r *http.Request) (string, error)

BearerTokenRequired extracts the Bearer token or returns an error.

func Bind

func Bind[T any](r *http.Request) (T, error)

Bind decodes the JSON request body into T using the global config. Returns the decoded value and an *errors.Error on failure.

user, err := request.Bind[CreateUserReq](r)

func BindJSON

func BindJSON[T any](r *http.Request) (T, error)

BindJSON is an alias for Bind that makes the JSON intent explicit.

func BindWithConfig

func BindWithConfig[T any](r *http.Request, cfg Config) (T, error)

BindWithConfig decodes the JSON request body into T using the provided config.

func ClientIP

func ClientIP(r *http.Request, trustProxy ...bool) string

ClientIP returns the client's IP address. When trustProxy is true, proxy headers (X-Forwarded-For, X-Real-IP) are checked first. When false, only RemoteAddr is used, which is safe against header spoofing.

For production behind a reverse proxy, set trustProxy to true. For direct-to-internet deployments, set trustProxy to false.

func ContentType

func ContentType(r *http.Request) string

ContentType returns the request's Content-Type (media type only, without params).

func DecodeJSON

func DecodeJSON(r *http.Request, v any) error

DecodeJSON decodes the request body into the provided pointer. Use Bind[T] for a generic alternative.

func Header(r *http.Request, key, defaultVal string) string

Header returns a request header value, or the default.

func HeaderRequired

func HeaderRequired(r *http.Request, key string) (string, error)

HeaderRequired returns a header value or an error if missing.

func IdempotencyKey

func IdempotencyKey(r *http.Request) string

IdempotencyKey returns the Idempotency-Key header value.

func PathParam

func PathParam(r *http.Request, key string) string

PathParam returns a path parameter value from the request. Works with Go 1.22+ stdlib routing: http.ServeMux patterns like "GET /users/{id}"

mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
    id := request.PathParam(r, "id")
})

func PathParamInt

func PathParamInt(r *http.Request, key string) (int, error)

PathParamInt returns a path parameter as an int.

func PathParamInt64

func PathParamInt64(r *http.Request, key string) (int64, error)

PathParamInt64 returns a path parameter as an int64.

func PathParamRequired

func PathParamRequired(r *http.Request, key string) (string, error)

PathParamRequired returns a path parameter or an error if empty.

func QueryBool

func QueryBool(r *http.Request, key string, defaultVal bool) (bool, error)

QueryBool returns a query parameter as a bool.

func QueryInt

func QueryInt(r *http.Request, key string, defaultVal int) (int, error)

QueryInt returns a query parameter as an int.

func QueryInt64

func QueryInt64(r *http.Request, key string, defaultVal int64) (int64, error)

QueryInt64 returns a query parameter as an int64.

func QueryString

func QueryString(r *http.Request, key, defaultVal string) string

QueryString returns a query parameter as a string.

func RequestID

func RequestID(r *http.Request) string

RequestID returns the request ID from common headers. Checks: X-Request-ID → X-Trace-ID

func SetConfig

func SetConfig(cfg Config)

SetConfig sets the global binding configuration.

func SetPaginationConfig

func SetPaginationConfig(cfg PaginationConfig)

SetPaginationConfig sets the global pagination configuration.

Types

type Config

type Config struct {
	// MaxBodySize is the maximum allowed request body size in bytes.
	// Defaults to 1MB if zero.
	MaxBodySize int64

	// DisallowUnknownFields rejects JSON bodies with unknown fields.
	DisallowUnknownFields bool
}

Config holds request binding configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default binding configuration.

type CursorPagination

type CursorPagination struct {
	Cursor string
	Limit  int
}

CursorPagination holds cursor-based pagination parameters.

func PaginateCursor

func PaginateCursor(r *http.Request) (CursorPagination, error)

PaginateCursor parses cursor-based pagination from the request.

GET /events?cursor=eyJpZCI6MTIzfQ&limit=25

func PaginateCursorWithConfig

func PaginateCursorWithConfig(r *http.Request, cfg CursorPaginationConfig) (CursorPagination, error)

PaginateCursorWithConfig parses cursor pagination with custom config.

type CursorPaginationConfig

type CursorPaginationConfig struct {
	DefaultLimit int
	MaxLimit     int
	CursorParam  string
	LimitParam   string
}

CursorPaginationConfig configures cursor-based pagination.

func DefaultCursorPaginationConfig

func DefaultCursorPaginationConfig() CursorPaginationConfig

DefaultCursorPaginationConfig returns sensible defaults.

type Filter

type Filter struct {
	Field    string
	Operator string
	Value    string
}

Filter represents a single filter condition.

func ParseFilters

func ParseFilters(r *http.Request, cfg FilterConfig) ([]Filter, error)

ParseFilters parses filter parameters from the request.

Supports two formats:

Simple:   ?filter[status]=active          → {Field: "status", Operator: "eq", Value: "active"}
Operator: ?filter[age][gte]=18            → {Field: "age", Operator: "gte", Value: "18"}

filters, err := request.ParseFilters(r, request.FilterConfig{
    AllowedFields: []string{"status", "age", "role"},
})

type FilterConfig

type FilterConfig struct {
	// AllowedFields is the allowlist of filterable fields.
	// If empty, all fields are allowed.
	AllowedFields []string

	// AllowedOperators restricts which operators can be used.
	// If empty, defaults to: eq, neq, gt, gte, lt, lte, in
	AllowedOperators []string
}

FilterConfig configures filter parsing.

type Pagination

type Pagination struct {
	Page    int
	PerPage int
	Offset  int
}

Pagination holds parsed pagination parameters.

func Paginate

func Paginate(r *http.Request) (Pagination, error)

Paginate parses pagination parameters from the request query string.

GET /users?page=2&per_page=25

p, err := request.Paginate(r)
// p.Page=2, p.PerPage=25, p.Offset=25

func PaginateWithConfig

func PaginateWithConfig(r *http.Request, cfg PaginationConfig) (Pagination, error)

PaginateWithConfig parses pagination with custom config.

type PaginationConfig

type PaginationConfig struct {
	DefaultPage    int
	DefaultPerPage int
	MaxPerPage     int
	PageParam      string
	PerPageParam   string
}

PaginationConfig configures pagination defaults and limits.

func DefaultPaginationConfig

func DefaultPaginationConfig() PaginationConfig

DefaultPaginationConfig returns sensible defaults.

type Query

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

Query provides typed access to URL query parameters. Query values are parsed once and cached for efficient repeated access.

func QueryFrom

func QueryFrom(r *http.Request) *Query

QueryFrom creates a Query helper from an HTTP request.

func (*Query) Bool

func (q *Query) Bool(key string, defaultVal bool) (bool, error)

Bool returns a query parameter as a bool. Accepts: true, false, 1, 0, yes, no.

func (*Query) Float64

func (q *Query) Float64(key string, defaultVal float64) (float64, error)

Float64 returns a query parameter as a float64.

func (*Query) Has

func (q *Query) Has(key string) bool

Has checks if a query parameter exists (even if empty).

func (*Query) Int

func (q *Query) Int(key string, defaultVal int) (int, error)

Int returns a query parameter as an int, or the default value.

func (*Query) Int64

func (q *Query) Int64(key string, defaultVal int64) (int64, error)

Int64 returns a query parameter as an int64.

func (*Query) IntRange

func (q *Query) IntRange(key string, defaultVal, min, max int) (int, error)

IntRange returns an int query parameter clamped to [min, max].

func (*Query) String

func (q *Query) String(key, defaultVal string) string

String returns a query parameter as a string, or the default value.

func (*Query) StringRequired

func (q *Query) StringRequired(key string) (string, error)

StringRequired returns a query parameter or an error if missing.

func (*Query) StringSlice

func (q *Query) StringSlice(key string) []string

StringSlice returns a query parameter as a string slice. Splits by comma by default: ?tags=a,b,c → ["a", "b", "c"] Also supports repeated params: ?tag=a&tag=b → ["a", "b"]

func (*Query) Time

func (q *Query) Time(key, layout string) (time.Time, error)

Time parses a query parameter as a time.Time using the given layout.

type SortConfig

type SortConfig struct {
	// Param is the query parameter name. Default: "sort"
	Param string

	// AllowedFields is the allowlist of sortable fields.
	// If empty, all fields are allowed.
	AllowedFields []string

	// Default is the default sort if none specified.
	Default []SortField
}

SortConfig configures sort parameter parsing.

type SortDirection

type SortDirection string

SortDirection represents ascending or descending sort.

const (
	SortAsc  SortDirection = "asc"
	SortDesc SortDirection = "desc"
)

Sort direction values.

type SortField

type SortField struct {
	Field     string
	Direction SortDirection
}

SortField represents a single sort field and direction.

func ParseSort

func ParseSort(r *http.Request, cfg SortConfig) ([]SortField, error)

ParseSort parses sort parameters from the request.

Format: ?sort=name,-created_at (prefix with - for descending)

sorts, err := request.ParseSort(r, request.SortConfig{
    AllowedFields: []string{"name", "created_at", "email"},
    Default: []request.SortField{{Field: "created_at", Direction: request.SortDesc}},
})

type Validation

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

Validation provides a fluent API for building field-level validation errors.

func NewValidation

func NewValidation() *Validation

NewValidation creates a new Validation builder.

func (*Validation) AddError

func (v *Validation) AddError(field, message string)

AddError adds a field error.

func (*Validation) Custom

func (v *Validation) Custom(field string, check func() bool, message string)

Custom allows adding a custom validation check.

func (*Validation) Error

func (v *Validation) Error() error

Error returns an *errors.Error if there are validation errors, or nil.

func (*Validation) Fields

func (v *Validation) Fields() map[string]string

Fields returns the validation error fields.

func (*Validation) HasErrors

func (v *Validation) HasErrors() bool

HasErrors returns true if any validation errors have been added.

func (*Validation) MaxLength

func (v *Validation) MaxLength(field, value string, max int)

MaxLength validates maximum string length.

func (*Validation) MinLength

func (v *Validation) MinLength(field, value string, min int)

MinLength validates minimum string length.

func (*Validation) OneOf

func (v *Validation) OneOf(field, value string, allowed []string)

OneOf validates that a string is one of the allowed values.

func (*Validation) Range

func (v *Validation) Range(field string, value, min, max int)

Range validates that a number is within a range.

func (*Validation) RequireInt

func (v *Validation) RequireInt(field string, value int)

RequireInt validates that an int field is not zero.

func (*Validation) RequireString

func (v *Validation) RequireString(field, value string)

RequireString validates that a string field is not empty.

type Validator

type Validator interface {
	Validate() error
}

Validator is the interface that request types can implement to perform self-validation after binding.

type CreateUserReq struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func (r CreateUserReq) Validate() error {
    v := request.NewValidation()
    v.RequireString("name", r.Name)
    v.RequireEmail("email", r.Email)
    return v.Error()
}

Jump to

Keyboard shortcuts

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