all repos — archive/homestead @ c48a92fdd4d9ab9ec96c1cff73af84b9cdd1a96d

My future indieweb platform

Send 304 when file time not greater than if-modified-since header

Alan Pearce
commit

c48a92fdd4d9ab9ec96c1cff73af84b9cdd1a96d

parent

7c376d43ed17ffb44933f3ac8c1c8b8590dd675e

1 file changed, 15 insertions(+), 3 deletions(-)

jump to
M src/index.tssrc/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); }, });