forked from awesomecoders/cloudkeys-go
/
httpHelper.go
66 lines (56 loc) · 1.81 KB
/
httpHelper.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 main
import (
"fmt"
"net/http"
"github.com/flosch/pongo2"
"github.com/gorilla/sessions"
)
type httpHelperFunc func(res http.ResponseWriter, r *http.Request, session *sessions.Session, ctx *pongo2.Context) (*string, error)
func httpHelper(f httpHelperFunc) http.HandlerFunc {
return func(res http.ResponseWriter, r *http.Request) {
sess, _ := cookieStore.Get(r, "cloudkeys-go")
ctx := pongo2.Context{}
if errFlash := sess.Flashes("error"); len(errFlash) > 0 {
ctx["error"] = errFlash[0].(string)
}
template, err := f(res, r, sess, &ctx)
if err != nil {
http.Error(res, "An error ocurred.", http.StatusInternalServerError)
fmt.Printf("ERR: %s\n", err)
return
}
if template != nil {
// Postponed until https://github.com/flosch/pongo2/issues/68
//
// tplsrc, err := Asset("templates/" + *template)
// if err != nil {
// fmt.Printf("ERR: Could not find template '%s'\n", *template)
// http.Error(res, "An error ocurred.", http.StatusInternalServerError)
// return
// }
ts := pongo2.NewSet("frontend")
ts.SetBaseDirectory("templates")
tpl, err := ts.FromFile(*template)
if err != nil {
fmt.Printf("ERR: Could not parse template '%s': %s\n", *template, err)
http.Error(res, "An error ocurred.", http.StatusInternalServerError)
return
}
out, err := tpl.Execute(ctx)
if err != nil {
fmt.Printf("ERR: Unable to execute template '%s': %s\n", *template, err)
http.Error(res, "An error ocurred.", http.StatusInternalServerError)
return
}
res.Write([]byte(out))
}
}
}
func simpleTemplateOutput(template string) httpHelperFunc {
return func(res http.ResponseWriter, r *http.Request, session *sessions.Session, ctx *pongo2.Context) (*string, error) {
return &template, nil
}
}
func stringPointer(s string) *string {
return &s
}