-
Notifications
You must be signed in to change notification settings - Fork 0
/
page_handler.go
66 lines (57 loc) · 1.19 KB
/
page_handler.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
package containers
import (
"bytes"
"fmt"
"log"
"net/http"
)
/*
PageHandler combine a `Page` and `Layout` to a normal http handler, then you can mount it a a url that fits.
*/
func PageHandler(page Page, layout Layout) http.Handler {
return &mainHandler{page, layout}
}
func handleError(w http.ResponseWriter, r *http.Request, err error) {
log.Println(err)
if errh, ok := err.(ErrHandler); ok {
errh.HandleErr(w, r, err)
return
}
eh, ok := r.Context().Value(internalServerErrorHandlerKey).(ErrHandler)
if ok {
eh.HandleErr(w, r, err)
return
}
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, err)
return
}
type mainHandler struct {
page Page
layout Layout
}
func (mh *mainHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
cs, err := mh.page.Containers(req)
if err != nil {
handleError(res, req, err)
return
}
buf := bytes.NewBuffer(nil)
for _, c := range cs {
r, err := c.Render(req)
if err != nil {
handleError(res, req, err)
return
}
buf.WriteString(r)
}
var html = buf.String()
if mh.layout != nil {
html, err = mh.layout(req, html)
if err != nil {
handleError(res, req, err)
return
}
}
fmt.Fprintln(res, html)
}