Skip to content

Commit

Permalink
http: send an empty response body if none is provided (denoland#429)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nautigsam authored and piscisaureus committed May 23, 2019
1 parent 7620fe1 commit e00e3fe
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
29 changes: 14 additions & 15 deletions http/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ export async function writeResponse(w: Writer, r: Response): Promise<void> {
if (!statusText) {
throw Error("bad status code");
}
if (!r.body) {
r.body = new Uint8Array();
}

let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`;

Expand All @@ -79,22 +82,18 @@ export async function writeResponse(w: Writer, r: Response): Promise<void> {
out += "\r\n";

const header = new TextEncoder().encode(out);
let n = await writer.write(header);
assert(header.byteLength == n);
const n = await writer.write(header);
assert(n === header.byteLength);

if (r.body) {
if (r.body instanceof Uint8Array) {
n = await writer.write(r.body);
assert(r.body.byteLength == n);
} else {
if (r.headers.has("content-length")) {
const bodyLength = parseInt(r.headers.get("content-length"));
const n = await copy(writer, r.body);
assert(n == bodyLength);
} else {
await writeChunkedBody(writer, r.body);
}
}
if (r.body instanceof Uint8Array) {
const n = await writer.write(r.body);
assert(n === r.body.byteLength);
} else if (r.headers.has("content-length")) {
const bodyLength = parseInt(r.headers.get("content-length"));
const n = await copy(writer, r.body);
assert(n === bodyLength);
} else {
await writeChunkedBody(writer, r.body);
}
await writer.flush();
}
Expand Down
9 changes: 8 additions & 1 deletion http/server_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,14 @@ const responseTests: ResponseTest[] = [
// Default 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
{
Expand Down

0 comments on commit e00e3fe

Please sign in to comment.