1
0
mirror of https://github.com/Luzifer/cloudkeys-go.git synced 2024-09-19 23:52:57 +00:00
cloudkeys-go/httpHelper.go

67 lines
1.8 KiB
Go
Raw Normal View History

2015-07-29 07:01:23 +00:00
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 {
2015-07-29 07:49:23 +00:00
http.Error(res, "An error ocurred.", http.StatusInternalServerError)
2015-07-29 07:01:23 +00:00
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
}
}
2015-07-29 07:49:23 +00:00
func stringPointer(s string) *string {
2015-07-29 07:01:23 +00:00
return &s
}