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 ¶
- func Error(w http.ResponseWriter, err error)
- func Handle[Req, Res any](v valid.Validator, fn func(ctx context.Context, req Req) (Res, error)) http.HandlerFunc
- func HandleEmpty[Req any](v valid.Validator, fn func(ctx context.Context, req Req) error) http.HandlerFunc
- func HandleNoBody[Res any](fn func(ctx context.Context) (Res, error)) http.HandlerFunc
- func JSON(w http.ResponseWriter, status int, v any)
- func NoContent(w http.ResponseWriter)
- type HandlerFunc
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 ¶
HandleNoBody adapts a typed function with no request body (GET, DELETE). Calls fn with request context; encodes result as JSON with HTTP 200.
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)