24 lines
600 B
Go
24 lines
600 B
Go
|
|
package httpmw
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"runtime/debug"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Recover returns a middleware that catches panics, logs them, and returns 500.
|
||
|
|
func Recover() func(http.Handler) http.Handler {
|
||
|
|
return func(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
defer func() {
|
||
|
|
if rec := recover(); rec != nil {
|
||
|
|
stack := debug.Stack()
|
||
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError),
|
||
|
|
http.StatusInternalServerError)
|
||
|
|
_ = stack // available for future logger injection
|
||
|
|
}
|
||
|
|
}()
|
||
|
|
next.ServeHTTP(w, r)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|