Check for invalid templates at server startup
This commit is contained in:
43
views/template.go
Normal file
43
views/template.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package views
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Template struct {
|
||||
htmlTpl *template.Template
|
||||
}
|
||||
|
||||
func (t Template) Execute(w http.ResponseWriter, data interface{}) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf8")
|
||||
err := t.htmlTpl.Execute(w, data)
|
||||
if err != nil {
|
||||
log.Printf("Error executing template: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
func (t Template) ExecuteWriter(w io.Writer, data interface{}) error {
|
||||
return t.htmlTpl.Execute(w, data)
|
||||
}
|
||||
|
||||
func FromFile(filepath string) (Template, error) {
|
||||
tpl, err := template.ParseFiles(filepath)
|
||||
if err != nil {
|
||||
return Template{}, fmt.Errorf("Error parsing template: %v", err)
|
||||
}
|
||||
return Template{
|
||||
htmlTpl: tpl,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func Must(t Template, err error) Template {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return t
|
||||
}
|
||||
Reference in New Issue
Block a user