1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-27 01:29:14 -05:00

http : Add cookie module (#338)

This commit is contained in:
Vincent LE GOFF 2019-04-24 13:38:52 +02:00 committed by Ryan Dahl
parent 0a61800163
commit 1d85447886
3 changed files with 47 additions and 0 deletions

21
http/cookie.ts Normal file
View file

@ -0,0 +1,21 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { ServerRequest } from "./server.ts";
export interface Cookie {
[key: string]: string;
}
/* Parse the cookie of the Server Request */
export function getCookie(rq: ServerRequest): Cookie {
if (rq.headers.has("Cookie")) {
const out: Cookie = {};
const c = rq.headers.get("Cookie").split(";");
for (const kv of c) {
const cookieVal = kv.split("=");
const key = cookieVal.shift().trim();
out[key] = cookieVal.join("");
}
return out;
}
return {};
}

25
http/cookie_test.ts Normal file
View file

@ -0,0 +1,25 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { ServerRequest } from "./server.ts";
import { getCookie } from "./cookie.ts";
import { assertEquals } from "../testing/asserts.ts";
import { test } from "../testing/mod.ts";
test({
name: "[HTTP] Cookie parser",
fn(): void {
let req = new ServerRequest();
req.headers = new Headers();
assertEquals(getCookie(req), {});
req.headers = new Headers();
req.headers.set("Cookie", "foo=bar");
assertEquals(getCookie(req), { foo: "bar" });
req.headers = new Headers();
req.headers.set("Cookie", "full=of ; tasty=chocolate");
assertEquals(getCookie(req), { full: "of ", tasty: "chocolate" });
req.headers = new Headers();
req.headers.set("Cookie", "igot=99; problems=but...");
assertEquals(getCookie(req), { igot: "99", problems: "but..." });
}
});

View file

@ -1,4 +1,5 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import "./cookie_test.ts";
import "./server_test.ts";
import "./file_server_test.ts";
import "./racing_server_test.ts";