Refactor server: use render func for templates

This commit is contained in:
bronku 2025-03-22 23:46:33 +01:00
parent ca4e448f82
commit a7bd1478bf
6 changed files with 60 additions and 39 deletions

View file

@ -3,6 +3,7 @@ package server
import (
"embed"
"html/template"
"net/http"
)
//go:embed templates/*
@ -13,3 +14,18 @@ func (h *Server) loadTemplates() error {
h.tmpl, err = template.ParseFS(templates, "templates/*")
return err
}
func (s *Server) render(fetch fetcher, templateName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "text/html")
data, err := fetch(r)
if err != nil {
errorPage(err, http.StatusInternalServerError).ServeHTTP(w, r)
return
}
err = s.tmpl.ExecuteTemplate(w, templateName, data)
if err != nil {
errorPage(err, http.StatusInternalServerError).ServeHTTP(w, r)
}
}
}