JSON helpers

Reading request bodies and writing JSON results and errors.

The request and response helpers keep a handler short. Successes go out as your own value, failures as a JSON ErrorResponse.

Writing responses

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

Encodes v as JSON with the given status code and the application/json content type.

func WriteError(w http.ResponseWriter, status int, err error)

Writes err as a JSON ErrorResponse with the given status code. Callers map domain errors to status codes themselves.

func WriteBadRequest(w http.ResponseWriter, err error)

Writes err with HTTP 400, the common case of WriteError.

ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

The canonical JSON error body, shaped as {"error": "..."}.

Reading requests

func ReadJSON(r *http.Request, v any) error

Decodes the request body into v.

func ReadRawJSON(r *http.Request) (json.RawMessage, error)

Returns the request body as a json.RawMessage after checking it is well-formed JSON, for when you forward or defer decoding of the payload.