- POST
- Form
- context
- Template
- FromForm
- Tera
Rocket - Echo using POST
examples/rocket/echo-using-post/Cargo.toml
[package] name = "echo-using-post" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] rocket = "0.5" rocket_dyn_templates = { version = "0.1", features = ["tera"] }
examples/rocket/echo-using-post/Rocket.toml
[debug] port=8001
examples/rocket/echo-using-post/src/main.rs
#[macro_use] extern crate rocket; use rocket::form::Form; use rocket_dyn_templates::{context, Template}; #[derive(FromForm)] struct InputText<'r> { text: &'r str, } #[get("/")] fn index() -> Template { Template::render("index", context! {}) } #[post("/echo", data = "<input>")] fn echo(input: Form<InputText<'_>>) -> Template { println!("text: {:?}", input.text); Template::render( "echo", context! { text: input.text }, ) } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![index, echo]) .attach(Template::fairing()) } #[cfg(test)] mod tests;
examples/rocket/echo-using-post/src/tests.rs
use rocket::http::{ContentType, 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!(response.into_string().unwrap().contains("<h1>Echo</h1>")); } #[test] fn echo_page() { let client = Client::tracked(super::rocket()).unwrap(); let response = client .post("/echo") .header(ContentType::Form) .body("text=Foo Bar") .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("You typed in <b>Foo Bar</b>".into()) ); } #[test] fn echo_page_missing_text() { let client = Client::tracked(super::rocket()).unwrap(); let response = client .post("/echo") .header(ContentType::Form) //.body("") .dispatch(); assert_eq!(response.status(), Status::UnprocessableEntity); assert_eq!( response.headers().get_one("Content-Type").unwrap(), "text/html; charset=utf-8" ); assert!(response .into_string() .unwrap() .contains("<h1>422: Unprocessable Entity</h1>")); }
examples/rocket/echo-using-post/templates/echo.html.tera
You typed in <b>{{ text }}</b>
examples/rocket/echo-using-post/templates/index.html.tera
<h1>Echo</h1> <form method="POST" action="/echo"> <input name="text"> <input type="submit" value="Echo"> </form> <h1>Bad form</h1> Missing the text field. <form method="POST" action="/echo"> <input type="submit" value="Echo"> </form>