mirror of
https://github.com/rwf2/Rocket.git
synced 2025-01-08 02:32:37 +00:00
2893ce754d
Catchers can now be scoped to paths, with preference given to the longest-prefix, then the status code. This a breaking change for all applications that register catchers: * `Rocket::register()` takes a base path to scope catchers under. - The previous behavior is recovered with `::register("/", ...)`. * Catchers now fallibly, instead of silently, collide. * `ErrorKind::Collision` is now `ErrorKind::Collisions`. Related changes: * `Origin` implements `TryFrom<String>`, `TryFrom<&str>`. * All URI variants implement `TryFrom<Uri>`. * Added `Segments::prefix_of()`. * `Rocket::mount()` takes a `TryInto<Origin<'_>>` instead of `&str` for the base mount point. * Extended `errors` example with scoped catchers. * Added scoped sections to catchers guide. Internal changes: * Moved router code to `router/router.rs`.
48 lines
1.5 KiB
Rust
48 lines
1.5 KiB
Rust
#[macro_use] extern crate rocket;
|
|
|
|
use rocket::request::Request;
|
|
use rocket::http::{Cookie, CookieJar};
|
|
|
|
#[catch(404)]
|
|
fn not_found(request: &Request) -> &'static str {
|
|
request.cookies().add(Cookie::new("not_found", "404"));
|
|
"404 - Not Found"
|
|
}
|
|
|
|
#[get("/")]
|
|
fn index(cookies: &CookieJar<'_>) -> &'static str {
|
|
cookies.add(Cookie::new("index", "hi"));
|
|
"Hello, world!"
|
|
}
|
|
|
|
mod tests {
|
|
use super::*;
|
|
use rocket::local::blocking::Client;
|
|
use rocket::fairing::AdHoc;
|
|
|
|
#[test]
|
|
fn error_catcher_sets_cookies() {
|
|
let rocket = rocket::ignite()
|
|
.mount("/", routes![index])
|
|
.register("/", catchers![not_found])
|
|
.attach(AdHoc::on_request("Add Cookie", |req, _| Box::pin(async move {
|
|
req.cookies().add(Cookie::new("fairing", "woo"));
|
|
})));
|
|
|
|
let client = Client::debug(rocket).unwrap();
|
|
|
|
// Check that the index returns the `index` and `fairing` cookie.
|
|
let response = client.get("/").dispatch();
|
|
let cookies = response.cookies();
|
|
assert_eq!(cookies.iter().count(), 2);
|
|
assert_eq!(cookies.get("index").unwrap().value(), "hi");
|
|
assert_eq!(cookies.get("fairing").unwrap().value(), "woo");
|
|
|
|
// Check that the catcher returns only the `not_found` cookie.
|
|
let response = client.get("/not-existent").dispatch();
|
|
let cookies = response.cookies();
|
|
assert_eq!(cookies.iter().count(), 1);
|
|
assert_eq!(cookies.get("not_found").unwrap().value(), "404");
|
|
}
|
|
}
|