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
# How gists.kejadlen.dev works

When I realized I wanted a place to post random snippets, I explored
self-hosted pastebin options before stumbling across a far simpler alternative
using Caddy's [`templates` directive][templates-directive].

[templates-directive]: https://caddyserver.com/docs/caddyfile/directives/templates

Abridged Caddyfile (with my [gists repo][gists-repo] mounted at `/data/gists`):

[gists-repo]: https://quire.kejadlen.dev/gists/tree

```
gists.kejadlen.dev {
	root * /data/gists
	encode zstd gzip

	handle {
		rewrite * /_render.html
		templates
		file_server
	}
}
```

And the abridged `_render.html` in the `gists` repo:

```
{{$path := .OriginalReq.URL.Path -}}
{{$file := printf "%s.md" (trimSuffix "/" $path) -}}
{{if not (fileExists $file)}}{{httpError 404}}{{end -}}
{{/* readFile, not include: include evaluates the .md as a template, so a
     document quoting this file's own source recurses until caddy OOMs. */ -}}
{{$doc := readFile $file | splitFrontMatter -}}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>{{default (trimSuffix ".md" $file) $doc.Meta.title}} — kejadlen.dev</title>
{{with $doc.Meta.description}}<meta name="description" content="{{.}}">
{{end}}<script>try{var t=localStorage.getItem("theme");if(t)document.documentElement.dataset.theme=t}catch(e){}</script>
<style>
(elided)
</style>
</head>
<body>
<button id="theme" hidden></button>
<article>
{{$doc.Body | markdown}}
</article>
</body>
</html>
```