From f04716df5c5c3029d246294d82646b298ec39afe Mon Sep 17 00:00:00 2001 From: hashrock Date: Tue, 28 Feb 2023 05:37:40 +0900 Subject: [PATCH] fix(context): handle HEAD requests (#1034) --- src/server/context.ts | 21 +++++++++++++++++++-- tests/main_test.ts | 23 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/server/context.ts b/src/server/context.ts index 9d25e411..d2d765d6 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -312,7 +312,7 @@ export class ServerContext { handler(): RequestHandler { const inner = rutt.router(...this.#handlers()); const withMiddlewares = this.#composeMiddlewares(this.#middlewares); - return function handler(req: Request, connInfo: ConnInfo) { + return async function handler(req: Request, connInfo: ConnInfo) { // Redirect requests that end with a trailing slash // to their non-trailing slash counterpart. // Ex: /about/ -> /about @@ -321,7 +321,24 @@ export class ServerContext { url.pathname = url.pathname.slice(0, -1); return Response.redirect(url.href, Status.TemporaryRedirect); } - return withMiddlewares(req, connInfo, inner); + + // HEAD requests should be handled as GET requests + // but without the body. + const originalMethod = req.method; + // Internally, HEAD is handled in the same way as GET. + if (req.method === "HEAD") { + req = new Request(req.url, { method: "GET", headers: req.headers }); + } + const res = await withMiddlewares(req, connInfo, inner); + if (originalMethod === "HEAD") { + res.body?.cancel(); + return new Response(null, { + headers: res.headers, + status: res.status, + statusText: res.statusText, + }); + } + return res; }; } diff --git a/tests/main_test.ts b/tests/main_test.ts index 4603927e..ea4c3199 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -254,6 +254,29 @@ Deno.test("static file - by file path", async () => { assertEquals(resp3.headers.get("content-type"), "text/plain"); }); +Deno.test("HEAD request", async () => { + // Static file + const resp = await router( + new Request("https://fresh.deno.dev/foo.txt", { + method: "HEAD", + }), + ); + assertEquals(resp.status, Status.OK); + const body = await resp.text(); + assertEquals(body, ""); + + // route + const resp2 = await router( + new Request("https://fresh.deno.dev/books/123", { + method: "HEAD", + }), + ); + assert(resp2); + assertEquals(resp2.status, Status.OK); + const body2 = await resp2.text(); + assertEquals(body2, ""); +}); + Deno.test("static file - by 'hashed' path", async () => { // Check that the file path have the BUILD_ID const resp = await router(