blob: 59f948e944bf6b4fb5f36b5b2c3a2177422247a4 [file] [log] [blame]
Serge Bazanski56c888b2021-05-30 21:48:58 +00001package main
2
3import (
4 "fmt"
5 "html/template"
6 "net/http"
7
8 "github.com/golang/glog"
9
10 "code.hackerspace.pl/hscloud/hswaw/site/templates"
11)
12
13// parseTemplates parses a set of templates from
14// //hswaw/site/templates/$name.html into a Go HTML template. Typical Go text
15// templating ordering behaviour applies (this basically replicates
16// template.ParseFiles, but for statically embedded files instead).
17func parseTemplates(names ...string) (*template.Template, error) {
18 if len(names) == 0 {
19 return nil, fmt.Errorf("at least one template must be given")
20 }
21
22 var t *template.Template
23 for _, n := range names {
24 path := fmt.Sprintf("hswaw/site/templates/%s.html", n)
25 data, ok := templates.Data[path]
26 if !ok {
27 return nil, fmt.Errorf("template %q (%s) not found", n, path)
28 }
29 s := string(data)
30
31 if t == nil {
32 t = template.New(n)
33 }
34 _, err := t.Parse(s)
35 if err != nil {
36 return nil, fmt.Errorf("template %q could not be parsed: %w", n, err)
37 }
38 }
39 return t, nil
40}
41
42var (
Serge Bazanski4d7b2f02021-05-31 22:33:51 +000043 tmplIndex = template.Must(parseTemplates("index"))
Serge Bazanski56c888b2021-05-30 21:48:58 +000044)
45
46// render attempts to render a given Go template with data into the HTTP
47// response writer, and logs a warning if anything goes wrong.
48func render(w http.ResponseWriter, t *template.Template, data interface{}) {
49 if err := t.Execute(w, data); err != nil {
50 glog.Warningf("Rendering %v failed: %v", t, err)
51 }
52}
53
Serge Bazanski4d7b2f02021-05-31 22:33:51 +000054// handleIndex handles rendering the main page at /.
55func (s *service) handleIndex(w http.ResponseWriter, r *http.Request) {
56 render(w, tmplIndex, map[string]interface{}{
Serge Bazanski3c9092a2021-05-30 23:15:20 +000057 "Entries": s.getFeeds(),
58 })
59}