Expand description
Route groups, guards and resources (18.35.0, #94).
A group registers routes under a shared path prefix and runs the same
guards — and, on AppWithState, the same
middleware — in front of each:
use rust_web_server::app::App;
use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
fn signed_in(request: &rust_web_server::request::Request, _: &rust_web_server::server::ConnectionInfo, _: &()) -> Result<(), Response> {
match request.header("authorization") {
Some(_) => Ok(()),
None => Err(Response::text(STATUS_CODE_REASON_PHRASE.n401_unauthorized, "sign in")),
}
}
let app = App::with_state(()).group("/admin", |admin| {
admin
.guard(signed_in)
.get("/", |_, _, _, _| Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, "dashboard"))
.resource("/posts", |posts| {
posts
.index(|_, _, _, _| Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, "all posts"))
.show(|_, params, _, _| Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, params.get("id").unwrap_or("")))
})
});Guards (before_action) are checked in the order added, outer groups
first, and apply to every route of the group whichever order they were
added in; the first Err(response) answers the request. Groups nest.
Resource registers the conventional routes for a collection:
| Method | Path | Builder | Name |
|---|---|---|---|
| GET | /posts | index | posts.index |
| GET | /posts/new | new_form | posts.new |
| POST | /posts | create | posts.create |
| GET | /posts/{id} | show | posts.show |
| GET | /posts/{id}/edit | edit | posts.edit |
| PUT, PATCH | /posts/{id} | update | posts.update |
| DELETE | /posts/{id} | destroy | posts.destroy |
new comes before {id}, so /posts/new is never taken as an id. The
names (the resource path’s last segment, then the action) work with
url_for; .name(…) on the resource changes
the prefix.
Structs§
- Async
Group GroupforAsyncAppWithState: async handlers, guards (sync checks before the handler runs). Middleware wraps the whole app there (app.wrap(layer)), not a group.- Async
Resource ResourceforAsyncAppWithState.- Group
- Routes under one path prefix for
AppWithState, sharing guards and middleware. Made byapp.group(prefix, |g| …). - Resource
- The conventional routes of a collection (see the module docs). Made by
app.resource(path, |r| …)or a group’sresource.
Functions§
- join_
path - Join a group prefix and a route pattern:
/admin+/=/admin,/admin+/posts=/admin/posts,+=/.
Type Aliases§
- Guard
- A route guard:
Ok(())lets the request through,Err(response)answers it (a redirect to the login page, a401, a403).