respond

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 2 Imported by: 0

README

go-respond

CI Go Reference License

HTTP JSON response helpers for Go. Write JSON responses in one line instead of five

Installation

go get github.com/philiprehberger/go-respond

Usage

package main

import (
    "net/http"

    "github.com/philiprehberger/go-respond"
)

func main() {
    http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
        user := map[string]string{"id": "1", "name": "Alice"}
        respond.OK(w, user)
    })

    http.HandleFunc("/items", func(w http.ResponseWriter, r *http.Request) {
        item := map[string]string{"id": "42", "title": "New Item"}
        respond.Created(w, item)
    })

    http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        respond.JSON(w, http.StatusOK, map[string]string{"status": "healthy"})
    })

    http.ListenAndServe(":8080", nil)
}
Error Responses
// Simple error
respond.Error(w, http.StatusNotFound, "resource not found")
// {"error":{"status":404,"message":"resource not found"}}

// Error with details
respond.ErrorWithDetails(w, http.StatusBadRequest, "validation failed", map[string]string{
    "field":  "email",
    "reason": "invalid format",
})
// {"error":{"status":400,"message":"validation failed","details":{"field":"email","reason":"invalid format"}}}
Validation Errors
import respond "github.com/philiprehberger/go-respond"

respond.ValidationError(w, map[string]string{
    "email": "is required",
    "age":   "must be positive",
})
// {"error":"Validation failed","details":{"email":"is required","age":"must be positive"}}
Paginated Responses
import respond "github.com/philiprehberger/go-respond"

respond.Paginated(w, users, 100, 1, 20)
// {"data":[...],"meta":{"total":100,"page":1,"pageSize":20,"pages":5}}
Problem Details (RFC 9457)
respond.Problem(w, http.StatusForbidden,
    respond.WithType("https://example.com/problems/forbidden"),
    respond.WithTitle("Forbidden"),
    respond.WithDetail("You do not have access to this resource"),
    respond.WithInstance("/accounts/12345"),
    respond.WithExtension("account_id", "12345"),
)
// Content-Type: application/problem+json
// {"type":"https://example.com/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have access to this resource","instance":"/accounts/12345","account_id":"12345"}

API

Function Description
JSON(w, status, data) Write JSON response with status code
OK(w, data) Write 200 JSON response
Created(w, data) Write 201 JSON response
NoContent(w) Write 204 response
Error(w, status, message) Write structured error response
ErrorWithDetails(w, status, message, details) Write error with details
ValidationError(w, errors) Write 422 with field validation errors
Paginated[T](w, items, total, page, pageSize) Write 200 with pagination metadata
Accepted(w, data) Write 202 Accepted response
Problem(w, status, opts...) Write RFC 9457 Problem Details

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package respond provides HTTP JSON response helpers for Go.

Write JSON responses in one line instead of five. Includes structured error responses and RFC 9457 Problem Details support.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Accepted added in v0.2.0

func Accepted(w http.ResponseWriter, data any)

Accepted writes a 202 Accepted response, typically for async operations.

func Created

func Created(w http.ResponseWriter, data any)

Created writes a 201 Created JSON response with the given data.

func Error

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

Error writes a structured error JSON response with the given status code and message. The response body has the form:

{"error":{"status":N,"message":"..."}}

func ErrorWithDetails

func ErrorWithDetails(w http.ResponseWriter, status int, message string, details any)

ErrorWithDetails writes a structured error JSON response that includes an additional details field. The response body has the form:

{"error":{"status":N,"message":"...","details":...}}

func JSON

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

JSON writes data as a JSON response with the given HTTP status code. It sets the Content-Type header to application/json. If marshalling fails, a 500 Internal Server Error is written as plain text.

func NoContent

func NoContent(w http.ResponseWriter)

NoContent writes a 204 No Content response with no body.

func OK

func OK(w http.ResponseWriter, data any)

OK writes a 200 OK JSON response with the given data.

func Paginated added in v0.2.0

func Paginated[T any](w http.ResponseWriter, items []T, total int, page int, pageSize int)

Paginated writes a 200 response with items and pagination metadata.

func Problem

func Problem(w http.ResponseWriter, status int, opts ...ProblemOption)

Problem writes an RFC 9457 Problem Details JSON response with the given status code and options. The Content-Type is set to application/problem+json. If marshalling fails, a 500 Internal Server Error is written as plain text.

func ValidationError added in v0.2.0

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

ValidationError writes a 422 response with a list of field validation errors.

Types

type ProblemDetails

type ProblemDetails struct {
	// Type is a URI reference that identifies the problem type.
	Type string `json:"type,omitempty"`

	// Title is a short, human-readable summary of the problem type.
	Title string `json:"title,omitempty"`

	// Status is the HTTP status code for this problem occurrence.
	Status int `json:"status"`

	// Detail is a human-readable explanation specific to this occurrence.
	Detail string `json:"detail,omitempty"`

	// Instance is a URI reference that identifies the specific occurrence.
	Instance string `json:"instance,omitempty"`

	// Extensions holds additional members of the problem details object.
	Extensions map[string]any `json:"-"`
}

ProblemDetails represents an RFC 9457 Problem Details object.

func (ProblemDetails) MarshalJSON

func (p ProblemDetails) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshalling for ProblemDetails to include extension fields as top-level members alongside the standard fields.

type ProblemOption

type ProblemOption func(*ProblemDetails)

ProblemOption is a functional option for configuring a ProblemDetails response.

func WithDetail

func WithDetail(d string) ProblemOption

WithDetail sets the detail message on the problem details.

func WithExtension

func WithExtension(key string, value any) ProblemOption

WithExtension adds a custom extension field to the problem details. Extension fields appear as top-level members in the JSON output.

func WithInstance

func WithInstance(uri string) ProblemOption

WithInstance sets the instance URI on the problem details.

func WithTitle

func WithTitle(t string) ProblemOption

WithTitle sets the title on the problem details.

func WithType

func WithType(uri string) ProblemOption

WithType sets the type URI on the problem details.

Jump to

Keyboard shortcuts

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