From 18cb34b7db7d381cd81cdaafc947270ac170af3f Mon Sep 17 00:00:00 2001 From: Leo Kettmeir Date: Fri, 29 Nov 2024 15:40:03 -0800 Subject: [PATCH] fix(http): handle HEAD requests in serveFile (#6218) --- http/file_server.ts | 29 ++++++++++++++++++++--------- http/file_server_test.ts | 12 ++++++++++++ 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/http/file_server.ts b/http/file_server.ts index 0d79b19361ed..ade5693d588d 100644 --- a/http/file_server.ts +++ b/http/file_server.ts @@ -179,7 +179,7 @@ export async function serveFile( filePath: string, options?: ServeFileOptions, ): Promise { - if (req.method !== METHOD.Get) { + if (req.method !== METHOD.Get && req.method !== METHOD.Head) { return createStandardResponse(STATUS_CODE.MethodNotAllowed); } @@ -220,6 +220,25 @@ export async function serveFile( headers.set(HEADER.ETag, etag); } + // Set mime-type using the file extension in filePath + const contentTypeValue = contentType(extname(filePath)); + if (contentTypeValue) { + headers.set(HEADER.ContentType, contentTypeValue); + } + const fileSize = fileInfo.size; + + if (req.method === METHOD.Head) { + // Set content length + headers.set(HEADER.ContentLength, `${fileSize}`); + + const status = STATUS_CODE.OK; + return new Response(null, { + status, + statusText: STATUS_TEXT[status], + headers, + }); + } + if (etag || fileInfo.mtime) { // If a `if-none-match` header is present and the value matches the tag or // if a `if-modified-since` header is present and the value is bigger than @@ -243,14 +262,6 @@ export async function serveFile( } } - // Set mime-type using the file extension in filePath - const contentTypeValue = contentType(extname(filePath)); - if (contentTypeValue) { - headers.set(HEADER.ContentType, contentTypeValue); - } - - const fileSize = fileInfo.size; - const rangeValue = req.headers.get(HEADER.Range); // handle range request diff --git a/http/file_server_test.ts b/http/file_server_test.ts index efce6c570112..08b3cb9c7e0b 100644 --- a/http/file_server_test.ts +++ b/http/file_server_test.ts @@ -1137,3 +1137,15 @@ async function readUntilMatch( reader.releaseLock(); return dec.decode(buf); } + +Deno.test(async function serveFileHeadRequest() { + const req = new Request("http://localhost/testdata/test_file.txt", { + method: "HEAD", + }); + const res = await serveFile(req, TEST_FILE_PATH); + assert(!res.body); + assertEquals(res.status, 200); + assertEquals(res.statusText, "OK"); + assertEquals(res.headers.get("content-type"), "text/plain; charset=UTF-8"); + assertEquals(res.headers.get("content-length"), "10034"); +});