-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
43 lines (35 loc) · 1.04 KB
/
handler.go
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
32
33
34
35
36
37
38
39
40
41
42
43
package problem
import (
"errors"
"net/http"
)
// InternalServerError is used by [Handler] to serve as response if no callback is defined.
var InternalServerError = &Details{
Status: http.StatusInternalServerError,
Title: "Internal Server Error",
}
// Handler wraps the given http.Handler and automatically recovers panics from given handler.
//
// When recovering from a panic, if the recovered value is an error, the handler will first try converting it into a
// value of type *Details using [errors.As] and, if successful, serve the value using [Details.ServeHTTP].
//
// Otherwise [InternalServerError] is served as response.
func Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
recovered := recover()
if recovered == nil {
return
}
var details *Details
if err, ok := recovered.(error); ok {
errors.As(err, &details)
}
if details == nil {
details = InternalServerError
}
details.ServeHTTP(w, r)
}()
next.ServeHTTP(w, r)
})
}