summaryrefslogtreecommitdiff
path: root/std/http/io.ts
diff options
context:
space:
mode:
author木杉 <zhmushan@qq.com>2020-05-01 22:35:18 +0800
committerGitHub <noreply@github.com>2020-05-01 10:35:18 -0400
commite57f0749e7129d0ee57f5b56dfed217ba0a52b94 (patch)
treef4d802219c9e43266f7df75f9c51e5f5c483bbf8 /std/http/io.ts
parentbe65f6692f0f81dc88c77ba4cf22cdda40760317 (diff)
fix(std/http): avoid directly modifying the headers object (#5024)
Diffstat (limited to 'std/http/io.ts')
-rw-r--r--std/http/io.ts33
1 files changed, 11 insertions, 22 deletions
diff --git a/std/http/io.ts b/std/http/io.ts
index fbce44342..631adafd0 100644
--- a/std/http/io.ts
+++ b/std/http/io.ts
@@ -214,24 +214,6 @@ export async function writeTrailers(
await writer.flush();
}
-export function setContentLength(r: Response): void {
- if (!r.headers) {
- r.headers = new Headers();
- }
-
- if (r.body) {
- if (!r.headers.has("content-length")) {
- // typeof r.body === "string" handled in writeResponse.
- if (r.body instanceof Uint8Array) {
- const bodyLength = r.body.byteLength;
- r.headers.set("content-length", bodyLength.toString());
- } else {
- r.headers.set("transfer-encoding", "chunked");
- }
- }
- }
-}
-
export async function writeResponse(
w: Deno.Writer,
r: Response
@@ -253,14 +235,21 @@ export async function writeResponse(
let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`;
- setContentLength(r);
- assert(r.headers != null);
- const headers = r.headers;
+ const headers = r.headers ?? new Headers();
+
+ if (r.body && !headers.get("content-length")) {
+ if (r.body instanceof Uint8Array) {
+ out += `content-length: ${r.body.byteLength}\r\n`;
+ } else if (!headers.get("transfer-encoding")) {
+ out += "transfer-encoding: chunked\r\n";
+ }
+ }
for (const [key, value] of headers) {
out += `${key}: ${value}\r\n`;
}
- out += "\r\n";
+
+ out += `\r\n`;
const header = encoder.encode(out);
const n = await writer.write(header);