feat(ui): Enable Brotli compression for better compression ratio in transit

This commit is contained in:
Linus Lee
2021-07-24 18:54:24 -04:00
parent bd219d64d2
commit 09c8d4c97e
3 changed files with 38 additions and 13 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
static/indexes/*.json
static/indexes/*.json.gz
static/indexes/*.json.br
node_modules/

View File

@@ -48,11 +48,14 @@ index:
ink src/index.ink
# remove control characters that sneak into content. These are filtered out
# in the index but not in doc sources, and trips up JSON parsers.
tr -d '[:cntrl:]' < static/indexes/docs.json > /tmp/docs.json
LC_ALL=C tr -d '[:cntrl:]' < static/indexes/docs.json > /tmp/docs.json
mv /tmp/docs.json static/indexes/docs.json
# gzip
gzip --best < static/indexes/docs.json > static/indexes/docs.json.gz
gzip --best < static/indexes/index.json > static/indexes/index.json.gz
# brotli
brotli -kZf static/indexes/docs.json
brotli -kZf static/indexes/index.json
# build whenever Ink sources change
watch:

View File

@@ -6,6 +6,7 @@ str := load('../vendor/str')
log := std.log
f := std.format
readFile := std.readFile
contains? := str.contains?
http := load('../vendor/http')
mimeForPath := load('../vendor/mime').forPath
@@ -28,18 +29,38 @@ serveStatic := path => (req, end) => req.method :: {
_ -> end(MethodNotAllowed)
}
serveGZip := path => (req, end) => req.method :: {
'GET' -> readFile('static/indexes/' + path + '.gz', file => file :: {
() -> end(NotFound)
_ -> end({
status: 200
headers: {
'Content-Type': mimeForPath(path)
'Content-Encoding': 'gzip'
}
body: file
})
serveGZip := (path, end) => readFile('static/indexes/' + path + '.gz', file => file :: {
() -> end(NotFound)
_ -> end({
status: 200
headers: {
'Content-Type': mimeForPath(path)
'Content-Encoding': 'gzip'
}
body: file
})
})
serveBrotli := (path, end) => readFile('static/indexes/' + path + '.br', file => file :: {
() -> end(NotFound)
_ -> end({
status: 200
headers: {
'Content-Type': mimeForPath(path)
'Content-Encoding': 'br'
}
body: file
})
})
serveCompressed := path => (req, end) => req.method :: {
'GET' -> acceptEncoding := req.headers.'Accept-Encoding' :: {
() -> serveGZip(path, end)
` we check brotli compatibility before serving, as it is not as
ubiquitous as gzip `
_ -> contains?(acceptEncoding, 'br') :: {
true -> serveBrotli(path, end)
_ -> serveGZip(path, end)
}
}
_ -> end(MethodNotAllowed)
}
@@ -47,7 +68,7 @@ addRoute := server.addRoute
` static paths `
addRoute('/static/*staticPath', params => serveStatic(params.staticPath))
addRoute('/indexes/*indexPath', params => serveGZip(params.indexPath))
addRoute('/indexes/*indexPath', params => serveCompressed(params.indexPath))
addRoute('/favicon.ico', params => serveStatic('favicon.ico'))
addRoute('/', params => serveStatic('index.html'))