Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(http): allow custom http codes along with custom response text #855

Merged
merged 4 commits into from
May 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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