-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
31 lines (28 loc) · 810 Bytes
/
Copy pathmiddleware.go
File metadata and controls
31 lines (28 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package api
import (
"log/slog"
"net/http"
"runtime/debug"
)
// Middleware is the standard middleware signature compatible with the entire
// Go middleware ecosystem.
type Middleware func(next http.Handler) http.Handler
// Recovery returns middleware that recovers from panics and responds with 500.
func Recovery() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
slog.Error("panic recovered",
"panic", rec,
"stack", string(debug.Stack()),
"method", r.Method,
"path", r.URL.Path,
)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}