Rocket - Path parameters
Instead of passing parameters in the Query string in a GET request we can also use the path to pass parameters. This is especially interesgint if we would like to make the pages indexable by search engines.
- e.g. in a blog engine the path can be mapped to a blog entry
- In a social site we might want to have a separate page for each users.
examples/rocket/path-parameters/src/main.rs
#[macro_use] extern crate rocket; use rocket::response::content; #[get("/")] fn index() -> content::RawHtml<String> { let html = String::from( r#" <a href="/user/42">User 42</a><br> <a href="/user/foo">User foo - not valid</a><br> "#, ); content::RawHtml(html) } #[get("/user/<uid>")] fn user(uid: usize) -> content::RawHtml<String> { let html = format!("User ID: {uid}"); content::RawHtml(html) } #[launch] fn rocket() -> _ { rocket::build().mount("/", routes![index, user]) } #[cfg(test)] mod tests;
examples/rocket/path-parameters/src/tests.rs
use rocket::http::Status; use rocket::local::blocking::Client; #[test] fn main_page() { let client = Client::tracked(super::rocket()).unwrap(); let response = client.get("/").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!( response.headers().get_one("Content-Type").unwrap(), "text/html; charset=utf-8" ); let html = response.into_string().unwrap(); assert!(html.contains(r#"<a href="/user/42">User 42</a><br>"#)); } #[test] fn valid_user() { let client = Client::tracked(super::rocket()).unwrap(); let response = client.get("/user/42").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!( response.headers().get_one("Content-Type").unwrap(), "text/html; charset=utf-8" ); let html = response.into_string().unwrap(); assert_eq!(html, "User ID: 42"); } #[test] fn invalid_user() { let client = Client::tracked(super::rocket()).unwrap(); let response = client.get("/user/foo").dispatch(); assert_eq!(response.status(), Status::UnprocessableEntity); // 422 }