-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
66 lines (58 loc) · 1.48 KB
/
middleware.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
package ginception
import (
"bytes"
"github.com/gin-gonic/gin"
"html/template"
"log"
"net/http"
"runtime/debug"
)
type rtException struct {
Exception string
StackTrace string
Headers http.Header
Cookies []*http.Cookie
WithoutCookies bool
HaveCookies bool
Query string
}
var exceptionPageTemplate *template.Template
func init() {
var err error
exceptionPageTemplate, err = template.New("exception page").Parse(exceptionPage)
if err != nil {
panic("failed to create template" + err.Error())
}
}
func Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// Log incident
log.Println("Ginception caught panic")
debug.PrintStack()
// Prepare model
exception := rtException{}
exception.StackTrace = string(debug.Stack())
exception.Exception = template.HTMLEscapeString(r.(string))
exception.Headers = c.Request.Header
exception.Query = c.Request.RequestURI
exception.Cookies = c.Request.Cookies()
if len(exception.Cookies) < 1 {
exception.WithoutCookies = true
}
exception.HaveCookies = !exception.WithoutCookies
// Render template
result := bytes.Buffer{}
err := exceptionPageTemplate.Execute(&result, exception)
// Return it
c.Data(http.StatusInternalServerError, "text/html; charset=utf-8", result.Bytes())
if err != nil {
log.Println(err.Error())
}
}
}()
// Skip to next template
c.Next()
}
}