2017-05-20 22:06:30 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-12-13 18:49:13 +00:00
|
|
|
"context"
|
2017-05-20 22:06:30 +00:00
|
|
|
"fmt"
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2019-01-12 17:05:00 +00:00
|
|
|
"within.website/ln"
|
2017-05-20 22:06:30 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func logTemplateTime(name string, from time.Time) {
|
|
|
|
now := time.Now()
|
2017-12-13 18:49:13 +00:00
|
|
|
ln.Log(context.Background(), ln.F{"action": "template_rendered", "dur": now.Sub(from).String(), "name": name})
|
2017-05-20 22:06:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Site) renderTemplatePage(templateFname string, data interface{}) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
defer logTemplateTime(templateFname, time.Now())
|
|
|
|
s.tlock.RLock()
|
|
|
|
defer s.tlock.RUnlock()
|
|
|
|
|
|
|
|
var t *template.Template
|
|
|
|
var err error
|
|
|
|
|
|
|
|
if s.templates[templateFname] == nil {
|
|
|
|
t, err = template.ParseFiles("templates/base.html", "templates/"+templateFname)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2017-12-13 18:49:13 +00:00
|
|
|
ln.Error(context.Background(), err, ln.F{"action": "renderTemplatePage", "page": templateFname})
|
2017-05-20 22:06:30 +00:00
|
|
|
fmt.Fprintf(w, "error: %v", err)
|
|
|
|
}
|
|
|
|
|
2017-12-13 18:49:13 +00:00
|
|
|
ln.Log(context.Background(), ln.F{"action": "loaded_new_template", "fname": templateFname})
|
2017-05-20 22:06:30 +00:00
|
|
|
|
|
|
|
s.tlock.RUnlock()
|
|
|
|
s.tlock.Lock()
|
|
|
|
s.templates[templateFname] = t
|
|
|
|
s.tlock.Unlock()
|
|
|
|
s.tlock.RLock()
|
|
|
|
} else {
|
|
|
|
t = s.templates[templateFname]
|
|
|
|
}
|
|
|
|
|
|
|
|
err = t.Execute(w, data)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
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:]
|
2017-05-20 22:06:30 +00:00
|
|
|
var p *Post
|
|
|
|
for _, pst := range s.Posts {
|
2018-12-10 16:14:00 +00:00
|
|
|
if pst.Link == cmp {
|
2017-05-20 22:06:30 +00:00
|
|
|
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)
|
|
|
|
}
|