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
- func APIKey(r *http.Request, headerName string) string
- func APIKeyRequired(r *http.Request, headerName string) (string, error)
- func AcceptsJSON(r *http.Request) bool
- func BearerToken(r *http.Request) string
- func BearerTokenRequired(r *http.Request) (string, error)
- func Bind[T any](r *http.Request) (T, error)
- func BindJSON[T any](r *http.Request) (T, error)
- func BindWithConfig[T any](r *http.Request, cfg Config) (T, error)
- func ClientIP(r *http.Request, trustProxy ...bool) string
- func ContentType(r *http.Request) string
- func DecodeJSON(r *http.Request, v any) error
- func Header(r *http.Request, key, defaultVal string) string
- func HeaderRequired(r *http.Request, key string) (string, error)
- func IdempotencyKey(r *http.Request) string
- func IsValidEmail(s string) bool
- func IsValidURL(s string) bool
- func IsValidUUID(s string) bool
- func MatchesRegexp(s, pattern string) bool
- func PathParam(r *http.Request, key string) string
- func PathParamInt(r *http.Request, key string) (int, error)
- func PathParamInt64(r *http.Request, key string) (int64, error)
- func PathParamRequired(r *http.Request, key string) (string, error)
- func QueryBool(r *http.Request, key string, defaultVal bool) (bool, error)
- func QueryInt(r *http.Request, key string, defaultVal int) (int, error)
- func QueryInt64(r *http.Request, key string, defaultVal int64) (int64, error)
- func QueryString(r *http.Request, key, defaultVal string) string
- func RequestID(r *http.Request) string
- func SetConfig(cfg Config)
- func SetPaginationConfig(cfg PaginationConfig)
- func ValidateStruct(v any) error
- type Config
- type CursorPagination
- type CursorPaginationConfig
- type Filter
- type FilterConfig
- type Pagination
- func (p Pagination) HasNext(total int) bool
- func (p Pagination) HasPrevious() bool
- func (p Pagination) IsFirstPage() bool
- func (p Pagination) IsLastPage(total int) bool
- func (p Pagination) NextPage() int
- func (p Pagination) PreviousPage() int
- func (p Pagination) SQLClause() string
- func (p Pagination) SQLClauseMySQL() string
- func (p Pagination) TotalPages(total int) int
- type PaginationConfig
- type Query
- func (q *Query) Bool(key string, defaultVal bool) (bool, error)
- func (q *Query) Float64(key string, defaultVal float64) (float64, error)
- func (q *Query) Has(key string) bool
- func (q *Query) Int(key string, defaultVal int) (int, error)
- func (q *Query) Int64(key string, defaultVal int64) (int64, error)
- func (q *Query) IntRange(key string, defaultVal, min, max int) (int, error)
- func (q *Query) String(key, defaultVal string) string
- func (q *Query) StringRequired(key string) (string, error)
- func (q *Query) StringSlice(key string) []string
- func (q *Query) Time(key, layout string) (time.Time, error)
- type SortConfig
- type SortDirection
- type SortField
- type Validation
- func (v *Validation) AddError(field, message string)
- func (v *Validation) Custom(field string, check func() bool, message string)
- func (v *Validation) Error() error
- func (v *Validation) Fields() map[string]string
- func (v *Validation) HasErrors() bool
- func (v *Validation) MatchesPattern(field, value, pattern, message string)
- func (v *Validation) MaxLength(field, value string, max int)
- func (v *Validation) MinLength(field, value string, min int)
- func (v *Validation) OneOf(field, value string, allowed []string)
- func (v *Validation) Range(field string, value, min, max int)
- func (v *Validation) RequireEmail(field, value string)
- func (v *Validation) RequireInt(field string, value int)
- func (v *Validation) RequireString(field, value string)
- func (v *Validation) RequireURL(field, value string)
- func (v *Validation) UUID(field, value string)
- type Validator
Constants ¶
const ( FilterOpEq = "eq" FilterOpNeq = "neq" FilterOpGt = "gt" FilterOpGte = "gte" FilterOpLt = "lt" FilterOpLte = "lte" FilterOpIn = "in" )
Standard filter operators.
const (
DefaultMaxBodySize = 1 << 20 // 1 MB
)
Default limits
Variables ¶
This section is empty.
Functions ¶
func APIKeyRequired ¶
APIKeyRequired extracts an API key or returns an error.
func AcceptsJSON ¶
AcceptsJSON checks if the client accepts JSON responses.
func BearerToken ¶
BearerToken extracts the Bearer token from the Authorization header. Returns empty string if not present or not a Bearer token.
func BearerTokenRequired ¶
BearerTokenRequired extracts the Bearer token or returns an error.
func Bind ¶
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 BindWithConfig ¶
BindWithConfig decodes the JSON request body into T using the provided config.
func ClientIP ¶
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 ¶
ContentType returns the request's Content-Type (media type only, without params).
func DecodeJSON ¶
DecodeJSON decodes the request body into the provided pointer. Use Bind[T] for a generic alternative.
func HeaderRequired ¶
HeaderRequired returns a header value or an error if missing.
func IdempotencyKey ¶
IdempotencyKey returns the Idempotency-Key header value.
func IsValidEmail ¶ added in v0.3.0
IsValidEmail checks whether s is a valid email address using net/mail.
func IsValidURL ¶ added in v0.3.0
IsValidURL checks whether s is a valid absolute URL.
func IsValidUUID ¶ added in v0.3.0
IsValidUUID checks whether s matches the standard UUID format.
func MatchesRegexp ¶ added in v0.3.0
MatchesRegexp checks whether s matches the given regexp pattern.
func PathParam ¶
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 ¶
PathParamInt returns a path parameter as an int.
func PathParamInt64 ¶
PathParamInt64 returns a path parameter as an int64.
func PathParamRequired ¶
PathParamRequired returns a path parameter or an error if empty.
func QueryInt64 ¶
QueryInt64 returns a query parameter as an int64.
func QueryString ¶
QueryString returns a query parameter as a string.
func RequestID ¶
RequestID returns the request ID from common headers. Checks: X-Request-ID → X-Trace-ID
func SetPaginationConfig ¶
func SetPaginationConfig(cfg PaginationConfig)
SetPaginationConfig sets the global pagination configuration.
func ValidateStruct ¶ added in v0.3.0
ValidateStruct validates a struct's fields using `validate` struct tags. It returns an *errors.Error (422) with field-level messages if validation fails, or nil if all rules pass.
Supported tags (comma-separated in `validate:"..."`):
required — value must not be zero email — valid email address (net/mail) url — valid URL (net/url) min=N — minimum length (string/slice/map) or value (int/float) max=N — maximum length (string/slice/map) or value (int/float) len=N — exact length (string/slice/map) oneof=a b c — value must be one of the listed values (space-separated) alpha — string contains only letters alphanum — string contains only letters and digits numeric — string contains only digits uuid — valid UUID format contains=X — string contains substring X startswith=X — string starts with prefix X endswith=X — string ends with suffix X
Field names in error output use the `json` tag name if present.
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 ¶
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 ¶
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 ¶
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.
func (Pagination) HasNext ¶ added in v0.2.0
func (p Pagination) HasNext(total int) bool
HasNext returns true if there are more pages after the current one.
func (Pagination) HasPrevious ¶ added in v0.2.0
func (p Pagination) HasPrevious() bool
HasPrevious returns true if there are pages before the current one.
func (Pagination) IsFirstPage ¶ added in v0.2.0
func (p Pagination) IsFirstPage() bool
IsFirstPage returns true if the current page is the first page.
func (Pagination) IsLastPage ¶ added in v0.2.0
func (p Pagination) IsLastPage(total int) bool
IsLastPage returns true if the current page is the last page.
func (Pagination) NextPage ¶ added in v0.2.0
func (p Pagination) NextPage() int
NextPage returns the next page number (current page + 1). It does not exceed math.MaxInt; callers should use HasNext to check bounds.
func (Pagination) PreviousPage ¶ added in v0.2.0
func (p Pagination) PreviousPage() int
PreviousPage returns the previous page number, minimum 1.
func (Pagination) SQLClause ¶ added in v0.2.0
func (p Pagination) SQLClause() string
SQLClause returns a PostgreSQL-style LIMIT/OFFSET clause.
p.SQLClause() // "LIMIT 20 OFFSET 40"
func (Pagination) SQLClauseMySQL ¶ added in v0.2.0
func (p Pagination) SQLClauseMySQL() string
SQLClauseMySQL returns a MySQL-style LIMIT clause.
p.SQLClauseMySQL() // "LIMIT 40, 20"
func (Pagination) TotalPages ¶ added in v0.2.0
func (p Pagination) TotalPages(total int) int
TotalPages returns the total number of pages for the given total item count.
type PaginationConfig ¶
type PaginationConfig struct {
DefaultPage int
DefaultPerPage int
MaxPerPage int
PageParam string
// PerPageParams lists parameter names to try in order for per-page detection.
// The first matching non-empty parameter wins. If empty, defaults to
// ["per_page", "page_size", "limit"].
PerPageParams []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 (*Query) StringRequired ¶
StringRequired returns a query parameter or an error if missing.
func (*Query) StringSlice ¶
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"]
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) MatchesPattern ¶ added in v0.3.0
func (v *Validation) MatchesPattern(field, value, pattern, message string)
MatchesPattern validates that a string matches the given regex pattern.
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) RequireEmail ¶ added in v0.3.0
func (v *Validation) RequireEmail(field, value string)
RequireEmail validates that a string field is non-empty and a valid email address.
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.
func (*Validation) RequireURL ¶ added in v0.3.0
func (v *Validation) RequireURL(field, value string)
RequireURL validates that a string field is non-empty and a valid URL.
func (*Validation) UUID ¶ added in v0.3.0
func (v *Validation) UUID(field, value string)
UUID validates that a string is a valid UUID format.
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()
}