forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
92 lines (81 loc) · 1.86 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package cow
import (
"bytes"
"io"
"os"
"text/template"
"time"
)
// Do not end with "\r\n" so we can add more header later
var headRawTmpl = "HTTP/1.1 {{.CodeReason}}\r\n" +
"Connection: keep-alive\r\n" +
"Cache-Control: no-cache\r\n" +
"Pragma: no-cache\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: {{.Length}}\r\n"
var errPageTmpl, headTmpl *template.Template
func init() {
hostName, err := os.Hostname()
if err != nil {
hostName = "unknown host"
}
errPageRawTmpl := `<!DOCTYPE html>
<html>
<head> <title>COW Proxy</title> </head>
<body>
<h1>{{.H1}}</h1>
{{.Msg}}
<hr />
Generated by <i>COW ` + version + `</i> <br />
Host <i>` + hostName + `</i> <br />
{{.T}}
</body>
</html>
`
if headTmpl, err = template.New("errorHead").Parse(headRawTmpl); err != nil {
Fatal("Internal error on generating error head template")
}
if errPageTmpl, err = template.New("errorPage").Parse(errPageRawTmpl); err != nil {
Fatalf("Internal error on generating error page template")
}
}
func genErrorPage(h1, msg string) (string, error) {
var err error
data := struct {
H1 string
Msg string
T string
}{
h1,
msg,
time.Now().Format(time.ANSIC),
}
buf := new(bytes.Buffer)
err = errPageTmpl.Execute(buf, data)
return buf.String(), err
}
func sendPageGeneric(w io.Writer, codeReason, h1, msg string) {
page, err := genErrorPage(h1, msg)
if err != nil {
errl.Println("Error generating error page:", err)
return
}
data := struct {
CodeReason string
Length int
}{
codeReason,
len(page),
}
buf := new(bytes.Buffer)
if err := headTmpl.Execute(buf, data); err != nil {
errl.Println("Error generating error page header:", err)
return
}
buf.WriteString("\r\n")
buf.WriteString(page)
w.Write(buf.Bytes())
}
func sendErrorPage(w io.Writer, codeReason, h1, msg string) {
sendPageGeneric(w, codeReason, "[Error] "+h1, msg)
}