ui.go (view raw)
1package main
2
3import (
4 "embed"
5 "fmt"
6 "html/template"
7 "log"
8 "net/http"
9 "time"
10)
11
12func calcYear(currentYear, year uint) uint {
13 return currentYear - year
14}
15
16func padZero(i uint) string {
17 return fmt.Sprintf("%02d", i)
18}
19
20var (
21 //go:embed templates/index.html
22 templates embed.FS
23 indexTemplate *template.Template
24 funcMap = template.FuncMap{
25 "padZero": padZero,
26 "calcYear": calcYear,
27 }
28)
29
30func ParseTemplates() {
31 var err error
32 indexTemplate, err = template.New("index.html").Funcs(funcMap).ParseFS(templates, "templates/index.html")
33 if err != nil {
34 log.Fatal("Could not parse index template")
35 return
36 }
37}
38
39func ShowIndexPage(w http.ResponseWriter, r *http.Request) {
40 var occurrences []Occurrence
41 db.Order("month, day, name").Find(&occurrences)
42
43 data := struct {
44 Occurrences []Occurrence
45 CurrentYear uint
46 }{
47 Occurrences: occurrences,
48 CurrentYear: uint(time.Now().Year()),
49 }
50
51 err := indexTemplate.Execute(w, data)
52 if err != nil {
53 log.Println(err.Error())
54 http.Error(w, "Internal Server Error", http.StatusInternalServerError)
55 }
56}