Skip to content

Commit

Permalink
Set http response body as empty by default
Browse files Browse the repository at this point in the history
Fix #402
  • Loading branch information
Nautigsam committed May 21, 2019
1 parent aad0896 commit 1f70348
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 12 deletions.
23 changes: 12 additions & 11 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 @@ -82,18 +85,16 @@ export async function writeResponse(w: Writer, r: Response): Promise<void> {
let n = await writer.write(header);
assert(header.byteLength == n);

if (r.body) {
if (r.body instanceof Uint8Array) {
n = await writer.write(r.body);
assert(r.body.byteLength == n);
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 {
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 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 @@ -26,7 +26,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
1 change: 1 addition & 0 deletions io/bufio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ export class BufWriter implements Writer {
return err;
}
this.n = 0;
return null;
}

/** Returns how many bytes are unused in the buffer. */
Expand Down

0 comments on commit 1f70348

Please sign in to comment.