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:
parent
0a61800163
commit
1d85447886
3 changed files with 47 additions and 0 deletions
21
http/cookie.ts
Normal file
21
http/cookie.ts
Normal 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
25
http/cookie_test.ts
Normal 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..." });
|
||||
}
|
||||
});
|
|
@ -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";
|
||||
|
|
Loading…
Reference in a new issue