Documentation
¶
Overview ¶
Package rr provides unified, framework-agnostic HTTP request helpers and response envelopes.
Request helpers cover list-endpoint concerns (pagination, sorting) and work from url.Values or *http.Request. Struct tags use standard form / json / query keys so the same types bind in gin, echo, fiber, and similar frameworks.
Response types and builders have no framework dependency. Write helpers use the standard library's http.ResponseWriter, so they plug into net/http, chi, gorilla/mux, gin, echo, fiber (via adaptor), and any other HTTP stack.
Index ¶
- Constants
- Variables
- func BadRequest(w http.ResponseWriter, message string)
- func Conflict(w http.ResponseWriter, message string)
- func Forbidden(w http.ResponseWriter, message string)
- func InternalError(w http.ResponseWriter, message string)
- func JSON[T any](resp Response[T]) ([]byte, error)
- func NotFound(w http.ResponseWriter, message string)
- func TooManyRequests(w http.ResponseWriter, message string)
- func Unauthorized(w http.ResponseWriter, message string)
- func UnprocessableEntity(w http.ResponseWriter, message string)
- func Write[T any](w http.ResponseWriter, status int, resp Response[T])
- func WriteError(w http.ResponseWriter, status, code int, message string)
- func WriteOK[T any](w http.ResponseWriter, data T)
- func WriteOKMeta[T any](w http.ResponseWriter, data T, meta *Meta)
- func WriteOKMsg[T any](w http.ResponseWriter, data T, msg string)
- func WriteOKMsgMeta[T any](w http.ResponseWriter, data T, msg string, meta *Meta)
- type Error
- type ListParams
- type Meta
- type PaginationParams
- type Response
- func Fail(code int, message string) Response[any]
- func FailData[T any](code int, message string, data T) Response[T]
- func OK[T any](data T) Response[T]
- func OKMeta[T any](data T, meta *Meta) Response[T]
- func OKMsg[T any](data T, msg string) Response[T]
- func OKMsgMeta[T any](data T, msg string, meta *Meta) Response[T]
- type SortParams
Constants ¶
const ( DefaultPage = 1 DefaultLimit = 10 DefaultMax = 100 )
Default pagination values. Override via Config or per-call options.
Variables ¶
var Config = struct { DefaultPage int DefaultLimit int MaxLimit int // Query key names used by Parse* helpers. PageKey string LimitKey string SortByKey string IsDescKey string // OrderKey is an alternative to IsDescKey: "asc" / "desc". OrderKey string }{ DefaultPage: DefaultPage, DefaultLimit: DefaultLimit, MaxLimit: DefaultMax, PageKey: "page", LimitKey: "limit", SortByKey: "sortBy", IsDescKey: "isDesc", OrderKey: "order", }
Config holds package-level defaults. Safe to mutate at startup only.
Functions ¶
func InternalError ¶
func InternalError(w http.ResponseWriter, message string)
InternalError writes 500.
func TooManyRequests ¶
func TooManyRequests(w http.ResponseWriter, message string)
TooManyRequests writes 429.
func Unauthorized ¶
func Unauthorized(w http.ResponseWriter, message string)
Unauthorized writes 401.
func UnprocessableEntity ¶
func UnprocessableEntity(w http.ResponseWriter, message string)
UnprocessableEntity writes 422.
func Write ¶
func Write[T any](w http.ResponseWriter, status int, resp Response[T])
Write encodes resp as JSON with the given HTTP status code.
If json.Marshal fails (e.g. circular data, panicking MarshalJSON), it writes a 500 Internal Server Error fallback instead of silently returning a partial or empty body under the original status code.
func WriteError ¶
func WriteError(w http.ResponseWriter, status, code int, message string)
WriteError writes a failed response with the given HTTP status and error body. status is the HTTP status code; code is the application error code in the body.
func WriteOK ¶
func WriteOK[T any](w http.ResponseWriter, data T)
WriteOK writes a 200 success response.
func WriteOKMeta ¶
func WriteOKMeta[T any](w http.ResponseWriter, data T, meta *Meta)
WriteOKMeta writes a 200 success response with metadata.
func WriteOKMsg ¶
func WriteOKMsg[T any](w http.ResponseWriter, data T, msg string)
WriteOKMsg writes a 200 success response with a custom message.
func WriteOKMsgMeta ¶
func WriteOKMsgMeta[T any](w http.ResponseWriter, data T, msg string, meta *Meta)
WriteOKMsgMeta writes a 200 success response with a custom message and metadata.
Types ¶
type Error ¶
Error holds application-level error details inside the envelope. Code is free-form (HTTP status, business code, or both — your convention).
type ListParams ¶
type ListParams struct {
PaginationParams
SortParams
}
ListParams combines pagination and sorting for typical list endpoints.
func ParseList ¶
func ParseList(q url.Values) ListParams
ParseList reads both pagination and sort params from url.Values.
func ParseListFromRequest ¶
func ParseListFromRequest(r *http.Request) ListParams
ParseListFromRequest reads list params from r.URL.Query().
type Meta ¶
type Meta struct {
Page int `json:"page,omitempty"`
PerPage int `json:"per_page,omitempty"`
TotalCount int64 `json:"total_count,omitempty"`
// TotalPages is computed when both PerPage and TotalCount are set via NewMeta.
TotalPages int `json:"total_pages,omitempty"`
}
Meta holds optional response metadata such as pagination.
type PaginationParams ¶
type PaginationParams struct {
Page int `form:"page" json:"page" query:"page"`
Limit int `form:"limit" json:"limit" query:"limit"`
// MaxLimit caps GetLimit(). Zero means use Config.MaxLimit.
MaxLimit int `form:"-" json:"-" query:"-"`
}
PaginationParams is a reusable page/limit pair for list endpoints.
Embed into your own request DTOs:
type ListUsersReq struct {
rr.PaginationParams
Status string `form:"status" json:"status" query:"status"`
}
func ParsePagination ¶
func ParsePagination(q url.Values) PaginationParams
ParsePagination reads page/limit from url.Values (query or form).
func ParsePaginationFromRequest ¶
func ParsePaginationFromRequest(r *http.Request) PaginationParams
ParsePaginationFromRequest reads pagination from r.URL.Query().
func (*PaginationParams) GetLimit ¶
func (p *PaginationParams) GetLimit() int
GetLimit returns a safe page size, clamped to MaxLimit.
func (*PaginationParams) GetOffset ¶
func (p *PaginationParams) GetOffset() int64
GetOffset is an alias of GetSkip for naming conventions that prefer "offset".
func (*PaginationParams) GetPage ¶
func (p *PaginationParams) GetPage() int
GetPage returns a safe page number (>= 1).
func (*PaginationParams) GetSkip ¶
func (p *PaginationParams) GetSkip() int64
GetSkip returns the offset for SQL OFFSET / Mongo skip style queries.
func (PaginationParams) WithMaxLimit ¶
func (p PaginationParams) WithMaxLimit(max int) PaginationParams
WithMaxLimit returns a copy of p with MaxLimit set.
type Response ¶
type Response[T any] struct { Success bool `json:"success"` Msg string `json:"msg,omitempty"` Data T `json:"data,omitempty"` Error *Error `json:"error,omitempty"` Meta *Meta `json:"meta,omitempty"` }
Response is the unified API response envelope.
Example success:
{"success":true,"msg":"ok","data":{...},"meta":{...}}
Example error:
{"success":false,"error":{"code":400,"message":"invalid id"}}
type SortParams ¶
type SortParams struct {
// SortBy is the client-requested sort field.
SortBy string `form:"sortBy" json:"sortBy" query:"sortBy"`
// IsDesc requests descending order when true.
IsDesc bool `form:"isDesc" json:"isDesc" query:"isDesc"`
// Order is an alternative to IsDesc: "asc", "desc", "descending", or "d".
// Used by struct-binding frameworks (gin, echo) which read query tags.
Order string `form:"order" json:"order" query:"order"`
// AllowedSortBy restricts SortBy to a whitelist. Empty = allow any.
AllowedSortBy []string `form:"-" json:"-" query:"-"`
// DefaultSortBy is used when SortBy is empty or not allowed.
DefaultSortBy string `form:"-" json:"-" query:"-"`
}
SortParams is a reusable sort-by / order pair for list endpoints.
func ParseSort ¶
func ParseSort(q url.Values) SortParams
ParseSort reads sortBy / isDesc (or order) from url.Values.
Supported inputs for direction:
- isDesc=true|1|yes
- order=desc|asc (case-insensitive)
func ParseSortFromRequest ¶
func ParseSortFromRequest(r *http.Request) SortParams
ParseSortFromRequest reads sort params from r.URL.Query().
func (*SortParams) GetOrder ¶
func (p *SortParams) GetOrder() string
GetOrder returns "asc" or "desc".
func (*SortParams) GetSortBy ¶
func (p *SortParams) GetSortBy() string
GetSortBy returns a validated sort field (or DefaultSortBy / empty).
func (*SortParams) IsDescending ¶
func (p *SortParams) IsDescending() bool
IsDescending reports whether sort order is descending.
func (SortParams) WithAllowedSort ¶
func (p SortParams) WithAllowedSort(allowed []string, defaultSort string) SortParams
WithAllowedSort returns a copy of p with AllowedSortBy / DefaultSortBy set. Useful after ParseSort:
sort := rr.ParseSort(q).WithAllowedSort([]string{"name","created_at"}, "created_at")