From 53ed34d68a605b2ed54a2797eb7cca6b965e2b0c Mon Sep 17 00:00:00 2001 From: Benjamin Wegener Date: Tue, 16 Jan 2024 20:01:09 +0000 Subject: [PATCH] enh(serve) extend example server with gzip compression --- examples/server.js | 44 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/examples/server.js b/examples/server.js index 0ac9847..ae25d4b 100644 --- a/examples/server.js +++ b/examples/server.js @@ -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 }); }, };