enh(serve) extend example server with gzip compression

This commit is contained in:
Benjamin Wegener
2024-01-16 20:01:09 +00:00
parent bea825b809
commit 53ed34d68a

View File

@@ -12,7 +12,8 @@ export default {
if (url.pathname == '/main.js') {
const path = resolve(__dirname, `./.cache/`);
const filename = `${magicKey}.js`;
const file = Bun.file(resolve(path, filename));
const filePath = resolve(path, filename);
const file = Bun.file(filePath);
const result = await Bun.build({
entrypoints: ['./src/main.js'],
outdir: path,
@@ -21,20 +22,49 @@ export default {
naming: `[dir]/${filename}`,
});
console.log(result);
let content = await file.arrayBuffer();
let headers = {
'Cache-Control': 'no-cache',
'Content-Length': file.size,
'Content-Type': file.type,
};
const resp = new Response(file, {
headers: { 'Cache-Control': 'no-cache' },
if (req.headers.get('accept-encoding').includes('gzip')) {
headers['Content-Encoding'] = 'gzip';
headers['Vary'] = 'Accept-Encoding';
content = Bun.gzipSync(content);
}
const resp = new Response(content, {
headers,
});
setTimeout(() => {
unlinkSync(resolve(path, filename));
unlinkSync(filePath);
}, 400);
return resp;
}
if (url.pathname == '/')
return new Response(Bun.file(resolve('./index.html')));
if (url.pathname == '/') {
const file = Bun.file(resolve('./index.html'));
let content = await file.arrayBuffer();
let headers = {
'Cache-Control': 'no-cache',
'Content-Length': file.size,
'Content-Type': file.type,
};
if (req.headers.get('accept-encoding').includes('gzip')) {
headers['Content-Encoding'] = 'gzip';
headers['Vary'] = 'Accept-Encoding';
content = Bun.gzipSync(content);
}
console.log(headers, req.headers.get('accept-encoding'));
return new Response(content, {
headers,
});
}
return new Response('ERR 404: Not Found', { status: 404 });
},
};