-
Notifications
You must be signed in to change notification settings - Fork 0
/
templateHandler.go
37 lines (31 loc) · 1.02 KB
/
templateHandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package piplayer
import (
"html/template"
"log"
"net/http"
"path/filepath"
)
// TemplateHandler handles rendering html templates
type TemplateHandler struct {
// once sync.Once
filename string
templ *template.Template
data map[string]interface{}
}
const templateDir = "pkg/piplayer/templates"
// NewTemplateHandler returns a new template handler for a specific page
func NewTemplateHandler(filename string) TemplateHandler {
return TemplateHandler{filename: filename}
}
// ServeHTTP handles HTTP requests for the templates
func (t *TemplateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// once keeps track of which of these anonymous functions have already been called,
// and stores their result. If they are called again it just returns the stored result.
// t.once.Do(func(){
t.templ = template.Must(template.ParseFiles(filepath.Join(templateDir, t.filename)))
// // })
err := t.templ.Execute(w, t.data)
if err != nil {
log.Println("Error trying to render page: ", t.filename, err)
}
}