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")) |
Serge Bazanski | 3c9092a | 2021-05-30 23:15:20 +0000 | [diff] [blame^] | 45 | tmplMain = template.Must(parseTemplates("basic", "main")) |
Serge Bazanski | 56c888b | 2021-05-30 21:48:58 +0000 | [diff] [blame] | 46 | ) |
| 47 | |
| 48 | // render attempts to render a given Go template with data into the HTTP |
| 49 | // response writer, and logs a warning if anything goes wrong. |
| 50 | func render(w http.ResponseWriter, t *template.Template, data interface{}) { |
| 51 | if err := t.Execute(w, data); err != nil { |
| 52 | glog.Warningf("Rendering %v failed: %v", t, err) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // handleAbout handles rendering the about page at /about |
| 57 | func (s *service) handleAbout(w http.ResponseWriter, r *http.Request) { |
| 58 | render(w, tmplAbout, nil) |
| 59 | } |
| 60 | |
| 61 | // handleAboutEn handles rendering the about page at /about_en |
| 62 | func (s *service) handleAboutEn(w http.ResponseWriter, r *http.Request) { |
| 63 | render(w, tmplAboutEn, nil) |
| 64 | } |
Serge Bazanski | 3c9092a | 2021-05-30 23:15:20 +0000 | [diff] [blame^] | 65 | |
| 66 | // handleMain handles rendering the main page at /. |
| 67 | func (s *service) handleMain(w http.ResponseWriter, r *http.Request) { |
| 68 | render(w, tmplMain, map[string]interface{}{ |
| 69 | "Entries": s.getFeeds(), |
| 70 | }) |
| 71 | } |