blob: ae623220864e367f9ebe6275e070ec795313d256 [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 (
43 tmplAbout = template.Must(parseTemplates("basic", "about"))
44 tmplAboutEn = template.Must(parseTemplates("basic", "about_en"))
45)
46
47// render attempts to render a given Go template with data into the HTTP
48// response writer, and logs a warning if anything goes wrong.
49func render(w http.ResponseWriter, t *template.Template, data interface{}) {
50 if err := t.Execute(w, data); err != nil {
51 glog.Warningf("Rendering %v failed: %v", t, err)
52 }
53}
54
55// handleAbout handles rendering the about page at /about
56func (s *service) handleAbout(w http.ResponseWriter, r *http.Request) {
57 render(w, tmplAbout, nil)
58}
59
60// handleAboutEn handles rendering the about page at /about_en
61func (s *service) handleAboutEn(w http.ResponseWriter, r *http.Request) {
62 render(w, tmplAboutEn, nil)
63}