xonecas.io
8356
Wx

www-xonecas-io / files

www-xonecas-io / cmd / site / devnotes.go

992 bytes
1package main
2
3import (
4	"bytes"
5	_ "embed"
6	"net/http"
7	"net/http/httptest"
8	"strings"
9)
10
11// devnotesJS is the output of `rat-king devnotes script`: Ctrl+click a page to file a Rats ticket.
12//
13//go:embed devnotes.js
14var devnotesJS []byte
15
16// devnotes serves next with the devnotes script inlined into every page a browser loads. Pages end in a slash.
17// htmx requests are left alone: the script from the first page keeps running when htmx swaps the body.
18func devnotes(next http.Handler) http.Handler {
19	tag := append(append([]byte("<script>"), devnotesJS...), "</script></body>"...)
20	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
21		if r.Header.Get("HX-Request") != "" || !strings.HasSuffix(r.URL.Path, "/") {
22			next.ServeHTTP(w, r)
23			return
24		}
25		rec := httptest.NewRecorder()
26		next.ServeHTTP(rec, r)
27		for k, v := range rec.Header() {
28			w.Header()[k] = v
29		}
30		w.WriteHeader(rec.Code)
31		w.Write(bytes.Replace(rec.Body.Bytes(), []byte("</body>"), tag, 1))
32	})
33}