0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-02-08 15:21:26 -05:00

http: send an empty response body if none is provided (denoland/deno_std#429)

Fixes: denoland/deno_std#402

Original: e00e3fe33a
This commit is contained in:
Aurélien Bertron 2019-05-23 04:33:17 +02:00 committed by Bert Belder
parent 3cfc1244d8
commit a4346a3ac9
2 changed files with 22 additions and 16 deletions

View file

@ -66,6 +66,9 @@ export async function writeResponse(w: Writer, r: Response): Promise<void> {
if (!statusText) { if (!statusText) {
throw Error("bad status code"); throw Error("bad status code");
} }
if (!r.body) {
r.body = new Uint8Array();
}
let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`; let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`;
@ -79,22 +82,18 @@ export async function writeResponse(w: Writer, r: Response): Promise<void> {
out += "\r\n"; out += "\r\n";
const header = new TextEncoder().encode(out); const header = new TextEncoder().encode(out);
let n = await writer.write(header); const n = await writer.write(header);
assert(header.byteLength == n); assert(n === header.byteLength);
if (r.body) { if (r.body instanceof Uint8Array) {
if (r.body instanceof Uint8Array) { const n = await writer.write(r.body);
n = await writer.write(r.body); assert(n === r.body.byteLength);
assert(r.body.byteLength == n); } else if (r.headers.has("content-length")) {
} else { const bodyLength = parseInt(r.headers.get("content-length"));
if (r.headers.has("content-length")) { const n = await copy(writer, r.body);
const bodyLength = parseInt(r.headers.get("content-length")); assert(n === bodyLength);
const n = await copy(writer, r.body); } else {
assert(n == bodyLength); await writeChunkedBody(writer, r.body);
} else {
await writeChunkedBody(writer, r.body);
}
}
} }
await writer.flush(); await writer.flush();
} }

View file

@ -31,7 +31,14 @@ const responseTests: ResponseTest[] = [
// Default response // Default response
{ {
response: {}, response: {},
raw: "HTTP/1.1 200 OK\r\n" + "\r\n" raw: "HTTP/1.1 200 OK\r\n" + "content-length: 0" + "\r\n\r\n"
},
// Empty body with status
{
response: {
status: 404
},
raw: "HTTP/1.1 404 Not Found\r\n" + "content-length: 0" + "\r\n\r\n"
}, },
// HTTP/1.1, chunked coding; empty trailer; close // HTTP/1.1, chunked coding; empty trailer; close
{ {