Valentin Brandl 7d18008d80
Some checks failed
Build / build (push) Successful in 1m22s
Lint / lint (push) Failing after 1m51s
Helper to render template
2025-04-20 00:27:16 +02:00

56 lines
1.2 KiB
Go

package handlers
import (
"html/template"
"net/http"
"git.vbrandl.net/vbrandl/go-web-template/assets"
"github.com/rs/zerolog/hlog"
)
var indexTemplate *template.Template
var notFoundTemplate *template.Template
type templateData struct {
RequestID string
}
func (app *Application) ParseTemplates() error {
t, err := template.ParseFS(assets.Templates, "public/html/index.html", "public/html/navbar.tmpl", "public/html/footer.tmpl")
if err != nil {
return err
}
indexTemplate = t
t, err = template.ParseFS(assets.Templates, "public/html/notFound.html", "public/html/navbar.tmpl", "public/html/footer.tmpl")
if err != nil {
return err
}
notFoundTemplate = t
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)
}
}
}