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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#[macro_use]
extern crate rocket;
use rocket::response::content::RawHtml;
use std::time::Duration;
#[derive(Default, Clone)]
struct SessionData {
visits1: usize,
visits2: usize,
}
type Session<'a> = rocket_session::Session<'a, SessionData>;
#[launch]
fn rocket() -> _ {
rocket::build()
.attach(
Session::fairing()
.with_lifetime(Duration::from_secs(10))
.with_cookie_name("my_cookie")
.with_cookie_len(20),
)
.mount("/", routes![index, about])
}
#[get("/")]
fn index(session: Session) -> RawHtml<String> {
session.tap(|sess| {
sess.visits1 += 1;
RawHtml(format!(
r##"
<!DOCTYPE html>
<h1>Home</h1>
<a href="/">Refresh</a> • <a href="/about/">go to About</a>
<p>Visits: home {}, about {}</p>
"##,
sess.visits1, sess.visits2
))
})
}
#[get("/about")]
fn about(session: Session) -> RawHtml<String> {
let count = session.tap(|sess| {
sess.visits2 += 1;
sess.visits2
});
RawHtml(format!(
r##"
<!DOCTYPE html>
<h1>About</h1>
<a href="/about">Refresh</a> • <a href="/">go home</a>
<p>Page visits: {}</p>
"##,
count
))
}