forked from nickel-org/nickel.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cookies_example.rs
45 lines (36 loc) · 1.21 KB
/
cookies_example.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#[macro_use] extern crate nickel;
extern crate cookie;
use nickel::{Nickel, HttpRouter, Cookies, QueryString};
use nickel::cookies;
use cookie::Cookie;
struct Data {
secret_key: cookies::SecretKey
}
impl AsRef<cookies::SecretKey> for Data {
fn as_ref(&self) -> &cookies::SecretKey {
&self.secret_key
}
}
fn main() {
let data = Data { secret_key: cookies::SecretKey([0; 32]) };
let mut server = Nickel::with_data(data);
// Try curl -b MyCookie=bar localhost:6767
server.get("/", middleware! { |req|
let cookie = req.cookies().find("MyCookie");
format!("MyCookie={:?}", cookie.map(|c| c.value))
});
// Note: Don't use get for login in real applications ;)
// Try http://localhost:6767/login?name=foo
server.get("/login", middleware! { |req, mut res|
let jar = res.cookies_mut()
// long life cookies!
.permanent();
let name = req.query().get("name")
.unwrap_or("default_name");
let cookie = Cookie::new("MyCookie".to_owned(),
name.to_owned());
jar.add(cookie);
"Cookie set!"
});
server.listen("127.0.0.1:6767");
}