From e00e3fe33a4e57e8bebcf2b7cdd4f501674450d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Bertron?= Date: Thu, 23 May 2019 04:33:17 +0200 Subject: [PATCH] http: send an empty response body if none is provided (#429) Fixes: #402 --- http/server.ts | 29 ++++++++++++++--------------- http/server_test.ts | 9 ++++++++- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/http/server.ts b/http/server.ts index 809cf39ffe99f2..b49e23b15c308f 100644 --- a/http/server.ts +++ b/http/server.ts @@ -66,6 +66,9 @@ export async function writeResponse(w: Writer, r: Response): Promise { if (!statusText) { throw Error("bad status code"); } + if (!r.body) { + r.body = new Uint8Array(); + } let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`; @@ -79,22 +82,18 @@ export async function writeResponse(w: Writer, r: Response): Promise { 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(); } diff --git a/http/server_test.ts b/http/server_test.ts index e3baebd5385480..e17b29a4dad75b 100644 --- a/http/server_test.ts +++ b/http/server_test.ts @@ -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 {