From 7d18008d808dd08927b37d8dbadb0e5621794156 Mon Sep 17 00:00:00 2001 From: Valentin Brandl Date: Sun, 20 Apr 2025 00:27:16 +0200 Subject: [PATCH] Helper to render template --- handlers/index.go | 16 ++++------------ handlers/not_found.go | 17 +++++------------ handlers/template.go | 25 +++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 24 deletions(-) diff --git a/handlers/index.go b/handlers/index.go index 42d78dd..a5ff491 100644 --- a/handlers/index.go +++ b/handlers/index.go @@ -7,16 +7,8 @@ import ( ) func (app *Application) Index(w http.ResponseWriter, r *http.Request) { - l := hlog.FromRequest(r) - l.Info().Msg("Index") - - reqId := RequestID(r) - - err := indexTemplate.Execute(w, templateData{ - RequestID: reqId, - }) - if err != nil { - l.Error().Err(err).Msg("error executing template") - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - } + renderTemplate(*indexTemplate, nil, func(w http.ResponseWriter, r *http.Request) { + l := hlog.FromRequest(r) + l.Info().Msg("Index") + })(w, r) } diff --git a/handlers/not_found.go b/handlers/not_found.go index 7f949d6..00136ff 100644 --- a/handlers/not_found.go +++ b/handlers/not_found.go @@ -7,17 +7,10 @@ import ( ) func (app *Application) NotFound(w http.ResponseWriter, r *http.Request) { - l := hlog.FromRequest(r) - l.Info().Msg("Not found") + renderTemplate(*notFoundTemplate, nil, func(w http.ResponseWriter, r *http.Request) { + l := hlog.FromRequest(r) + l.Info().Msg("Not found") - reqId := RequestID(r) - w.WriteHeader(http.StatusNotFound) - - err := notFoundTemplate.Execute(w, templateData{ - RequestID: reqId, - }) - if err != nil { - l.Error().Err(err).Msg("error executing template") - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - } + w.WriteHeader(http.StatusNotFound) + })(w, r) } diff --git a/handlers/template.go b/handlers/template.go index 41e3f9b..f759332 100644 --- a/handlers/template.go +++ b/handlers/template.go @@ -2,8 +2,10 @@ package handlers import ( "html/template" + "net/http" "git.vbrandl.net/vbrandl/go-web-template/assets" + "github.com/rs/zerolog/hlog" ) var indexTemplate *template.Template @@ -28,3 +30,26 @@ func (app *Application) ParseTemplates() error { return nil } + +func renderTemplate(template template.Template, data map[any]any, additionalHandling http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + l := hlog.FromRequest(r) + + if data == nil { + data = make(map[any]any) + } + + reqId := RequestID(r) + data["RequestID"] = reqId + + if additionalHandling != nil { + additionalHandling(w, r) + } + + err := template.Execute(w, data) + if err != nil { + l.Error().Err(err).Msg("error rendering template") + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + } +}