-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandlers_error.go
More file actions
65 lines (56 loc) · 1.64 KB
/
handlers_error.go
File metadata and controls
65 lines (56 loc) · 1.64 KB
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
package main
import (
"net/http"
"strings"
)
type errorInterceptingWriter struct {
realWriter http.ResponseWriter
status int
}
func (w *errorInterceptingWriter) Header() http.Header {
return w.realWriter.Header()
}
func (w *errorInterceptingWriter) WriteHeader(status int) {
w.status = status
if w.shouldProxy() {
w.realWriter.WriteHeader(status)
}
}
func (w *errorInterceptingWriter) Write(p []byte) (int, error) {
if w.shouldProxy() {
return w.realWriter.Write(p)
}
return len(p), nil
}
func (w *errorInterceptingWriter) shouldProxy() bool {
return w.status != http.StatusNotFound &&
w.status != http.StatusUnauthorized &&
w.status != http.StatusForbidden &&
w.status != http.StatusInternalServerError &&
w.status != http.StatusBadRequest
}
func PageErrorHandler(t *Templates) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fakeWriter := &errorInterceptingWriter{realWriter: w}
next.ServeHTTP(fakeWriter, r)
switch fakeWriter.status {
case http.StatusNotFound:
isWiki := strings.HasPrefix(r.RequestURI, "/view/") || strings.HasPrefix(r.RequestURI, "/history")
oldPageTitle := ""
if strings.HasPrefix(r.RequestURI, "/view/") {
oldPageTitle = strings.TrimPrefix(r.RequestURI, "/view/")
}
t.RenderNotFound(w, r, isWiki, oldPageTitle)
case http.StatusUnauthorized:
t.RenderUnauthorised(w, r)
case http.StatusForbidden:
t.RenderForbidden(w, r)
case http.StatusInternalServerError:
t.RenderInternalError(w, r)
case http.StatusBadRequest:
t.RenderBadRequest(w, r)
}
})
}
}