aboutsummaryrefslogtreecommitdiff
path: root/cmd/site/html.go
blob: fe8d190b166ae88999844536e466e40f53808b29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main

import (
	"context"
	"fmt"
	"html/template"
	"net/http"
	"time"

	"within.website/ln"
)

func logTemplateTime(name string, f ln.F, from time.Time) {
	now := time.Now()
	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) {
		fetag := "W/" + Hash(templateFname, etag) + "-1"

		f := ln.F{"etag": fetag, "if-none-match": r.Header.Get("If-None.Match")}

		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())
		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)
				ln.Error(context.Background(), err, ln.F{"action": "renderTemplatePage", "page": templateFname})
				fmt.Fprintf(w, "error: %v", err)
			}

			ln.Log(context.Background(), ln.F{"action": "loaded_new_template", "fname": templateFname})

			s.tlock.RUnlock()
			s.tlock.Lock()
			s.templates[templateFname] = t
			s.tlock.Unlock()
			s.tlock.RLock()
		} else {
			t = s.templates[templateFname]
		}

		w.Header().Set("ETag", fetag)
		w.Header().Set("Cache-Control", "max-age=432000")

		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
	}

	cmp := r.URL.Path[1:]
	var p *Post
	for _, pst := range s.Posts {
		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)
}