Refactor server: use render func for templates
This commit is contained in:
parent
ca4e448f82
commit
a7bd1478bf
6 changed files with 60 additions and 39 deletions
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue