2015-07-29 07:01:23 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/flosch/pongo2"
|
|
|
|
"github.com/gorilla/sessions"
|
2017-12-24 19:10:43 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2015-07-29 07:01:23 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
2017-12-24 19:10:43 +00:00
|
|
|
log.WithError(err).Error("Unable to execute template")
|
2015-07-29 07:01:23 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if template != nil {
|
|
|
|
ts := pongo2.NewSet("frontend")
|
|
|
|
ts.SetBaseDirectory("templates")
|
|
|
|
tpl, err := ts.FromFile(*template)
|
|
|
|
if err != nil {
|
2017-12-24 19:10:43 +00:00
|
|
|
log.WithError(err).WithFields(log.Fields{
|
|
|
|
"template": *template,
|
|
|
|
}).Error("Could not parse template")
|
2015-07-29 07:01:23 +00:00
|
|
|
http.Error(res, "An error ocurred.", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
out, err := tpl.Execute(ctx)
|
|
|
|
if err != nil {
|
2017-12-24 19:10:43 +00:00
|
|
|
log.WithError(err).WithFields(log.Fields{
|
|
|
|
"template": *template,
|
|
|
|
}).Error("Could not execute template")
|
2015-07-29 07:01:23 +00:00
|
|
|
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
|
|
|
|
}
|