Skip to content

Commit

Permalink
feat(http): allow custom response code (#855)
Browse files Browse the repository at this point in the history
  • Loading branch information
lowlighter authored May 11, 2021
1 parent b850d01 commit 1b4eff0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 9 deletions.
8 changes: 5 additions & 3 deletions http/_io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,12 @@ export async function writeResponse(
const protoMajor = 1;
const protoMinor = 1;
const statusCode = r.status || 200;
const statusText = STATUS_TEXT.get(statusCode);
const statusText = r.statusText ?? STATUS_TEXT.get(statusCode) ?? null;
const writer = BufWriter.create(w);
if (!statusText) {
throw new Deno.errors.InvalidData("Bad status code");
if (statusText === null) {
throw new Deno.errors.InvalidData(
"Empty statusText (explicitely pass an empty string if this was intentional)",
);
}
if (!r.body) {
r.body = new Uint8Array();
Expand Down
1 change: 1 addition & 0 deletions http/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,7 @@ export async function listenAndServeTLS(
*/
export interface Response {
status?: number;
statusText?: string;
headers?: Headers;
body?: Uint8Array | Deno.Reader | string;
trailers?: () => Promise<Headers> | Headers;
Expand Down
30 changes: 24 additions & 6 deletions http/server_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ const responseTests: ResponseTest[] = [
},
raw: "HTTP/1.1 404 Not Found\r\n" + "content-length: 0" + "\r\n\r\n",
},
{
response: {
status: 893,
statusText: "Custom error",
},
raw: "HTTP/1.1 893 Custom error\r\n" + "content-length: 0" + "\r\n\r\n",
},
{
response: {
status: 893,
statusText: "",
},
raw: "HTTP/1.1 893 \r\n" + "content-length: 0" + "\r\n\r\n",
},
// HTTP/1.1, chunked coding; empty trailer; close
{
response: {
Expand Down Expand Up @@ -518,12 +532,16 @@ Deno.test({
const serverRoutine = async () => {
const server = serve(":8124");
for await (const req of server) {
await assertThrowsAsync(async () => {
await req.respond({
status: 12345,
body: new TextEncoder().encode("Hello World"),
});
}, Deno.errors.InvalidData);
await assertThrowsAsync(
async () => {
await req.respond({
status: 12345,
body: new TextEncoder().encode("Hello World"),
});
},
Deno.errors.InvalidData,
"Empty statusText",
);
// The connection should be destroyed
assert(!(req.conn.rid in Deno.resources()));
server.close();
Expand Down

0 comments on commit 1b4eff0

Please sign in to comment.