Sessions for Rocket.rs
https://crates.io/crates/rocket_session
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.3 KiB
59 lines
1.3 KiB
#[macro_use]
|
|
extern crate rocket;
|
|
|
|
use rocket::response::content::RawHtml;
|
|
use rocket::response::Redirect;
|
|
|
|
type Session<'a> = rocket_session::Session<'a, Vec<String>>;
|
|
|
|
#[launch]
|
|
fn rocket() -> _ {
|
|
rocket::build()
|
|
.attach(Session::fairing())
|
|
.mount("/", routes![index, add, remove])
|
|
}
|
|
|
|
#[get("/")]
|
|
fn index(session: Session) -> RawHtml<String> {
|
|
let mut page = String::new();
|
|
page.push_str(
|
|
r#"
|
|
<!DOCTYPE html>
|
|
<h1>My Dogs</h1>
|
|
|
|
<form method="POST" action="/add">
|
|
Add Dog: <input type="text" name="name"> <input type="submit" value="Add">
|
|
</form>
|
|
|
|
<ul>
|
|
"#,
|
|
);
|
|
session.tap(|sess| {
|
|
for (n, dog) in sess.iter().enumerate() {
|
|
page.push_str(&format!(
|
|
r#"<li>🐶 {} <a href="/remove/{}">Remove</a></li>"#,
|
|
dog, n
|
|
));
|
|
}
|
|
});
|
|
page.push_str("</ul>");
|
|
RawHtml(page)
|
|
}
|
|
|
|
#[post("/add", data = "<dog>")]
|
|
fn add(session: Session, dog: String) -> Redirect {
|
|
session.tap(move |sess| {
|
|
sess.push(dog);
|
|
});
|
|
Redirect::found("/")
|
|
}
|
|
|
|
#[get("/remove/<dog>")]
|
|
fn remove(session: Session, dog: usize) -> Redirect {
|
|
session.tap(|sess| {
|
|
if dog < sess.len() {
|
|
sess.remove(dog);
|
|
}
|
|
});
|
|
Redirect::found("/")
|
|
}
|
|
|