xesite/cmd/site/html.go

83 lines
2.1 KiB
Go
Raw Normal View History

package main
import (
2017-12-13 18:49:13 +00:00
"context"
"fmt"
"html/template"
"net/http"
2019-03-21 15:05:23 +00:00
"path/filepath"
"time"
2019-03-21 15:05:23 +00:00
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
2019-01-12 17:05:00 +00:00
"within.website/ln"
)
2019-01-26 14:38:22 +00:00
func logTemplateTime(name string, f ln.F, from time.Time) {
now := time.Now()
2019-01-26 14:38:22 +00:00
ln.Log(context.Background(), f, ln.F{"action": "template_rendered", "dur": now.Sub(from).String(), "name": name})
}
func (s *Site) renderTemplatePage(templateFname string, data interface{}) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2019-01-26 14:38:22 +00:00
fetag := "W/" + Hash(templateFname, etag) + "-1"
2019-03-21 14:55:32 +00:00
f := ln.F{"etag": fetag, "if_none_match": r.Header.Get("If-None-Match")}
2019-01-26 14:38:22 +00:00
if r.Header.Get("If-None-Match") == fetag {
http.Error(w, "Cached data OK", http.StatusNotModified)
ln.Log(r.Context(), f, ln.Info("Cache hit"))
return
}
defer logTemplateTime(templateFname, f, time.Now())
var t *template.Template
var err error
2019-03-21 14:55:32 +00:00
t, err = template.ParseFiles("templates/base.html", "templates/"+templateFname)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
ln.Error(context.Background(), err, ln.F{"action": "renderTemplatePage", "page": templateFname})
fmt.Fprintf(w, "error: %v", err)
}
2019-01-26 14:38:22 +00:00
w.Header().Set("ETag", fetag)
w.Header().Set("Cache-Control", "max-age=432000")
err = t.Execute(w, data)
if err != nil {
panic(err)
}
})
}
2019-03-21 15:05:23 +00:00
var postView = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "posts_viewed",
Help: "The number of views per post",
}, []string{"base"})
func (s *Site) showPost(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/blog/" {
http.Redirect(w, r, "/blog", http.StatusSeeOther)
return
}
2018-12-10 16:14:00 +00:00
cmp := r.URL.Path[1:]
var p *Post
for _, pst := range s.Posts {
2018-12-10 16:14:00 +00:00
if pst.Link == cmp {
p = pst
}
}
if p == nil {
w.WriteHeader(http.StatusNotFound)
s.renderTemplatePage("error.html", "no such post found: "+r.RequestURI).ServeHTTP(w, r)
return
}
s.renderTemplatePage("blogpost.html", p).ServeHTTP(w, r)
2019-03-21 15:05:23 +00:00
postView.With(prometheus.Labels{"base": filepath.Base(p.Link)}).Inc()
}