This is a complete Rocket application. It does exactly what you would expect. If you were to visit http://localhost:8000/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 12 13 | #![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; #[get("/hello/<name>/<age>")] fn hello(name: &str, age: u8) -> String { format!("Hello, {} year old named {}!", age, name) } fn main() { rocket::ignite().mount("/", routes![hello]).launch(); } |
Handling forms is simple and easy. Simply derive FromForm for your structure and let Rocket know which parameter to use. Rocket parses and validates the form request, creates the structure, and calls your function.
Bad form request? Rocket doesn’t call your function! What if you want to know if the form was bad? Simple! Change the type of task to Option or Result!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #[derive(FromForm)] struct Task { description: String, completed: bool } #[post("/", data = "<task>")] fn new(task: Form<Task>) -> Flash<Redirect> { if task.get().description.is_empty() { Flash::error(Redirect::to("/"), "Cannot be empty.") } else { Flash::success(Redirect::to("/"), "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.
Like other important features, JSON works through Rocket’s FromData trait, Rocket’s approach to deriving types from body data. It works like this: specify a data route parameter of any type that implements FromData. A value of that type will then be created automatically from the incoming request body. Best of all, you can implement FromData for your types!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #[derive(Serialize, Deserialize)] struct Message { contents: String, } #[put("/<id>", data = "<message>")] fn update(id: ID, message: JSON<Message>) -> JSON<Value> { if DB.contains_key(&id) { DB.insert(id, &message.contents); JSON(json!{ "status": "ok" }) } else { JSON(json!{ "status": "error" }) } } |