Documentation
¶
Overview ¶
Package httpkit provides standard HTTP middleware and response utilities.
Index ¶
- func JSONError(w http.ResponseWriter, r *http.Request, statusCode int, message string)
- func JSONProblem(w http.ResponseWriter, r *http.Request, err *errors.ServiceError)
- func Logging(logger *slog.Logger) func(http.Handler) http.Handler
- func Recovery(logger *slog.Logger) func(http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequestIDFrom(ctx context.Context) string
- func Tracing() func(http.Handler) http.Handler
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func JSONError ¶
JSONError writes an RFC 9457 Problem Details JSON response for the given status code and message. It constructs a ServiceError internally to derive the type URI and title. For richer error responses, use JSONProblem with an existing ServiceError directly.
func JSONProblem ¶ added in v1.4.0
func JSONProblem(w http.ResponseWriter, r *http.Request, err *errors.ServiceError)
JSONProblem writes an RFC 9457 Problem Details JSON response from a ServiceError.
func Logging ¶
Logging returns middleware that logs each request's method, path, status code, and duration using the provided structured logger. If a request ID is present in the context, it is included in the log entry.
func Recovery ¶
Recovery returns middleware that catches panics in downstream handlers, logs them at Error level with stack information, and returns a 500 JSON error. If the handler has already started writing the response, the error body is skipped to avoid corrupting the response.
func RequestID ¶
RequestID is middleware that generates a unique request ID, stores it in the request context, and sets it as the X-Request-ID response header.
func RequestIDFrom ¶
RequestIDFrom retrieves the request ID from the context. Returns an empty string if no request ID is present.
func Tracing ¶ added in v1.4.0
Tracing returns middleware that creates OpenTelemetry server spans for each HTTP request. It extracts incoming trace context from request headers using the globally configured propagator and records HTTP semantic convention attributes (method, path, status code). Responses with 5xx status codes cause the span status to be set to Error. It also records the http.server.request.duration metric as an OTel histogram.
Types ¶
This section is empty.