httputil

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: AGPL-3.0 Imports: 7 Imported by: 0

Documentation

Overview

Package httputil provides typed handler adapters and HTTP response helpers.

Handler adapters eliminate HTTP boilerplate — business functions stay pure Go with no knowledge of request parsing or response encoding. All errors flow through a centralized Error handler that logs once at the correct level and writes a standardized JSON response body.

Typed handler adapters

type CreateUserReq struct {
    Email string `json:"email" validate:"required,email"`
}
type CreateUserRes struct {
    ID string `json:"id"`
}

r.Post("/users", httputil.Handle(v, logger, func(ctx context.Context, req CreateUserReq) (CreateUserRes, error) {
    u, err := svc.CreateUser(ctx, req.Email)
    if err != nil {
        return CreateUserRes{}, err // propagates to Error — logged once, correct HTTP status
    }
    return CreateUserRes{ID: u.ID}, nil
}))

Centralized error handler

Error is the single point of error processing for all handlers:

  • 5xx → Error level (logz auto-enriches with error_code and WithContext fields)
  • 4xx → Warn level (client mistake — not a server failure)
  • 499 → Info level (client cancelled the request intentionally)

Call it directly from HandlerFunc when you need path parameters or custom logic:

r.Get("/users/{id}", httputil.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
    id := chi.URLParam(r, "id")
    u, err := svc.GetUser(r.Context(), id)
    if err != nil {
        httputil.Error(logger, w, r, err)
        return nil
    }
    httputil.JSON(w, http.StatusOK, u)
    return nil
}).ServeHTTP)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(logger logging.Logger, w http.ResponseWriter, r *http.Request, err error)

Error is the centralized error handler. It logs at the appropriate level and writes a standardized JSON error body.

Log level is derived from the HTTP status:

  • 5xx → Error (unexpected server failure; logz auto-enriches with error_code and context fields)
  • 4xx → Warn (client mistake — not a server failure)
  • 499 → Info (client cancelled the request intentionally)

The response body always contains code and message; platform_code and context fields attached via xerrors.Err.WithContext are included when present.

func Handle

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

Handle adapts a typed business function to http.HandlerFunc.

  • Decodes the JSON request body into Req.
  • Validates Req using the provided valid.Validator.
  • Calls fn with the request context and decoded Req.
  • Encodes Res as JSON with HTTP 200 on success.
  • On error: logs via Error (level derived from HTTP status) and writes the standardized JSON body.

func HandleEmpty

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

HandleEmpty adapts a typed function with a request body but no response body. Decodes and validates Req, calls fn, returns 204 No Content on success. On error: logs via Error and writes the standardized JSON body.

func HandleNoBody

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

HandleNoBody adapts a typed function with no request body (GET, HEAD). Calls fn with the request context; encodes the result as JSON with HTTP 200. On error: logs via Error and writes the standardized JSON body.

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 returns an error. On non-nil error the error is mapped to the appropriate HTTP response via Error. Use for manual handlers that need path parameters or custom status codes.

func (HandlerFunc) ServeHTTP

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

ServeHTTP implements http.Handler. Errors are written as standardized JSON without logging — no logger is in scope for a bare function type. Use Handle, HandleNoBody, or HandleEmpty for centralized logging, or call Error explicitly.

Jump to

Keyboard shortcuts

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