Send 304 when file time not greater than if-modified-since header
Alan Pearce alan@alanpearce.eu
Wed, 13 Sep 2023 06:52:32 +0200
1 files changed, 15 insertions(+), 3 deletions(-)
jump to
M src/index.ts → src/index.ts
@@ -15,7 +15,7 @@ type File = { filename: string; headers?: Record<string, string>; size: number; - mtime: string; + mtime: Date; }; let files = new Map<string, File>(); @@ -33,7 +33,7 @@ pathname === "/404.html" ? Object.assign({}, defaultHeaders, { "cache-control": "no-cache" }) : undefined, size: stat.size, - mtime: stat.mtime.toUTCString(), + mtime: stat.mtime, }); } @@ -67,7 +67,7 @@ ): Promise<Response> { if (file && (await fsp.exists(file.filename))) { return new Response(Bun.file(file.filename), { headers: { - "last-modified": file.mtime, + "last-modified": file.mtime.toUTCString(), ...(file.headers || defaultHeaders), }, status: statusCode, @@ -77,10 +77,22 @@ return serveFile(files.get("/404.html"), 404); } } +function parseIfModifiedSinceHeader(header: string | null): number { + return header ? new Date(header).getTime() + 999 : 0; +} + export default withHtmlLiveReload({ fetch: async function (request) { const pathname = new URL(request.url).pathname; const file = files.get(pathname); + if (file) { + const ims = parseIfModifiedSinceHeader( + request.headers.get("if-modified-since"), + ); + if (ims >= file?.mtime.getTime()) { + return new Response("", { status: 304 }); + } + } return serveFile(file); }, });