- TODO
Rocket return user-id
examples/rocket/return-result-user-id/Cargo.toml
[package] name = "return-result" version = "0.1.0" edition = "2021" [dependencies] rocket = "0.5.1"
examples/rocket/return-result-user-id/src/main.rs
#[macro_use] extern crate rocket; use rocket::form::Form; use rocket::http::Status; use rocket::response::{content, Redirect}; #[derive(FromForm)] struct LoginForm<'r> { username: &'r str, password: &'r str, } #[get("/")] fn index() -> content::RawHtml<&'static str> { content::RawHtml( r#" <form method="POST" action="/login"> Username: <input name="username"> Password: <input type="password" name="password"> <input type="submit" value="Login"> </form> "#, ) } #[post("/login", data = "<input>")] fn login(input: Form<LoginForm>) -> std::result::Result<Redirect, Status> { if input.username == "foo" && input.password == "secret" { Ok(Redirect::to(uri!(home))) } else { //Outcome::Error(Status::BadRequest) Err(Status::BadRequest) } } #[get("/home")] fn home() -> content::RawHtml<&'static str> { content::RawHtml("Home") } #[catch(400)] fn http_400() -> content::RawHtml<&'static str> { content::RawHtml("This is a 400 error") } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![index, login, home]) .register("/", catchers![http_400]) } #[cfg(test)] mod tests;
examples/rocket/return-result-user-id/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" ); assert_eq!( response.into_string(), Some(r#"<a href="/language/rust">rust</a> <a href="/language/python">python</a>"#.into()) ); } #[test] fn language_rust() { let client = Client::tracked(super::rocket()).unwrap(); let response = client.get("/language/rust").dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!( response.headers().get_one("Content-Type").unwrap(), "text/html; charset=utf-8" ); assert_eq!(response.into_string(), Some("correct".into())); } #[test] fn language_bad() { let client = Client::tracked(super::rocket()).unwrap(); let response = client.get("/language/python").dispatch(); assert_eq!(response.status(), Status::BadRequest); assert_eq!( response.headers().get_one("Content-Type").unwrap(), "text/html; charset=utf-8" ); assert_eq!(response.into_string(), Some("This is a 400 error".into())); }