/
recovery.go
55 lines (47 loc) · 1.25 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
package ostent
import (
"html/template"
"net/http"
"runtime"
"github.com/gorilla/context"
)
type ServePanic struct{ TaggedBin bool }
func NewServePanic(taggedbin bool) *ServePanic { return &ServePanic{TaggedBin: taggedbin} }
func (sp *ServePanic) PanicHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(PanicStatusCode)
var description string
recd := context.Get(r, CPanicError)
if err, ok := recd.(error); ok {
description = err.Error()
} else if s, ok := recd.(string); ok {
description = s
}
var stack string
if !sp.TaggedBin {
sbuf := make([]byte, 4096-len(PanicStatusText)-len(description))
size := runtime.Stack(sbuf, false)
stack = string(sbuf[:size])
}
if tpl, err := PanicTemplate.Clone(); err == nil { // otherwise bail out
tpl.Execute(w, struct {
Title, Description, Stack string
}{
Title: PanicStatusText,
Description: description,
Stack: stack,
})
}
}
const PanicStatusCode = http.StatusInternalServerError
var (
PanicStatusText = statusLine(PanicStatusCode)
PanicTemplate = template.Must(template.New("recovery.html").Parse(`
<html>
<head><title>{{.Title}}</title></head>
<body bgcolor="white">
<center><h1>{{.Description}}</h1></center>
<hr><pre>{{.Stack}}</pre>
</body>
</html>
`))
)