/
wrapper.go
75 lines (60 loc) · 1.3 KB
/
wrapper.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
package gomvc
import (
"fmt"
"github.com/flosch/pongo"
"github.com/gorilla/sessions"
"net/http"
"path"
"strings"
)
type Wrapper struct {
Req *http.Request
Res http.ResponseWriter
App App
Session *sessions.Session
}
type TemplateVars map[string]interface{}
var (
dirtyBits int = 256
)
func (w Wrapper) Write(str string) {
fmt.Fprintf(w.Res, str)
}
var tplCache = map[string]*pongo.Template{}
func (w Wrapper) Render(p string) {
w.RenderWithVars(p, TemplateVars{})
}
func (w Wrapper) RenderWithVars(p string, vars TemplateVars) {
w.Res.Header().Add("Content-type", "text/html")
tplFile := path.Join(w.App.ViewsRoot, p)
var tpl *pongo.Template
if val, ok := tplCache[tplFile]; ok {
tpl = val
} else {
tpl = pongo.Must(pongo.FromFile(tplFile, nil))
}
var context = pongo.Context{
"session": w.Session,
}
for k, v := range vars {
context[k] = v
}
out, err := tpl.Execute(&context)
if err != nil {
panic(err)
}
w.Write(*out)
}
func (w Wrapper) Push(c string) {
fmt.Fprintf(w.Res, "<script>console.log('xd');</script>\n"+strings.Repeat("\n", dirtyBits))
f := w.Res.(http.Flusher)
f.Flush()
}
func (w Wrapper) End() {
fmt.Fprintf(w.Res, strings.Repeat("\n", dirtyBits))
f := w.Res.(http.Flusher)
f.Flush()
}
func (w Wrapper) SaveSession() {
w.Session.Save(w.Req, w.Res)
}