-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplates_handlers.go
58 lines (52 loc) · 1.36 KB
/
templates_handlers.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
package gw
import (
"github.com/gorilla/mux"
"github.com/juju/errors"
"net/http"
"path/filepath"
)
func TemplatesRegister(router *mux.Router, c Settings) {
for tmpl, _ := range c.GetTemplates() {
if tmpl == "index.html" {
router.
Handle(
"/",
Middleware(TemplateMiddleware(tmpl), c)).
Methods("GET")
} else if filepath.Base(tmpl) == "index.html" {
router.
Handle(
"/"+filepath.Dir(tmpl)+"/",
Middleware(TemplateMiddleware(tmpl), c)).
Methods("GET")
} else {
router.
Handle(
"/"+tmpl,
Middleware(TemplateMiddleware(tmpl), c)).
Methods("GET")
}
}
}
func TemplateMiddleware(tmpl string) AppHandler {
return func(w http.ResponseWriter, r *http.Request) *AppError {
return TemplateHandler(w, r, tmpl)
}
}
func TemplateHandler(w http.ResponseWriter, r *http.Request, template string) *AppError {
env := r.Context().Value("env").(Settings)
tmpl, ok := env.GetTemplates()[template]
if !ok {
return &AppError{http.StatusInternalServerError, errors.Errorf("The template %s does not exist.", template)}
}
buf := env.GetPool().Get()
err := tmpl.ExecuteTemplate(buf, "base", nil)
if err != nil {
env.GetPool().Put(buf)
return &AppError{http.StatusInternalServerError, errors.Trace(err)}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
buf.WriteTo(w)
env.GetPool().Put(buf)
return nil
}