Files
member-console/internal/middleware/recover.go
T
cgalo5758 88db730fcc Add dual licensing and SPDX headers
Introduce a commercial license option alongside AGPL-3.0-only, require a
CLA for contributors, and document the terms in COMMERCIAL.md and
NOTICE. Add a script to stamp SPDX headers on Go files and apply it
across the tree.
2026-09-06 02:29:42 -05:00

51 lines
1.5 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
package middleware
import (
"log/slog"
"net/http"
"runtime/debug"
"git.coopcloud.tech/wiki-cafe/member-console/internal/logging"
)
// Recovery middleware catches panics and logs them with structured logging.
// errorPage, when non-nil, writes the client-facing 500 response (the server
// wires the styled error page here); it must never include the panic value.
// A nil errorPage falls back to a plain-text 500.
func Recovery(errorPage func(http.ResponseWriter, *http.Request)) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
// Get logger from context
logger := logging.FromContext(r.Context())
// Get request ID from context
requestID := GetRequestID(r.Context())
// Log the panic with stack trace
logger.Error("panic recovered",
slog.String("request_id", requestID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Any("error", err),
slog.String("stack", string(debug.Stack())),
)
// Return 500 Internal Server Error to the client
if errorPage != nil {
errorPage(w, r)
} else {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
}()
next.ServeHTTP(w, r)
})
}
}