This repository has been archived by the owner on Dec 22, 2022. It is now read-only.
forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover.go
74 lines (61 loc) · 1.66 KB
/
recover.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
package rest
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime/debug"
)
// RecoverMiddleware catches the panic errors that occur in the wrapped HandleFunc,
// and convert them to 500 responses.
type RecoverMiddleware struct {
// Custom logger used for logging the panic errors,
// optional, defaults to log.New(os.Stderr, "", 0)
Logger *log.Logger
// If true, the log records will be printed as JSON. Convenient for log parsing.
EnableLogAsJson bool
// If true, when a "panic" happens, the error string and the stack trace will be
// printed in the 500 response body.
EnableResponseStackTrace bool
}
// MiddlewareFunc makes RecoverMiddleware implement the Middleware interface.
func (mw *RecoverMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
// set the default Logger
if mw.Logger == nil {
mw.Logger = log.New(os.Stderr, "", 0)
}
return func(w ResponseWriter, r *Request) {
// catch user code's panic, and convert to http response
defer func() {
if reco := recover(); reco != nil {
trace := debug.Stack()
// log the trace
message := fmt.Sprintf("%s\n%s", reco, trace)
mw.logError(message)
// write error response
if mw.EnableResponseStackTrace {
Error(w, message, http.StatusInternalServerError)
} else {
Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
}()
// call the handler
h(w, r)
}
}
func (mw *RecoverMiddleware) logError(message string) {
if mw.EnableLogAsJson {
record := map[string]string{
"error": message,
}
b, err := json.Marshal(&record)
if err != nil {
panic(err)
}
mw.Logger.Printf("%s", b)
} else {
mw.Logger.Print(message)
}
}