forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
94 lines (83 loc) · 1.91 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
93
94
package main
import (
"bytes"
"fmt"
"io"
"os"
"text/template"
"time"
)
var errPageRawTmpl = `<!DOCTYPE html>
<html>
<head> <title>COW Proxy</title> </head>
<body>
<h1>{{.H1}}</h1>
{{.Msg}}
{{.Form}}
<hr />
Generated by <i>COW</i> at {{.T}}
</body>
</html>
`
// 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, blockedFormTmpl, directFormTmpl *template.Template
func init() {
var err error
if headTmpl, err = template.New("errorHead").Parse(headRawTmpl); err != nil {
fmt.Println("Internal error on generating error head template")
os.Exit(1)
}
if errPageTmpl, err = template.New("errorPage").Parse(errPageRawTmpl); err != nil {
fmt.Println("Internal error on generating error page template")
os.Exit(1)
}
}
func genErrorPage(h1, msg, form string) (string, error) {
var err error
data := struct {
H1 string
Msg string
Form string
T string
}{
h1,
msg,
form,
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, form, addHeader string) {
page, err := genErrorPage(h1, msg, form)
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(addHeader)
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, "", "")
}