From e17e186c1d55e70a689d61fb957f0343a00d741f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lilian=20J=C3=B3nsd=C3=B3ttir?= Date: Mon, 22 Jan 2024 21:55:03 -0800 Subject: [PATCH] refactor handlers - repeat less - lay framework for adding more pages --- internal/handlers/handlers.go | 40 ++++++++++++++++++++++++++++------- internal/render/render.go | 3 +-- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index 8edca53..ed6a43e 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -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) + } +} diff --git a/internal/render/render.go b/internal/render/render.go index 6afb704..71b109a 100644 --- a/internal/render/render.go +++ b/internal/render/render.go @@ -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