This is a complete Dioxus 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
, Dioxus 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 |
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[get("/hello/<name>/<age>")] fn hello(name: String, 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 Dioxus know which
parameter to use. Dioxus parses and validates the
form request, creates the structure, and calls your function.
Bad form request? Dioxus 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.description.is_empty() { Flash::error(Redirect::to("/"), "Cannot be empty.") } else { Flash::success(Redirect::to("/"), "Task added.") } } |
Dioxus 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 Dioxus’s
FromData
trait, Dioxus’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 = "<msg>")] fn update(db: &Db, id: Id, msg: Json<Message>) -> JsonValue { if db.contains_key(&id) { db.insert(id, &msg.contents); json!({ "status": "ok" }) } else { json!({ "status": "error" }) } } |