version bump, comments, improve examples, update readme

This commit is contained in:
Ondřej Hruška
2019-12-31 20:48:56 +01:00
parent cde08fe788
commit f8d5445cdc
5 changed files with 100 additions and 60 deletions
+17 -10
View File
@@ -2,9 +2,9 @@
#[macro_use]
extern crate rocket;
use rocket::request::Form;
use rocket::response::content::Html;
use rocket::response::Redirect;
use rocket::request::Form;
type Session<'a> = rocket_session::Session<'a, Vec<String>>;
@@ -18,7 +18,8 @@ fn main() {
#[get("/")]
fn index(session: Session) -> Html<String> {
let mut page = String::new();
page.push_str(r#"
page.push_str(
r#"
<!DOCTYPE html>
<h1>My Dogs</h1>
@@ -27,19 +28,25 @@ fn index(session: Session) -> Html<String> {
</form>
<ul>
"#);
"#,
);
session.tap(|sess| {
for (n, dog) in sess.iter().enumerate() {
page.push_str(&format!(r#"
page.push_str(&format!(
r#"
<li>&#x1F436; {} <a href="/remove/{}">Remove</a></li>
"#, dog, n));
"#,
dog, n
));
}
});
page.push_str(r#"
page.push_str(
r#"
</ul>
"#);
"#,
);
Html(page)
}
@@ -49,8 +56,8 @@ struct AddForm {
name: String,
}
#[post("/add", data="<dog>")]
fn add(session: Session, dog : Form<AddForm>) -> Redirect {
#[post("/add", data = "<dog>")]
fn add(session: Session, dog: Form<AddForm>) -> Redirect {
session.tap(move |sess| {
sess.push(dog.into_inner().name);
});
@@ -59,7 +66,7 @@ fn add(session: Session, dog : Form<AddForm>) -> Redirect {
}
#[get("/remove/<dog>")]
fn remove(session: Session, dog : usize) -> Redirect {
fn remove(session: Session, dog: usize) -> Redirect {
session.tap(|sess| {
if dog < sess.len() {
sess.remove(dog);
+14 -12
View File
@@ -6,8 +6,8 @@
#[macro_use]
extern crate rocket;
use std::time::Duration;
use rocket::response::content::Html;
use std::time::Duration;
#[derive(Default, Clone)]
struct SessionData {
@@ -20,13 +20,14 @@ type Session<'a> = rocket_session::Session<'a, SessionData>;
fn main() {
rocket::ignite()
.attach(Session::fairing()
// 10 seconds of inactivity until session expires
// (wait 10s and refresh, the numbers will reset)
.with_lifetime(Duration::from_secs(10))
// custom cookie name and length
.with_cookie_name("my_cookie")
.with_cookie_len(20)
.attach(
Session::fairing()
// 10 seconds of inactivity until session expires
// (wait 10s and refresh, the numbers will reset)
.with_lifetime(Duration::from_secs(10))
// custom cookie name and length
.with_cookie_name("my_cookie")
.with_cookie_len(20),
)
.mount("/", routes![index, about])
.launch();
@@ -41,14 +42,14 @@ fn index(session: Session) -> Html<String> {
session.tap(|sess| {
sess.visits1 += 1;
Html(format!(r##"
Html(format!(
r##"
<!DOCTYPE html>
<h1>Home</h1>
<a href="/">Refresh</a> &bull; <a href="/about/">go to About</a>
<p>Visits: home {}, about {}</p>
"##,
sess.visits1,
sess.visits2
sess.visits1, sess.visits2
))
})
}
@@ -61,7 +62,8 @@ fn about(session: Session) -> Html<String> {
sess.visits2
});
Html(format!(r##"
Html(format!(
r##"
<!DOCTYPE html>
<h1>About</h1>
<a href="/about">Refresh</a> &bull; <a href="/">go home</a>