Serge Bazanski | 56c888b | 2021-05-30 21:48:58 +0000 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 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). |
| 17 | func 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 | |
| 42 | var ( |
| 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. |
| 49 | func 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 |
| 56 | func (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 |
| 61 | func (s *service) handleAboutEn(w http.ResponseWriter, r *http.Request) { |
| 62 | render(w, tmplAboutEn, nil) |
| 63 | } |