httputil

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2026 License: MIT Imports: 6 Imported by: 0

README

httputil

Typed HTTP handler adapters and response helpers for stdlib net/http.

Install

go get code.nochebuena.dev/go/httputil

Typed handlers

// JSON body + validation + typed response
r.Post("/orders", httputil.Handle(validator, svc.CreateOrder))

// No request body (GET / DELETE)
r.Get("/orders/{id}", httputil.HandleNoBody(svc.GetOrder))

// Request body, no response body (204)
r.Delete("/orders/{id}", httputil.HandleEmpty(validator, svc.DeleteOrder))

// Manual handler with centralised error mapping
r.Get("/raw", httputil.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
    data, err := svc.Load(r.Context(), chi.URLParam(r, "id"))
    if err != nil {
        return err
    }
    return httputil.JSON(w, http.StatusOK, data)
}))

Error mapping

xerrors.Code → HTTP status:

Code Status
ErrInvalidInput 400
ErrUnauthorized 401
ErrPermissionDenied 403
ErrNotFound 404
ErrAlreadyExists 409
ErrInternal 500
ErrNotImplemented 501
ErrUnavailable 503
ErrDeadlineExceeded 504
unknown 500

Error response body:

{"code": "NOT_FOUND", "message": "record not found"}

Fields from xerrors.Err are merged into the top-level response object.

Dependencies

  • code.nochebuena.dev/go/xerrors
  • code.nochebuena.dev/go/valid

Documentation

Overview

Package httputil provides typed HTTP handler adapters and response helpers.

The centrepiece is Handle, a generics-based adapter that wraps a pure Go function into an net/http.HandlerFunc, handling JSON decode, validation, and error mapping automatically:

r.Get("/orders/{id}", httputil.Handle(validator, svc.GetOrder))

Error responses are mapped from xerrors.Code to HTTP status codes. All response helpers set Content-Type: application/json.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(w http.ResponseWriter, err error)

Error maps err to the appropriate HTTP status code and writes a JSON error body. Understands *xerrors.Err — extracts Code, PlatformCode, and Message. Falls back to 500 for unknown errors.

func Handle

func Handle[Req, Res any](v valid.Validator, fn func(ctx context.Context, req Req) (Res, error)) http.HandlerFunc

Handle adapts a typed business function to http.HandlerFunc. - Decodes JSON request body into Req. - Validates Req using the provided Validator. - Calls fn with the request context and decoded Req. - Encodes Res as JSON with HTTP 200. - Maps any returned error to the appropriate HTTP status via xerrors code.

func HandleEmpty

func HandleEmpty[Req any](v valid.Validator, fn func(ctx context.Context, req Req) error) http.HandlerFunc

HandleEmpty adapts a typed function with a body but no response body (returns 204). Decodes JSON body into Req, validates, calls fn. Returns 204 on success.

func HandleNoBody

func HandleNoBody[Res any](fn func(ctx context.Context) (Res, error)) http.HandlerFunc

HandleNoBody adapts a typed function with no request body (GET, DELETE). Calls fn with request context; encodes result as JSON with HTTP 200.

func JSON

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

JSON encodes v as JSON and writes it with the given status code. Sets Content-Type: application/json.

func NoContent

func NoContent(w http.ResponseWriter)

NoContent writes a 204 No Content response.

Types

type HandlerFunc

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

HandlerFunc is an http.Handler that can return an error. On non-nil error the error is mapped to the appropriate HTTP response via Error. Useful for manual handlers that don't need the typed adapter.

func (HandlerFunc) ServeHTTP

func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

Jump to

Keyboard shortcuts

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