blob: 59f948e944bf6b4fb5f36b5b2c3a2177422247a4 [file] [log] [blame]
package main
import (
"fmt"
"html/template"
"net/http"
"github.com/golang/glog"
"code.hackerspace.pl/hscloud/hswaw/site/templates"
)
// parseTemplates parses a set of templates from
// //hswaw/site/templates/$name.html into a Go HTML template. Typical Go text
// templating ordering behaviour applies (this basically replicates
// template.ParseFiles, but for statically embedded files instead).
func parseTemplates(names ...string) (*template.Template, error) {
if len(names) == 0 {
return nil, fmt.Errorf("at least one template must be given")
}
var t *template.Template
for _, n := range names {
path := fmt.Sprintf("hswaw/site/templates/%s.html", n)
data, ok := templates.Data[path]
if !ok {
return nil, fmt.Errorf("template %q (%s) not found", n, path)
}
s := string(data)
if t == nil {
t = template.New(n)
}
_, err := t.Parse(s)
if err != nil {
return nil, fmt.Errorf("template %q could not be parsed: %w", n, err)
}
}
return t, nil
}
var (
tmplIndex = template.Must(parseTemplates("index"))
)
// render attempts to render a given Go template with data into the HTTP
// response writer, and logs a warning if anything goes wrong.
func render(w http.ResponseWriter, t *template.Template, data interface{}) {
if err := t.Execute(w, data); err != nil {
glog.Warningf("Rendering %v failed: %v", t, err)
}
}
// handleIndex handles rendering the main page at /.
func (s *service) handleIndex(w http.ResponseWriter, r *http.Request) {
render(w, tmplIndex, map[string]interface{}{
"Entries": s.getFeeds(),
})
}