Helper to render template
Some checks failed
Build / build (push) Successful in 1m22s
Lint / lint (push) Failing after 1m51s

This commit is contained in:
Valentin Brandl 2025-04-20 00:27:16 +02:00
parent a247856a24
commit 7d18008d80
Signed by: vbrandl
GPG Key ID: 7FB009175885FC76
3 changed files with 34 additions and 24 deletions

View File

@ -7,16 +7,8 @@ import (
) )
func (app *Application) Index(w http.ResponseWriter, r *http.Request) { func (app *Application) Index(w http.ResponseWriter, r *http.Request) {
l := hlog.FromRequest(r) renderTemplate(*indexTemplate, nil, func(w http.ResponseWriter, r *http.Request) {
l.Info().Msg("Index") l := hlog.FromRequest(r)
l.Info().Msg("Index")
reqId := RequestID(r) })(w, 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)
}
} }

View File

@ -7,17 +7,10 @@ import (
) )
func (app *Application) NotFound(w http.ResponseWriter, r *http.Request) { func (app *Application) NotFound(w http.ResponseWriter, r *http.Request) {
l := hlog.FromRequest(r) renderTemplate(*notFoundTemplate, nil, func(w http.ResponseWriter, r *http.Request) {
l.Info().Msg("Not found") l := hlog.FromRequest(r)
l.Info().Msg("Not found")
reqId := RequestID(r) w.WriteHeader(http.StatusNotFound)
w.WriteHeader(http.StatusNotFound) })(w, r)
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)
}
} }

View File

@ -2,8 +2,10 @@ package handlers
import ( import (
"html/template" "html/template"
"net/http"
"git.vbrandl.net/vbrandl/go-web-template/assets" "git.vbrandl.net/vbrandl/go-web-template/assets"
"github.com/rs/zerolog/hlog"
) )
var indexTemplate *template.Template var indexTemplate *template.Template
@ -28,3 +30,26 @@ func (app *Application) ParseTemplates() error {
return nil 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)
}
}
}