Skip to main content

Module group

Module group 

Source
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:

MethodPathBuilderName
GET/postsindexposts.index
GET/posts/newnew_formposts.new
POST/postscreateposts.create
GET/posts/{id}showposts.show
GET/posts/{id}/editeditposts.edit
PUT, PATCH/posts/{id}updateposts.update
DELETE/posts/{id}destroyposts.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§

AsyncGroup
Group for AsyncAppWithState: async handlers, guards (sync checks before the handler runs). Middleware wraps the whole app there (app.wrap(layer)), not a group.
AsyncResource
Resource for AsyncAppWithState.
Group
Routes under one path prefix for AppWithState, sharing guards and middleware. Made by app.group(prefix, |g| …).
Resource
The conventional routes of a collection (see the module docs). Made by app.resource(path, |r| …) or a group’s resource.

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, a 401, a 403).