blob: 09755b2d50be20f71c88e841b1a899088a5f2dce [file] [log] [blame]
Serge Bazanski56c888b2021-05-30 21:48:58 +00001package main
2
3import (
Serge Bazanski11b276d2021-07-11 23:49:55 +00004 "encoding/json"
Serge Bazanski56c888b2021-05-30 21:48:58 +00005 "fmt"
6 "html/template"
7 "net/http"
8
9 "github.com/golang/glog"
10
11 "code.hackerspace.pl/hscloud/hswaw/site/templates"
12)
13
14// parseTemplates parses a set of templates from
15// //hswaw/site/templates/$name.html into a Go HTML template. Typical Go text
16// templating ordering behaviour applies (this basically replicates
17// template.ParseFiles, but for statically embedded files instead).
18func parseTemplates(names ...string) (*template.Template, error) {
19 if len(names) == 0 {
20 return nil, fmt.Errorf("at least one template must be given")
21 }
22
23 var t *template.Template
24 for _, n := range names {
25 path := fmt.Sprintf("hswaw/site/templates/%s.html", n)
26 data, ok := templates.Data[path]
27 if !ok {
28 return nil, fmt.Errorf("template %q (%s) not found", n, path)
29 }
30 s := string(data)
31
32 if t == nil {
33 t = template.New(n)
34 }
35 _, err := t.Parse(s)
36 if err != nil {
37 return nil, fmt.Errorf("template %q could not be parsed: %w", n, err)
38 }
39 }
40 return t, nil
41}
42
43var (
Serge Bazanski4d7b2f02021-05-31 22:33:51 +000044 tmplIndex = template.Must(parseTemplates("index"))
Serge Bazanski56c888b2021-05-30 21:48:58 +000045)
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
Serge Bazanski4d7b2f02021-05-31 22:33:51 +000055// handleIndex handles rendering the main page at /.
56func (s *service) handleIndex(w http.ResponseWriter, r *http.Request) {
Serge Bazanskid2271de2021-07-11 21:26:37 +000057 ctx := r.Context()
58
59 atStatus, atError := getAt(ctx)
60
Serge Bazanski4d7b2f02021-05-31 22:33:51 +000061 render(w, tmplIndex, map[string]interface{}{
Serge Bazanskid2271de2021-07-11 21:26:37 +000062 "Entries": s.getFeeds(),
63 "AtStatus": atStatus,
64 "AtError": atError,
Serge Bazanski3c9092a2021-05-30 23:15:20 +000065 })
66}
Serge Bazanski11b276d2021-07-11 23:49:55 +000067
68func (s *service) handleSpaceAPI(w http.ResponseWriter, r *http.Request) {
69 ctx := r.Context()
70 w.Header().Set("Content-Type", "application/json")
71 json.NewEncoder(w).Encode(generateSpaceAPIResponse(ctx))
72}