diff --git a/http/cookie.ts b/http/cookie.ts new file mode 100644 index 0000000000..e78d482389 --- /dev/null +++ b/http/cookie.ts @@ -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 {}; +} diff --git a/http/cookie_test.ts b/http/cookie_test.ts new file mode 100644 index 0000000000..e8f920b31c --- /dev/null +++ b/http/cookie_test.ts @@ -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..." }); + } +}); diff --git a/http/test.ts b/http/test.ts index 938ea4458c..7226ad40fe 100644 --- a/http/test.ts +++ b/http/test.ts @@ -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";