diff options
| author | Vincent LE GOFF <g_n_s@hotmail.fr> | 2019-04-24 13:38:52 +0200 |
|---|---|---|
| committer | Ryan Dahl <ry@tinyclouds.org> | 2019-04-24 07:38:52 -0400 |
| commit | e1f7a60bb326f8299f339635c0738d28431afa0a (patch) | |
| tree | ddcad79b9544a325a081ec4b82a6b87b59ce1255 | |
| parent | 0fb83ba0d2e8facfa32e92a4d0700caad83701d9 (diff) | |
http : Add cookie module (denoland/deno_std#338)
Original: https://github.com/denoland/deno_std/commit/1d8544788648b4c571d10b9a55cc3670a1cbf69c
| -rw-r--r-- | http/cookie.ts | 21 | ||||
| -rw-r--r-- | http/cookie_test.ts | 25 | ||||
| -rw-r--r-- | http/test.ts | 1 |
3 files changed, 47 insertions, 0 deletions
diff --git a/http/cookie.ts b/http/cookie.ts new file mode 100644 index 000000000..e78d48238 --- /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 000000000..e8f920b31 --- /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 938ea4458..7226ad40f 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"; |
