Helper to render template
This commit is contained in:
parent
a247856a24
commit
7d18008d80
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user