-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.go
More file actions
216 lines (188 loc) · 5.6 KB
/
handler.go
File metadata and controls
216 lines (188 loc) · 5.6 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package ukuleleweb
import (
"embed"
"flag"
"html/template"
"io"
"log"
"net/http"
"regexp"
"strings"
"sync"
"unicode"
"github.com/peterbourgon/diskv/v3"
)
var (
cssURL = flag.String("brand.css_url", "/static/style.css", "The URL for the CSS file")
faviconURL = flag.String("brand.favicon_url", "/static/favicon.svg", "The URL for the favicon")
)
//go:embed templates/*
var templateFiles embed.FS
var (
baseTmpl = template.Must(template.New("layout").ParseFS(templateFiles, "templates/base/*.html"))
PageTmpl = template.Must(template.Must(baseTmpl.Clone()).ParseFS(templateFiles, "templates/contents/page.html"))
EditTmpl = template.Must(template.Must(baseTmpl.Clone()).ParseFS(templateFiles, "templates/contents/edit.html"))
)
type pageValues struct {
Title string
PageName string
HTMLContent template.HTML
SourceContent string
Error string
ReverseLinks []string
FaviconURL string
CSSURL string
}
type PageHandler struct {
MainPage string
D *diskv.Diskv
// A cached version of the reverse links.
revLinksMu sync.RWMutex
revLinks map[string][]string
}
func (h *PageHandler) serveEdit(w http.ResponseWriter, r *http.Request) {
pageName := r.PathValue("pageName")
if !isPageName(pageName) {
http.Error(w, "Invalid page name", http.StatusNotFound)
return
}
content := contentValue(r)
if content == "" {
content = h.D.ReadString(pageName)
}
// Search engines do not need to index the edit page.
w.Header().Set("X-Robots-Tag", "noindex")
pv := h.newPageValues(pageName)
pv.SourceContent = content
if err := EditTmpl.Execute(w, pv); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (h *PageHandler) serveSave(w http.ResponseWriter, r *http.Request) {
pageName := r.PathValue("pageName")
if !isPageName(pageName) {
http.Error(w, "Invalid page name", http.StatusNotFound)
return
}
content := contentValue(r)
err := h.D.WriteString(pageName, content)
if err == nil {
// TODO: Potentially do it in a background job?
h.recalculateRevLinks()
http.Redirect(w, r, "/"+pageName, http.StatusFound)
return
}
// On error, render edit form with the error message.
log.Printf("ERROR: diskv.WriteString(%q, ...): %v\n", pageName, err)
w.WriteHeader(http.StatusInternalServerError)
pv := h.newPageValues(pageName)
pv.Error = "Internal error writing page"
pv.SourceContent = content
if err := EditTmpl.Execute(w, pv); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (h *PageHandler) serveRaw(w http.ResponseWriter, pageName string) {
if !isPageName(pageName) {
http.Error(w, "Invalid page name", http.StatusNotFound)
return
}
content := h.D.ReadString(pageName)
w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
io.WriteString(w, content)
}
// acceptsMarkdown reports whether the request's Accept header includes text/markdown.
// No registered media type has "text/markdown" as a substring, so Contains suffices.
func acceptsMarkdown(r *http.Request) bool {
return strings.Contains(r.Header.Get("Accept"), "text/markdown")
}
func (h *PageHandler) serveView(w http.ResponseWriter, r *http.Request) {
pageName := r.PathValue("pageName")
if raw, ok := strings.CutSuffix(pageName, ".md"); ok {
h.serveRaw(w, raw)
return
}
if !isPageName(pageName) {
http.Error(w, "Invalid page name", http.StatusNotFound)
return
}
if acceptsMarkdown(r) {
h.serveRaw(w, pageName)
return
}
content := h.D.ReadString(pageName)
rendered, err := RenderHTML(content)
if err != nil {
http.Error(w, "Failed to render markdown", http.StatusInternalServerError)
return
}
pv := h.newPageValues(pageName)
pv.HTMLContent = template.HTML(rendered)
pv.ReverseLinks = h.reverseLinks(pageName)
if err := PageTmpl.Execute(w, pv); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (h *PageHandler) newPageValues(pageName string) *pageValues {
return &pageValues{
Title: ToTitle(pageName),
PageName: pageName,
FaviconURL: *faviconURL,
CSSURL: *cssURL,
}
}
func (h *PageHandler) reverseLinks(pagename string) []string {
h.revLinksMu.RLock()
defer h.revLinksMu.RUnlock()
if h.revLinks == nil {
// Recalculate at read only if not done before.
// This should only happen on startup.
h.revLinksMu.RUnlock()
h.recalculateRevLinks()
h.revLinksMu.RLock()
}
return h.revLinks[pagename]
}
func (h *PageHandler) recalculateRevLinks() {
rl := AllReverseLinks(h.D)
h.revLinksMu.Lock()
defer h.revLinksMu.Unlock()
h.revLinks = rl
}
var fullPageNameRE = regexp.MustCompile(`^` + pageNameRE.String() + `$`)
// isPageName returns true iff pn is a camel case page name.
func isPageName(pn string) bool {
return fullPageNameRE.MatchString(pn)
}
// ToTitle turns a given page name into a human-readable title.
//
// This means that it inserts a space before every capital letter,
// except for the first one.
func ToTitle(pageName string) string {
var bld strings.Builder
bld.Grow(len(pageName) + 3)
for pos, rn := range pageName {
if unicode.IsUpper(rn) && pos > 0 {
bld.WriteByte(' ')
}
// Guaranteed to not return errors.
bld.WriteRune(rn)
}
return bld.String()
}
func contentValue(r *http.Request) string {
return strings.ReplaceAll(r.FormValue("content"), "\r\n", "\n")
}
func previewHandler(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
return
}
rendered, err := RenderHTML(string(body))
if err != nil {
http.Error(w, "Failed to render markdown", http.StatusInternalServerError)
return
}
w.Write([]byte(rendered))
}