-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathspa_response_writer.go
More file actions
231 lines (192 loc) · 5.23 KB
/
spa_response_writer.go
File metadata and controls
231 lines (192 loc) · 5.23 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package riverui
import (
"bytes"
"encoding/json"
"html/template"
"io"
"mime"
"net/http"
"slices"
"strconv"
"strings"
"time"
)
func intercept404(handler, on404 http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
// pre-emptively intercept the root path and serve the dynamically processed index.html:
on404.ServeHTTP(w, r)
return
}
hookedWriter := &spaResponseWriter{ResponseWriter: w}
handler.ServeHTTP(hookedWriter, r)
if hookedWriter.got404 {
on404.ServeHTTP(w, r)
}
})
}
func serveIndexHTML(devMode bool, manifest map[string]any, pathPrefix string, files http.FileSystem) http.HandlerFunc {
cachedIndex := indexTemplateResult{}
if !devMode {
cachedIndex = loadIndexTemplate(files)
}
return func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet && req.Method != http.MethodHead {
rw.Header().Set("Allow", "GET, HEAD")
http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
return
}
addVaryHeader(rw.Header(), "Accept")
// Restrict only to instances where the browser is looking for an HTML file
if !acceptsHTML(req) {
http.Error(rw, "not acceptable: only text/html is available", http.StatusNotAcceptable)
return
}
indexTemplate := cachedIndex
if devMode {
indexTemplate = loadIndexTemplate(files)
}
if indexTemplate.err != nil {
http.Error(rw, indexTemplate.errMessage, http.StatusInternalServerError)
return
}
config := indexTemplateConfig{
APIURL: pathPrefix + "/api",
Base: pathPrefix,
}
templateData := indexTemplateData{
Config: config,
Dev: devMode,
Manifest: manifest,
Base: pathPrefix,
}
var output bytes.Buffer
if err := indexTemplate.tmpl.Execute(&output, templateData); err != nil {
http.Error(rw, "could not execute index.html", http.StatusInternalServerError)
return
}
indexReader := bytes.NewReader(output.Bytes())
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
http.ServeContent(rw, req, indexTemplate.name, indexTemplate.modTime, indexReader)
}
}
func acceptsHTML(req *http.Request) bool {
acceptValues := req.Header.Values("Accept")
if len(acceptValues) == 0 {
return true
}
return slices.ContainsFunc(acceptValues, acceptsHTMLValue)
}
func acceptsHTMLValue(accept string) bool {
if strings.TrimSpace(accept) == "" {
return true
}
for part := range strings.SplitSeq(accept, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
mediaType, params, err := mime.ParseMediaType(part)
if err != nil {
mediaType = strings.TrimSpace(strings.SplitN(part, ";", 2)[0])
params = nil
}
quality := 1.0
if params != nil {
if qRaw, ok := params["q"]; ok {
if parsed, err := strconv.ParseFloat(qRaw, 64); err == nil {
quality = parsed
}
}
}
if quality <= 0 {
continue
}
switch mediaType {
case "text/html", "application/xhtml+xml", "text/*", "*/*":
return true
}
}
return false
}
func addVaryHeader(headers http.Header, value string) {
for _, existing := range headers.Values("Vary") {
for part := range strings.SplitSeq(existing, ",") {
if strings.EqualFold(strings.TrimSpace(part), value) {
return
}
}
}
headers.Add("Vary", value)
}
type indexTemplateConfig struct {
APIURL string `json:"apiUrl"` //nolint:tagliatelle
Base string `json:"base"`
}
type indexTemplateData struct {
Config indexTemplateConfig
Dev bool
Manifest map[string]any
Base string
}
type indexTemplateResult struct {
tmpl *template.Template
name string
modTime time.Time
err error
errMessage string
}
func loadIndexTemplate(files http.FileSystem) indexTemplateResult {
rawIndex, err := files.Open("index.html")
if err != nil {
return indexTemplateResult{err: err, errMessage: "could not open index.html"}
}
defer rawIndex.Close()
fileInfo, err := rawIndex.Stat()
if err != nil {
return indexTemplateResult{err: err, errMessage: "could not stat index.html"}
}
indexBuf, err := io.ReadAll(rawIndex)
if err != nil {
return indexTemplateResult{err: err, errMessage: "could not read index.html"}
}
tmpl, err := parseIndexTemplate(indexBuf)
if err != nil {
return indexTemplateResult{err: err, errMessage: "could not parse index.html"}
}
return indexTemplateResult{
tmpl: tmpl,
name: fileInfo.Name(),
modTime: fileInfo.ModTime(),
}
}
func parseIndexTemplate(indexBuf []byte) (*template.Template, error) {
return template.New("index.html").Funcs(template.FuncMap{
"marshal": func(v any) (template.JS, error) {
payload, err := json.Marshal(v)
if err != nil {
return "", err
}
return template.JS(payload), nil //nolint:gosec
},
}).Parse(string(indexBuf))
}
type spaResponseWriter struct {
http.ResponseWriter
got404 bool
}
func (srw *spaResponseWriter) WriteHeader(status int) {
if status == http.StatusNotFound {
// Don't actually write the 404 header, just set a flag.
srw.got404 = true
} else {
srw.ResponseWriter.WriteHeader(status)
}
}
func (srw *spaResponseWriter) Write(payload []byte) (int, error) {
if srw.got404 {
// No-op, but pretend that we wrote len(p) bytes to the writer.
return len(payload), nil
}
return srw.ResponseWriter.Write(payload)
}