-
Notifications
You must be signed in to change notification settings - Fork 4
/
recoverer.go
75 lines (59 loc) · 1.32 KB
/
recoverer.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package middleware
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"runtime/debug"
"github.com/getsentry/sentry-go"
)
type (
RecovererOptions struct {
Debug bool
Sentry bool
Response RecovererResponse
}
RecovererResponse struct {
Status int
ContentType string
Body interface{}
}
)
func Recoverer(options RecovererOptions) func(http.Handler) http.Handler {
f := func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil {
if options.Debug {
debug.PrintStack()
}
if options.Sentry {
errStr := fmt.Sprint(rvr)
sentry.CaptureException(errors.New(errStr))
}
w = CreateResponse(w, options.Response.ContentType, options.Response.Status, options.Response.Body)
}
}()
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
return f
}
func CreateResponse(w http.ResponseWriter, contentType string, status int, body interface{}) http.ResponseWriter {
if contentType == "" {
contentType = "application/json"
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(status)
if contentType == "application/json" {
jData, err := json.Marshal(body)
if err != nil {
panic(err)
}
w.Write(jData)
} else {
w.Write([]byte(body.(string)))
}
return w
}