Skip to content

Commit

Permalink
fix(http): handle HEAD requests in serveFile (#6218)
Browse files Browse the repository at this point in the history
  • Loading branch information
crowlKats authored Nov 29, 2024
1 parent 9f294ee commit 18cb34b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
29 changes: 20 additions & 9 deletions http/file_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export async function serveFile(
filePath: string,
options?: ServeFileOptions,
): Promise<Response> {
if (req.method !== METHOD.Get) {
if (req.method !== METHOD.Get && req.method !== METHOD.Head) {
return createStandardResponse(STATUS_CODE.MethodNotAllowed);
}

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions http/file_server_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});

0 comments on commit 18cb34b

Please sign in to comment.