Help us shape the future of Go! Take the 2026 Go Developer Survey

responder

package
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: Apache-2.0, MIT Imports: 9 Imported by: 0

Documentation

Overview

Package responder writes the standard API response envelope.

Index

Constants

View Source
const (
	DefaultPageSize = 25
	MaxPageSize     = 100
)

Default and maximum page sizes.

View Source
const (
	StatusSuccess = "success"
	StatusError   = "error"
)

Envelope status values.

View Source
const PaginationAll = -1

PaginationAll requests all records.

Variables

View Source
var ErrInvalidPagination = errors.New("invalid pagination parameters")

ErrInvalidPagination is returned by ParsePagination for malformed pagination query parameters.

Functions

func All added in v0.0.12

func All(page, limit int) bool

All reports whether a normalized page and limit select every record.

func BadRequestJSON

func BadRequestJSON(w http.ResponseWriter, r *http.Request, message string)

BadRequestJSON writes a 400 error envelope.

func Fail

func Fail(w http.ResponseWriter, r *http.Request, status int, message string, opts ...Option)

Fail writes an error envelope. Error details go through WithError.

func ItemRange added in v0.0.12

func ItemRange(page, limit, totalItems int) (first, last int, ok bool)

ItemRange returns the zero-based inclusive range of items a page covers for totalItems records. ok is false when the range is unknown (every record requested, an empty result, or an out-of-range page).

func MethodNotAllowedJSON

func MethodNotAllowedJSON(w http.ResponseWriter, r *http.Request)

MethodNotAllowedJSON writes a 405 error envelope.

func NewRequestID

func NewRequestID() string

NewRequestID generates a fresh request ID.

func NormalizePage added in v0.0.12

func NormalizePage(page, limit, defaultLimit, maxLimit int) (int, int)

NormalizePage applies the shared pagination rules to raw page and limit values and returns the effective pair: a page below 1 becomes the first page, a limit below 1 takes defaultLimit, and a limit above maxLimit is clamped. A transport that can express "unset" separately from zero (query parameters) rejects the zero before calling; a transport that cannot (proto3 int32) relies on the default here, so an unset limit never reaches a store as "no LIMIT".

func NotFoundJSON

func NotFoundJSON(w http.ResponseWriter, r *http.Request)

NotFoundJSON writes a 404 error envelope.

func Offset added in v0.0.12

func Offset(page, limit int) int

Offset returns the SQL offset for a page and limit.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID in ctx, if present.

func Success

func Success(w http.ResponseWriter, r *http.Request, status int, data any, opts ...Option)

Success writes a success envelope with an optional data payload.

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

WithRequestID attaches a request ID to a context.

func WriteError

func WriteError(w http.ResponseWriter, r *http.Request, err error)

WriteError maps an error to the standard response envelope. Validation errors become 422; anything else is an opaque 500 — module handlers map their own domain errors to specific statuses.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes v as JSON without an envelope.

Types

type Envelope

type Envelope struct {
	Status   string   `json:"status"`
	Message  string   `json:"message,omitempty"`
	Data     any      `json:"data,omitzero"`
	Error    any      `json:"error,omitzero"`
	Metadata Metadata `json:"metadata"`
	Links    Links    `json:"links,omitzero"`
}

Envelope is the standard API response wrapper.

type Links map[string]*string

Links maps link relations to URLs. A nil entry marshals as null.

type Metadata

type Metadata struct {
	StatusCode int        `json:"status_code"`
	RequestID  string     `json:"request_id"`
	TraceID    string     `json:"trace_id,omitempty"`
	RateLimit  *RateLimit `json:"rate_limit,omitempty"`

	Page           *int `json:"page,omitempty"`
	Limit          *int `json:"limit,omitempty"`
	TotalPages     *int `json:"total_pages,omitempty"`
	TotalItems     *int `json:"total_items,omitempty"`
	FirstItemIndex *int `json:"first_item_index,omitempty"`
	LastItemIndex  *int `json:"last_item_index,omitempty"`
}

Metadata carries request and pagination data.

type Option

type Option func(*Envelope)

Option customizes the envelope built by Success and Fail.

func WithError

func WithError(detail any) Option

WithError attaches structured error details (an object or array).

func WithPagination

func WithPagination(p Pagination) Option

WithPagination embeds precomputed pagination metadata.

func WithPaginationFrom

func WithPaginationFrom(params PaginationParams, totalItems int) Option

WithPaginationFrom computes pagination metadata from params and totalItems.

type Pagination

type Pagination struct {
	Page           *int
	Limit          *int
	TotalPages     *int
	TotalItems     *int
	FirstItemIndex *int
	LastItemIndex  *int
}

Pagination describes a page within a result set.

func NewPagination

func NewPagination(params PaginationParams, totalItems int) Pagination

NewPagination computes page metadata for totalItems records.

type PaginationParams

type PaginationParams struct {
	Page      int
	Limit     int
	SortBy    string
	SortOrder SortOrder
}

PaginationParams holds pagination query parameters.

func ParsePagination

func ParsePagination(r *http.Request) (PaginationParams, error)

ParsePagination reads pagination parameters from the request.

func ParsePaginationSized

func ParsePaginationSized(r *http.Request, defaultLimit, maxLimit int) (PaginationParams, error)

ParsePaginationSized reads pagination parameters with custom limits.

func (PaginationParams) All

func (p PaginationParams) All() bool

All reports whether the params request every record.

func (PaginationParams) Offset

func (p PaginationParams) Offset() int

Offset returns the SQL offset for the current page.

type RateLimit

type RateLimit struct {
	Limit     int   `json:"limit"`
	Remaining int   `json:"remaining"`
	Reset     int64 `json:"reset"` // unix timestamp when the window resets
}

RateLimit reports the per-window allowance of the rate limiter.

type RequestID

type RequestID = typeid.TypeID[requestPrefix]

RequestID identifies a single API request for tracing and support.

type SortOrder

type SortOrder string

SortOrder is the direction of a sorted result set.

const (
	SortAscending  SortOrder = "asc"
	SortDescending SortOrder = "desc"
)

Jump to

Keyboard shortcuts

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