httpmw

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 5 Imported by: 0

README

httpmw

net/http middleware for transport-layer concerns: panic recovery, CORS, request ID injection, and structured request logging.

Overview

Four composable func(http.Handler) http.Handler middleware functions:

Middleware Responsibility
Recover() Catches panics; writes 500; captures stack trace
RequestID(generator) Generates a unique ID; injects it via logz.WithRequestID; sets X-Request-ID header
RequestLogger(logger) Logs method, path, status, latency, and request ID after each request
CORS(origins) Sets CORS headers; short-circuits OPTIONS with 204

No authentication or identity logic lives here — see httpauth-firebase for that.

Install

go get code.nochebuena.dev/go/httpmw

Usage

// Recommended order — outermost middleware first
mux.Use(httpmw.Recover())
mux.Use(httpmw.RequestID(uuid.NewString))
mux.Use(httpmw.RequestLogger(logger))
mux.Use(httpmw.CORS([]string{"https://example.com"}))

Pass []string{"*"} to CORS to allow any origin (development only).

Middleware

Recover
mux.Use(httpmw.Recover())

Wraps the handler in a defer/recover. On panic, writes 500 Internal Server Error and captures debug.Stack(). No logger is required.

RequestID
mux.Use(httpmw.RequestID(uuid.NewString))

Calls generator() on every request, stores the ID with logz.WithRequestID, and writes it to the X-Request-ID response header. Must run before RequestLogger so the ID is in context when the logger reads it.

RequestLogger
mux.Use(httpmw.RequestLogger(logger))

Logs method, path, status, latency, and request_id after the inner handler returns. Uses logger.Error for 5xx responses and logger.Info for all others.

CORS
mux.Use(httpmw.CORS([]string{"https://app.example.com", "https://admin.example.com"}))

Sets Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers for matching origins. OPTIONS requests are short-circuited with 204 No Content.

Allowed methods: GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS Allowed headers: Content-Type, Authorization, X-Request-ID

Logger interface

RequestLogger accepts any value satisfying the Logger interface — satisfied by logz.Logger via duck typing:

type Logger interface {
    Info(msg string, args ...any)
    Error(msg string, err error, args ...any)
    With(args ...any) Logger
}

StatusRecorder

StatusRecorder is exported for use in custom middleware that needs to inspect the written status code:

rec := &httpmw.StatusRecorder{ResponseWriter: w, Status: http.StatusOK}
next.ServeHTTP(rec, r)
fmt.Println(rec.Status) // e.g. 404

Dependencies

  • code.nochebuena.dev/go/logz

Documentation

Overview

Package httpmw provides stdlib net/http middleware for transport concerns: panic recovery, CORS, request ID injection, and structured request logging.

No authentication or identity logic lives here — see httpauth-firebase for that.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORS

func CORS(origins []string) func(http.Handler) http.Handler

CORS applies Cross-Origin Resource Sharing headers. origins is the allowed origins list. Pass []string{"*"} for development.

func Recover

func Recover() func(http.Handler) http.Handler

Recover returns a middleware that catches panics, logs them, and returns 500.

func RequestID

func RequestID(generator func() string) func(http.Handler) http.Handler

RequestID injects a unique request ID into the context (via logz.WithRequestID) and the X-Request-ID response header. generator is typically uuid.NewString.

func RequestLogger

func RequestLogger(logger Logger) func(http.Handler) http.Handler

RequestLogger logs each request with method, path, status code, latency, and request ID.

Types

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Error(msg string, err error, args ...any)
	With(args ...any) Logger
}

Logger is the minimal interface httpmw needs — satisfied by logz.Logger via duck typing. httpmw does NOT duck-type the Logger for context purposes (it imports logz for logz.WithRequestID / logz.GetRequestID context helpers).

type StatusRecorder

type StatusRecorder struct {
	http.ResponseWriter
	Status int
}

StatusRecorder wraps http.ResponseWriter to expose the written status code.

func (*StatusRecorder) WriteHeader

func (r *StatusRecorder) WriteHeader(code int)

Jump to

Keyboard shortcuts

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