Handlers
Introduction
Instead of writing all of your request handling as closures in your route files, you may organize it in handlers. A handler is an async function that handles a request, and related handlers live together in a module. For example, a posts module might hold the handlers that list, show, and create blog posts. Your application keeps these modules in the src/http/handlers directory.
Handlers keep each page's code in one place and let the route file stay a short list of URIs and middleware. They also give you a natural place to test behaviour: a handler is an ordinary async function, so the modules that hold it are easy to read, review, and change.
Writing handlers
Basic handlers
A handler asks for what it needs through its arguments, and returns a response. For example, here's a posts module in src/http/handlers/posts.rs. Its index handler lists every post, show displays a single post, and store creates a post from a submitted form:
use dust::model::create;use dust::prelude::*;use dust::view::View;use crate::models::Post;#[dust::input(fills = Post)]#[validate(authenticated)]pub struct NewPost { #[validate(required, max_length(255))] pub title: String, #[validate(required)] pub body: String,}pub async fn index() -> dust::Result<View> { let posts = Post::all().await?; Ok(view("posts.index", data! { posts }))}pub async fn show(post: Post) -> View { view("posts.show", data! { post })}pub async fn store(Valid(input): Valid<NewPost>) -> dust::Result<Redirect> { let post = create!(Post { ..input }).await?; Ok(redirect!(show, &post))}Each handler takes only the arguments it needs, and dust-framework provides them when the request comes in:
showtakes the post that the route's URI names, such as post 42 for/posts/42. If no post has that ID, dust-framework responds with a404page, andshownever runs.storetakes the form's input after it has been validated. If the input is invalid, dust-framework sends the user back to the form with the errors. Otherwise,storecreates the post and redirects to the new post's page.
Each handler returns a dust::Result when it can fail, so it may use ? on any error. When a handler returns an error, dust-framework renders the error as a response, such as an error page. A handler that cannot fail returns its response directly, as show does above.
Once you've written a module, declare it in src/http/handlers/mod.rs, so your route files can use its handlers:
pub mod posts;Handlers and routes
Once you've written a handler, point a route at it in a route file, such as src/routes/web.rs. When a request matches the route's URI, dust-framework builds the handler's arguments from the request and calls the handler:
use dust::prelude::*;use crate::http::handlers::posts;pub fn routes(route: &mut Router) { route.get("/posts", posts::index); route.get("/posts/{post}", posts::show); route.post("/posts", posts::store);}Since each route is identified by its handler, you link to a route by naming its handler. For example, route!(posts::show, &post)? returns the post's URL, such as http://example.com/posts/42. To learn more, check out the routing guide's section on linking to routes.
Some handlers should only run for certain users, such as a handler that creates posts, which only logged-in users should reach. To check the request before the handler runs, attach a middleware to the handler's route. For example, Authenticate redirects guests to your login page:
use dust::auth::Authenticate;route.post("/posts", posts::store).middleware(Authenticate);Many modules hold the same set of handlers: index, create, store, show, edit, update, and destroy, which list, create, show, change, and delete a model. Rather than register a route for each of them, you may register them all at once with resource!(posts). To learn more, check out the routing guide's section on resource routes.
Organizing handler modules
A handler module usually serves one resource, and its function names follow the resource's actions. When a module uses the conventional names, resource! can register the whole set without a route for each function:
| Handler | What it does | Typical route |
|---|---|---|
index |
Lists the resource | GET /posts |
create |
Shows the form for a new resource | GET /posts/create |
store |
Saves a new resource | POST /posts |
show |
Displays one resource | GET /posts/{post} |
edit |
Shows the form to change a resource | GET /posts/{post}/edit |
update |
Saves changes to a resource | PUT, PATCH /posts/{post} |
destroy |
Deletes a resource | DELETE /posts/{post} |
Actions that don't fit those names get their own function and route, such as publish, archive, or restore. Keep the route in the route file like any other, and give the handler the same request checks it needs:
pub async fn publish(post: Post) -> dust::Result<Redirect> { // Publish the post... Ok(redirect!(show, &post))}route.post("/posts/{post}/publish", posts::publish).middleware(Authenticate);Small applications may keep a module per resource. Larger ones group modules by area, such as src/http/handlers/admin/users.rs, and register them under a prefix rather than treating the folder as a parent resource. The routing guide explains both layouts.
Handler arguments
A handler may take any number of arguments. Each argument is an extractor: a type that dust-framework builds from the request before it calls your handler. If dust-framework can't build an argument, it responds without calling the handler. For example, it responds with a 404 when a post doesn't exist, and redirects back to the form when the input is invalid.
These are the arguments handlers take most often:
| Argument | What it is |
|---|---|
A model, such as Post |
The model that the route parameter named after it finds. |
Authenticated<User> |
The logged-in user. It redirects guests to your login page. |
Auth<User> |
The authentication state, for logging users in and out, and for pages that guests see too. |
Valid<T> |
The request's input, validated into T. |
ValidRequest<T> |
The validated input and the request together, for handlers that need both. |
Query<T> |
The query string, parsed into a #[dust::query] struct T. |
Request |
The request, with its input, its session through request.session(), and the logged-in user through request.user(). |
Session |
The request's session, on routes in the web group. |
Params<T> |
The route parameters. |
Inject<T> |
A service from the container. |
Section<T> |
One of your own configuration sections. |
Arguments that read the body
Valid<T>, ValidRequest<T>, and Request all read the request's body, and a body can only be read once. So a handler may take only one of them, and it must be the handler's last argument. For example, this handler updates the logged-in user's profile. It takes the user first and the validated form last:
use dust::model::update;use dust::prelude::*;use crate::models::User;#[dust::input(fills = User)]#[validate(authenticated)]pub struct EditProfile { #[validate(required, max_length(255))] pub name: String,}pub async fn update( Authenticated(mut user): Authenticated<User>, Valid(input): Valid<EditProfile>,) -> dust::Result<Redirect> { update!(user { ..input }).await?; Ok(Redirect::back())}When the handler needs the request as well as the input, take ValidRequest<T> last and call into_parts to receive both. The validation guide shows how to record the client's IP address or read a header from the same handler.
A handler may also take any Axum extractor. However, prefer dust-framework's Query<T> and Valid<T> to Axum's Query and Form extractors. When the input is invalid, Axum's Query and Form respond with plain text and skip your application's error handling, so the user never sees their errors. With dust-framework's Query<T>, Valid<T>, and Request::parse, forms get their errors back after a redirect, JSON clients get structured JSON errors, and query structs drop bad optional filters cleanly.
When a function can't handle requests
If a route's handler takes an argument dust-framework can't build, or takes its arguments in the wrong order, the route fails to compile with the error "this function can't handle requests". The usual cause is an argument that reads the body, such as Request, placed before another argument. The error doesn't say which argument is wrong, so add #[debug_handler] to the handler to find out:
use dust::prelude::*;use dust::routing::debug_handler;#[debug_handler]pub async fn update(request: Request, session: Session) -> Redirect { // Save the form, then redirect... todo!()}With #[debug_handler], the compiler points at Request and says it can't come before the last argument. To fix the handler, move request after session. You may leave #[debug_handler] in place, because it only adds checks at compile time.
Returning responses
A handler's return type tells dust-framework how to build the HTTP response. The return type must be one value, so choose it before you write the branches:
| Return type | When to use it |
|---|---|
&'static str, String |
Plain text, such as a health message or a webhook acknowledgement. |
Json<T> |
A JSON API response. T may be a struct, a model, or a list. |
View |
A server-rendered HTML page. |
Redirect |
Sending the user to another page after a form or action. |
File, Download |
A file on disk, or generated content offered as a download. |
Streamed, JsonStream, EventStream |
A response produced over time. |
(StatusCode, T) |
A body with a status other than 200. |
Response |
Branches that return different kinds of response. |
When branches return different types, return Response and call .into_response() on each one. If the handler also uses ?, return dust::Result<Response> and wrap each branch in Ok(..):
use dust::prelude::*;pub async fn show(request: Request) -> Response { if request.wants_json() { return Json(json!({ "status": "ok" })).into_response(); } view("status.show", data! {}).into_response()}To learn about status codes, headers, cookies, redirects, files, and streams in detail, check out the responses guide.
Testing handlers
The test client sends requests through your routes, so a handler test exercises the same extractors, middleware, and error handling as production. Assert on the response rather than calling the handler directly:
use dust::model::create;use dust::testing::prelude::*;use crate::models::Post;#[dust::test]async fn the_post_page_shows_the_title(app: Application) -> dust::Result<()> { let post = create!(Post { title: "Hello", body: "World" }).await?; app.get(format!("/posts/{}", post.id)) .await .assert_ok() .assert_see("Hello"); Ok(())}A handler that returns Json is just as easy to check with assert_json_path or assert_json. To learn more, check out the testing guide's sections on HTTP tests and available assertions.