response

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package response provides structured JSON response helpers with a consistent envelope format and generics support.

The standard response envelope:

{
    "success": true,
    "message": "User created",
    "data": { ... },
    "meta": { ... },
    "timestamp": 1700000000
}

Usage with the builder:

response.New().
    Status(201).
    Message("User created").
    Data(user).
    Send(w)

Or with convenience functions:

response.OK(w, "Success", user)
response.NotFound(w, "User not found")
response.ValidationError(w, fields)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Accepted

func Accepted(w http.ResponseWriter, message string, data any)

Accepted writes a 202 response.

func BadRequest

func BadRequest(w http.ResponseWriter, message string)

BadRequest writes a 400 response.

func Conflict

func Conflict(w http.ResponseWriter, message string)

Conflict writes a 409 response.

func Created

func Created(w http.ResponseWriter, message string, data any)

Created writes a 201 response.

func CursorPaginated

func CursorPaginated(w http.ResponseWriter, data any, meta CursorMeta)

CursorPaginated writes a cursor-paginated response.

response.CursorPaginated(w, events, response.CursorMeta{
    NextCursor: "eyJpZCI6MTAwfQ==",
    HasMore:    true,
    Total:      500,
})

func Err

func Err(w http.ResponseWriter, err error)

Err writes an error response from an *errors.Error. This is the primary way to send error responses, bridging the errors package.

if err != nil {
    response.Err(w, err)
    return
}

func Error

func Error(w http.ResponseWriter, statusCode int, code, message string)

Error writes a custom error response.

func ErrorWithFields

func ErrorWithFields(w http.ResponseWriter, statusCode int, code, message string, fields map[string]string)

ErrorWithFields writes an error response with field-level errors.

func File

func File(w http.ResponseWriter, filename string, data []byte, contentType string)

File sends a file as a download.

func Forbidden

func Forbidden(w http.ResponseWriter, message string)

Forbidden writes a 403 response.

func HTML

func HTML(w http.ResponseWriter, statusCode int, html string)

HTML writes an HTML response.

func Handle

func Handle(fn HandlerFunc) http.HandlerFunc

Handle wraps a HandlerFunc into a standard http.HandlerFunc. If the handler returns an error:

  • *errors.Error → sends the appropriate status code and error body
  • Standard error → sends 500 with a generic message (original error NOT exposed)

func HandleWith

func HandleWith(fn HandlerFunc, onError func(w http.ResponseWriter, r *http.Request, err error)) http.HandlerFunc

HandleWith wraps a HandlerFunc with a custom error handler.

func InternalServerError

func InternalServerError(w http.ResponseWriter, message string)

InternalServerError writes a 500 response.

func JSON

func JSON(w http.ResponseWriter, statusCode int, data any)

JSON writes a success response with the given status code and data.

func NoContent

func NoContent(w http.ResponseWriter)

NoContent writes a 204 response with no body.

func NotFound

func NotFound(w http.ResponseWriter, message string)

NotFound writes a 404 response.

func OK

func OK(w http.ResponseWriter, message string, data any)

OK writes a 200 response.

func Paginated

func Paginated(w http.ResponseWriter, data any, meta PageMeta)

Paginated writes a paginated response with offset-based metadata.

response.Paginated(w, users, response.PageMeta{
    Page: 1, PerPage: 20, Total: 150, TotalPages: 8,
})

func PaginatedWithMessage

func PaginatedWithMessage(w http.ResponseWriter, message string, data any, meta PageMeta)

PaginatedWithMessage writes a paginated response with a message.

func Raw

func Raw(w http.ResponseWriter, statusCode int, contentType string, data []byte)

Raw writes raw bytes with a custom content type. Use this for non-JSON responses like HTML, XML, plain text, etc.

func Redirect

func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)

Redirect sends an HTTP redirect.

func ServiceUnavailable

func ServiceUnavailable(w http.ResponseWriter, message string)

ServiceUnavailable writes a 503 response.

func SetLinkHeader added in v0.2.0

func SetLinkHeader(w http.ResponseWriter, baseURL string, page, perPage, total int)

SetLinkHeader sets an RFC 5988 Link header for paginated responses.

response.SetLinkHeader(w, "https://api.example.com/users", 2, 20, 100)
// Link: <https://api.example.com/users?page=3&per_page=20>; rel="next",
//       <https://api.example.com/users?page=1&per_page=20>; rel="prev",
//       <https://api.example.com/users?page=1&per_page=20>; rel="first",
//       <https://api.example.com/users?page=5&per_page=20>; rel="last"

func Stream

func Stream(w http.ResponseWriter, fn func(send func(event, data string) error) error)

Stream provides Server-Sent Events (SSE) streaming.

response.Stream(w, func(send func(event, data string) error) error {
    for msg := range messages {
        if err := send("message", msg); err != nil {
            return err
        }
    }
    return nil
})

func StreamJSON

func StreamJSON(w http.ResponseWriter, fn func(send func(event string, data any) error) error)

StreamJSON is like Stream but sends JSON-encoded data.

func Text

func Text(w http.ResponseWriter, statusCode int, text string)

Text writes a plain text response.

func TooManyRequests

func TooManyRequests(w http.ResponseWriter, message string)

TooManyRequests writes a 429 response.

func Unauthorized

func Unauthorized(w http.ResponseWriter, message string)

Unauthorized writes a 401 response.

func ValidationError

func ValidationError(w http.ResponseWriter, fields map[string]string)

ValidationError writes a 422 response with field errors.

func Wrap

Wrap wraps a standard http.HandlerFunc so that any error passed to Err or the error convenience helpers is automatically written as a structured JSON response. Use this when you prefer the standard handler signature with no return type.

mux.HandleFunc("GET /users/{id}", response.Wrap(getUser))

func getUser(w http.ResponseWriter, r *http.Request) {
    id := request.PathParam(r, "id")
    user, err := db.FindUser(id)
    if err != nil {
        response.Err(w, errors.NotFound("User"))
        return
    }
    response.OK(w, "Success", user)
}

Wrap is a thin pass-through today, but it future-proofs your handlers for middleware features like response capture or panic recovery.

Types

type Builder

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

Builder provides a fluent interface for constructing responses.

response.New().
    Status(http.StatusCreated).
    Message("User created").
    Data(user).
    Header("X-Resource-ID", user.ID).
    Send(w)

func New

func New() *Builder

New creates a new response Builder with defaults (200 OK, success=true).

func (*Builder) CursorPagination

func (b *Builder) CursorPagination(nextCursor string, hasMore bool, total int) *Builder

CursorPagination sets cursor-based pagination metadata.

func (*Builder) Data

func (b *Builder) Data(data any) *Builder

Data sets the response data.

func (*Builder) Err

func (b *Builder) Err(code, message string) *Builder

Err sets error information, marking the response as failed.

func (*Builder) ErrDetails

func (b *Builder) ErrDetails(details map[string]any) *Builder

ErrDetails adds arbitrary error metadata.

func (*Builder) ErrFields

func (b *Builder) ErrFields(fields map[string]string) *Builder

ErrFields adds field-level error details.

func (*Builder) Header

func (b *Builder) Header(key, value string) *Builder

Header sets a custom response header.

func (*Builder) JSON

func (b *Builder) JSON() ([]byte, error)

JSON returns the response envelope as JSON bytes.

func (*Builder) Message

func (b *Builder) Message(msg string) *Builder

Message sets the response message.

func (*Builder) Meta

func (b *Builder) Meta(meta any) *Builder

Meta sets the response metadata.

func (*Builder) MustJSON

func (b *Builder) MustJSON() []byte

MustJSON returns the response as JSON bytes or panics.

func (*Builder) Pagination

func (b *Builder) Pagination(page, perPage, total int) *Builder

Pagination sets offset-based pagination metadata.

func (*Builder) Send

func (b *Builder) Send(w http.ResponseWriter)

Send writes the response to the http.ResponseWriter. The timestamp is set at send time to reflect the actual response time.

func (*Builder) Status

func (b *Builder) Status(code int) *Builder

Status sets the HTTP status code.

type CursorMeta

type CursorMeta struct {
	NextCursor string `json:"next_cursor,omitempty"`
	HasMore    bool   `json:"has_more"`
	Total      int    `json:"total,omitempty"`
}

CursorMeta represents cursor-based pagination metadata.

type Envelope

type Envelope struct {
	Success   bool       `json:"success"`
	Message   string     `json:"message,omitempty"`
	Data      any        `json:"data,omitempty"`
	Error     *ErrorBody `json:"error,omitempty"`
	Meta      any        `json:"meta,omitempty"`
	Timestamp int64      `json:"timestamp"`
}

Envelope is the standard API response envelope. All API responses are wrapped in this structure.

type ErrorBody

type ErrorBody struct {
	Code    string            `json:"code"`
	Message string            `json:"message"`
	Fields  map[string]string `json:"fields,omitempty"`
	Details map[string]any    `json:"details,omitempty"`
}

ErrorBody is the error portion of the response envelope.

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

HandlerFunc is an HTTP handler that returns an error. When the handler returns a non-nil error, it is automatically converted to a structured JSON response.

mux.HandleFunc("GET /users/{id}", response.Handle(getUser))

func getUser(w http.ResponseWriter, r *http.Request) error {
    id := request.PathParam(r, "id")
    user, err := db.FindUser(id)
    if err != nil {
        return errors.NotFound("User")
    }
    response.OK(w, "Success", user)
    return nil
}

type PageMeta

type PageMeta struct {
	Page        int  `json:"page"`
	PerPage     int  `json:"per_page"`
	Total       int  `json:"total"`
	TotalPages  int  `json:"total_pages"`
	HasNext     bool `json:"has_next"`
	HasPrevious bool `json:"has_previous"`
}

PageMeta represents offset-based pagination metadata.

func NewPageMeta

func NewPageMeta(page, perPage, total int) PageMeta

NewPageMeta creates a PageMeta from page, perPage, and total count. TotalPages, HasNext, and HasPrevious are computed automatically. If perPage is <= 0, TotalPages defaults to 0.

type TypedEnvelope

type TypedEnvelope[T any] struct {
	Success   bool       `json:"success"`
	Message   string     `json:"message,omitempty"`
	Data      T          `json:"data,omitempty"`
	Error     *ErrorBody `json:"error,omitempty"`
	Meta      any        `json:"meta,omitempty"`
	Timestamp int64      `json:"timestamp"`
}

TypedEnvelope is a generic version of Envelope for type-safe responses. Useful when you want compile-time type checking on the data field.

Jump to

Keyboard shortcuts

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