/
error.go
61 lines (55 loc) · 1.32 KB
/
error.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
package gowl
import (
"fmt"
"html/template"
"io"
"net/http"
"runtime"
"strings"
"github.com/lokhman/gowl/types"
"github.com/pkg/errors"
)
type stackTracer interface {
StackTrace() errors.StackTrace
}
func getMainStackTrace(stack errors.StackTrace) errors.StackTrace {
start := 0
for i, frame := range stack {
fn := runtime.FuncForPC(uintptr(frame) - 1)
if fn == nil {
continue
}
if strings.HasPrefix(fn.Name(), "main.") {
start = i
break
}
}
return stack[start:]
}
func ErrorResponse(statusCode int, debug string) ResponseInterface {
response := NewResponse(statusCode, func(w io.Writer) error {
return ErrorTemplate.Execute(w, types.StringMap{
"name": fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode)),
"server": ServerName,
"debug": debug,
})
})
response.header.Set("Content-Type", "text/html; charset=utf-8")
response.header.Set("X-Content-Type-Options", "nosniff")
return response
}
var ErrorTemplate = template.Must(template.New("error").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{.name}}</title>
</head>
<body style="font-family: sans-serif">
<h1 style="font-size: x-large">{{.name}}</h1>
{{if .debug -}}
<pre>{{.debug}}</pre>
{{- end}}
<hr style="border-style: outset">
<small>{{.server}}</small>
</body>
</html>`))