/
main.go
48 lines (41 loc) · 1.01 KB
/
main.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
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"net/http"
"text/template"
"log"
)
var config struct {
liveTemplates bool
}
func init() {
log.Print("init()")
config.liveTemplates = true
}
func main() {
log.Print("main()")
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/", homeHandler)
log.Print("starting")
http.ListenAndServe(":8080", nil)
log.Print("started")
}
func homeHandler(w http.ResponseWriter, req *http.Request) {
renderTemplate(w, "home")
}
func compileTemplates() *template.Template {
return template.Must(template.ParseGlob("./templates/*.html"))
}
// Precompile the templates
var precompiledTemplates = compileTemplates()
func renderTemplate(w http.ResponseWriter, tmpl string) {
var templates *template.Template
if config.liveTemplates {
templates = compileTemplates()
} else {
templates = precompiledTemplates
}
err := templates.ExecuteTemplate(w, tmpl+".html", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}