-
Notifications
You must be signed in to change notification settings - Fork 0
/
recovery.go
56 lines (50 loc) · 1.1 KB
/
recovery.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
44
45
46
47
48
49
50
51
52
53
54
55
56
package middleware
import (
"fmt"
"log"
"net/http"
"os"
"runtime"
"github.com/alxarch/go-http/httperror"
)
func NewRecovery() *Recovery {
return &Recovery{
Logger: log.New(os.Stdout, "", 0),
StackSize: DefaultBufferSize,
}
}
type Recovery struct {
Logger *log.Logger
PrintStack bool
StackAll bool
StackSize int
}
func (rec *Recovery) Wrap(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if e := recover(); e != nil {
if hp, ok := e.(httperror.HTTPError); ok {
// Handle http coded errors gracefully
http.Error(w, hp.Error(), hp.Code())
} else {
w.WriteHeader(http.StatusInternalServerError)
f := "PANIC: %s\n%s"
var stack []byte
if rec.StackSize > 0 {
stack = make([]byte, rec.StackSize)
stack = stack[:runtime.Stack(stack, rec.StackAll)]
} else {
stack = []byte{}
}
if rec.PrintStack {
fmt.Fprintf(w, f, e, stack)
}
if rec.Logger != nil {
rec.Logger.Printf(f, e, stack)
}
}
}
}()
next.ServeHTTP(w, r)
})
}