This is a complete Rocket application. It does exactly what you would expect. If you were to visit /hello/John/58, you’d see:
Hello, 58 year old named John!
If someone visits a path with an <age> that isn’t a u8, Rocket doesn’t blindly call hello. Instead, it tries other matching routes or returns a 404.
1 2 3 4 5 6 7 8 9 10 11 | #[macro_use] extern crate rocket; #[get("/hello/<name>/<age>")] fn hello(name: &str, age: u8) -> String { format!("Hello, {} year old named {}!", age, name) } #[launch] fn rocket() -> _ { rocket::build().mount("/", routes![hello]) } |
Form handling is simple, declarative, and complete: derive FromForm for your structure and set the data parameter to a Form type. Rocket automatically parses and validates the form data into your structure and calls your function.
Bad form request? Rocket doesn’t call your function! Need to know what went wrong? Use a data parameter of Result! Want to rerender the form with user input and errors? Use Context! File uploads? A breeze with TempFile.
1 2 3 4 5 6 7 8 9 10 11 | #[derive(FromForm)] struct Task<'r> { #[field(validate = len(1..))] description: &'r str, completed: bool } #[post("/", data = "<task>")] fn new(task: Form<Task<'_>>) -> Flash<Redirect> { Flash::success(Redirect::to(uri!(home)), "Task added.") } |
Rocket has first-class support for JSON, right out of the box. Simply derive Deserialize or Serialize to receive or return JSON, respectively.
Look familiar? Forms, JSON, and all kinds of body data types work through Rocket’s FromData trait, Rocket’s approach to deriving types from body data. A data route parameter can be any type that implements FromData. A value of that type will be deserialized automatically from the incoming request body. You can even implement FromData for your own types!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #[derive(Serialize, Deserialize)] struct Message<'r> { contents: &'r str, } #[put("/<id>", data = "<msg>")] fn update(db: &Db, id: Id, msg: Json<Message<'_>>) -> Value { if db.contains_key(&id) { db.insert(id, msg.contents); json!({ "status": "ok" }) } else { json!({ "status": "error" }) } } |