forked from GoesToEleven/GolangTraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
34 lines (32 loc) · 827 Bytes
/
template.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
package main
import (
"bytes"
"encoding/json"
"google.golang.org/appengine"
"google.golang.org/appengine/memcache"
"io"
"net/http"
)
func serveTemplate(res http.ResponseWriter, req *http.Request, templateName string) {
memItem := getSession(req)
if len(memItem.Value) > 0 {
var sd SessionData
json.Unmarshal(memItem.Value, &sd)
sd.LoggedIn = true
tpl.ExecuteTemplate(res, templateName, sd)
} else {
ctx := appengine.NewContext(req)
i, err := memcache.Get(ctx, templateName)
if err != nil {
buf := new(bytes.Buffer)
writ := io.MultiWriter(res, buf)
tpl.ExecuteTemplate(writ, templateName, SessionData{})
memcache.Set(ctx, &memcache.Item{
Key: templateName,
Value: buf.Bytes(),
})
return
}
io.WriteString(res, string(i.Value)) // we're serving the page from memcache
}
}