refactor handlers
- repeat less - lay framework for adding more pages
This commit is contained in:
parent
4f97975986
commit
e17e186c1d
|
@ -2,6 +2,7 @@ package handlers
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.burning.moe/celediel/burning.moe/internal/config"
|
||||
"git.burning.moe/celediel/burning.moe/internal/models"
|
||||
|
@ -21,18 +22,12 @@ var Handlers = []Handler{
|
|||
// /about
|
||||
{
|
||||
Handles: "/about",
|
||||
Handler: func(w http.ResponseWriter, r *http.Request) {
|
||||
app.Logger.Info("Got request for about page.")
|
||||
render.RenderTemplate(w, "about.page", &models.TemplateData{})
|
||||
},
|
||||
Handler: makeBasicHandler("about"),
|
||||
},
|
||||
// / comes last
|
||||
{
|
||||
Handles: "/",
|
||||
Handler: func(w http.ResponseWriter, r *http.Request) {
|
||||
app.Logger.Info("Got request for homepage.")
|
||||
render.RenderTemplate(w, "home.page", &models.TemplateData{})
|
||||
},
|
||||
Handler: makeBasicHandler("home"),
|
||||
},
|
||||
}
|
||||
|
||||
|
@ -40,3 +35,32 @@ var Handlers = []Handler{
|
|||
func Initialise(a *config.AppConfig) {
|
||||
app = a
|
||||
}
|
||||
|
||||
// makeBasicTemplateData creates a blank TemplateData containing only the
|
||||
// time the related template was generated
|
||||
func makeBasicTemplateData(name string) models.TemplateData {
|
||||
var strMap map[string]string
|
||||
if _, ok := app.TemplateCache.Cache[name]; ok {
|
||||
strMap = map[string]string{
|
||||
"GeneratedAt": app.TemplateCache.Cache[name].GeneratedAt.Format(time.UnixDate),
|
||||
}
|
||||
} else {
|
||||
strMap = make(map[string]string)
|
||||
}
|
||||
|
||||
templateData := models.TemplateData{
|
||||
StringMap: strMap,
|
||||
}
|
||||
return templateData
|
||||
}
|
||||
|
||||
// makeBasicHandler creates a basic handler that builds from a .page.tmpl
|
||||
// file, and sends only the time the template was generated as TemplateData
|
||||
func makeBasicHandler(name string) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
app.Logger.Infof("Got request for %s page", name)
|
||||
pageName := name + ".page.tmpl"
|
||||
templateData := makeBasicTemplateData(pageName)
|
||||
render.RenderTemplate(w, pageName, &templateData)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -79,8 +79,7 @@ func GenerateNewTemplateCache() (models.TemplateCache, error) {
|
|||
}
|
||||
|
||||
// RenderTemplate renders requested template (t), pulling from cache.
|
||||
func RenderTemplate(w http.ResponseWriter, t string, data *models.TemplateData) {
|
||||
filename := t + ".tmpl"
|
||||
func RenderTemplate(w http.ResponseWriter, filename string, data *models.TemplateData) {
|
||||
var cache models.TemplateCache
|
||||
if app.UseCache {
|
||||
cache = app.TemplateCache
|
||||
|
|
Loading…
Reference in a new issue