Skip to content

Commit

Permalink
Discard Content-Length: NaN header, closes honojs/hono#520
Browse files Browse the repository at this point in the history
Temporary workaround until cloudflare/kv-asset-handler#295 released
  • Loading branch information
mrbbot committed Sep 12, 2022
1 parent de5adc8 commit 5ba38e8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/http-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ async function writeResponse(
// @ts-expect-error getAll is added to the Headers prototype by
// importing @miniflare/core
headers["set-cookie"] = response.headers.getAll("set-cookie");
} else {
} else if (key !== "content-length") {
// Content-Length has special handling below
headers[key] = value;
}
}
Expand All @@ -174,7 +175,9 @@ async function writeResponse(
const contentLength =
_getBodyLength(response) ??
(contentLengthHeader === null ? null : parseInt(contentLengthHeader));
if (contentLength !== null) headers["content-length"] = contentLength;
if (contentLength !== null && !isNaN(contentLength)) {
headers["content-length"] = contentLength;
}

// If a Content-Encoding is set, and the user hasn't encoded the body,
// we're responsible for doing so.
Expand Down
14 changes: 14 additions & 0 deletions packages/http-server/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,20 @@ test("createRequestListener: displays appropriately-formatted error page", async
});
t.is(headers["content-type"], "text/plain; charset=UTF-8");
});
test("createRequestListener: discards Content-Length header if invalid", async (t) => {
// https://github.com/honojs/hono/issues/520
const mf = useMiniflareWithHandler({ HTTPPlugin }, {}, (globals) => {
const res = new globals.Response("string");
return new globals.Response(res.body, {
headers: { "Content-Length": "undefined" },
});
});
const port = await listen(t, http.createServer(createRequestListener(mf)));
const [body, headers] = await request(port);
t.is(body, "string");
t.is(headers["content-length"], undefined);
t.is(headers["transfer-encoding"], "chunked");
});
test("createRequestListener: includes live reload script in html responses if enabled", async (t) => {
const mf = useMiniflareWithHandler({ HTTPPlugin }, {}, (globals) => {
return new globals.Response(
Expand Down

0 comments on commit 5ba38e8

Please sign in to comment.