Skip to main content

Routes

Struct Routes 

Source
pub struct Routes { /* private fields */ }
Expand description

A module’s routes, with optional names for URL generation.

Routes::new()
    .get("/products", index).name("products.index")
    .get("/products/{id}", show).name("products.show")
    .post("/products", store).name("products.store")

Implementations§

Source§

impl Routes

Source

pub fn new() -> Self

An empty set of routes.

Source

pub fn get<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, AppState>, T: 'static,

Adds a route for this HTTP method (the function’s name) at path.

Source

pub fn post<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, AppState>, T: 'static,

Adds a route for this HTTP method (the function’s name) at path.

Source

pub fn put<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, AppState>, T: 'static,

Adds a route for this HTTP method (the function’s name) at path.

Source

pub fn patch<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, AppState>, T: 'static,

Adds a route for this HTTP method (the function’s name) at path.

Source

pub fn delete<H, T>(self, path: &str, handler: H) -> Self
where H: Handler<T, AppState>, T: 'static,

Adds a route for this HTTP method (the function’s name) at path.

Source

pub fn resource(self, path: &str, name: &str, resource: Resource) -> Self

The routes of a resource, like Laravel’s Route::resource: only the actions given, under path, named {name}.{action}.

ActionMethod and pathName
indexGET /productsproducts.index
createGET /products/newproducts.create
storePOST /productsproducts.store
showGET /products/{id}products.show
editGET /products/{id}/editproducts.edit
updatePUT and PATCH /products/{id}products.update
destroyDELETE /products/{id}products.destroy
Routes::new()
    .resource("/products", "products", Resource::new().index(index).show(show).destroy(destroy))
    .require_auth()
Source

pub fn route(self, path: &str, method_router: MethodRouter<AppState>) -> Self

Adds a route with any axum method router, e.g. get(show).post(update).

Source

pub fn view(self, path: &str, template: &str) -> Self

A page that needs no handler: GET path renders template with the usual globals (Laravel’s Route::view), e.g. an “About” page.

Routes::new().view("/about", "pages/about.html").name("about")
Source

pub fn redirect(self, path: &str, to: &str) -> Self

Sends path to to with a 302 (Laravel’s Route::redirect), e.g. an old address.

Source

pub fn permanent_redirect(self, path: &str, to: &str) -> Self

Like redirect, with a 301: the move is permanent.

Source

pub fn name(self, name: &str) -> Self

Names the route added just before, for use with url() and route() in templates.

§Panics

If no route has been added yet.

Source

pub fn require_auth(self) -> Self

Only logged-in users may use the routes added so far; guests are sent to the login route. Call it after adding the routes it should cover.

Source

pub fn require_verified(self) -> Self

Like require_auth, and the user must have verified their email; others are sent to the verification.notice route.

Source

pub fn require_gate(self, name: &str) -> Self

Only users the gate name lets through (App::gate, gate_async or a permission of that name, after gate_before) may use the routes added so far; guests are sent to log in, others get 403.

Source

pub fn require_role(self, role: &str) -> Self

Only users with role (the Permissions module) may use the routes added so far; guests are sent to log in, others get 403.

Source

pub fn require_permission(self, permission: &str) -> Self

Only users granted permission (the Permissions module, after gate_before) may use the routes added so far.

Source

pub fn require_ability(self, ability: &str) -> Self

Requests with an API token must have ability (User::create_token_with); sessions and unrestricted tokens pass.

Source

pub fn require_password_confirmed(self) -> Self

Users who haven’t typed their password in the last three hours are asked for it (/confirm-password, from the Auth module) before the routes added so far, e.g. billing settings. Also marks auth.

Source

pub fn guest_only(self) -> Self

Only guests may use the routes added so far; logged-in users are sent to the home route (e.g. for login and registration pages).

Source

pub fn throttle(self, max: u32, per: Duration) -> Self

Limits the routes added so far to max requests per per, counted per logged-in user or per IP address. Over the limit: 429 with Retry-After.

Source

pub fn throttle_by(self, name: &str) -> Self

Limits the routes added so far with the named limiter name (App::rate_limiter), whose rule picks the limit per request.

Source

pub fn webhook<W: Webhook>(self, path: &str) -> Self

Receives W’s webhooks at path (POST): verifies, stores once per event and processes them in the queue. See renox::webhook. The route is named webhooks.<provider>, skips CSRF and keeps working in maintenance mode.

Source

pub fn etag(self) -> Self

Gives the routes added so far an ETag (a hash of the page as sent), and answers 304 Not Modified without the body when the browser already has that version (If-None-Match). For pages fetched again and again that rarely change, e.g. a catalogue or an API list. Only GET/HEAD answers with status 200 and a body of at most 2 MB get one; streamed bodies don’t.

Source

pub fn without_csrf(self) -> Self

Lets the routes added so far be posted to without a CSRF token, for callers that have no session, such as a payment gateway’s webhook. Such a handler must check the request itself (e.g. its signature).

Source

pub fn cors(self, origins: &[&str]) -> Self

Lets browsers on origins (e.g. https://app.example.com, or * for any) call the routes added so far with fetch: answers CORS preflights and adds the Access-Control-Allow-* headers. Allows the usual methods and the Content-Type, Authorization, Accept and X-CSRF-Token headers. Use cors_layer for anything else.

Source

pub fn cors_layer(self, layer: CorsLayer) -> Self

Like cors, with a tower_http::cors::CorsLayer built by hand (renox::cors::CorsLayer), e.g. to allow credentials.

Source

pub fn route_layer<L>(self, layer: L) -> Self
where L: Layer<Route> + Clone + Send + Sync + 'static, L::Service: Service<Request> + Clone + Send + Sync + 'static, <L::Service as Service<Request>>::Response: IntoResponse + 'static, <L::Service as Service<Request>>::Error: Into<Infallible> + 'static, <L::Service as Service<Request>>::Future: Send + 'static,

Wraps the routes added so far in a tower layer (axum’s route_layer).

Source

pub fn merge(self, other: impl Into<Routes>) -> Self

Adds the routes of other, with their names and layers.

Source

pub fn fallback<H, T>(self, handler: H) -> Self
where H: Handler<T, AppState>, T: 'static,

What answers a request no route and no public file matches: a page of your own instead of the 404 page (Laravel’s Route::fallback). One per app, or per domain inside Routes::domain.

async fn missing(uri: axum::http::Uri) -> (StatusCode, String) {
    (StatusCode::NOT_FOUND, format!("Nothing at {}. Try the search.", uri.path()))
}
Routes::new().fallback(missing)
Source

pub fn domain(self, pattern: &str, routes: impl Into<Routes>) -> Self

Routes served only on hosts matching pattern, e.g. admin.example.com, or {account}.example.com with the account in DomainParams (Laravel’s Route::domain).

Routes::new()
    .get("/", home) // other hosts
    .domain(
        "admin.example.com",
        Routes::new().get("/", dashboard).name("admin.dashboard").require_auth(),
    )

A host that matches a domain gets that domain’s routes only (all modules’ routes for that pattern), plus Renox’s own (/health, the scripts, public files); every other host gets the routes without a domain. So the same path can mean different pages on different hosts. route() gives the path, as for other routes. Matching uses the Host header: behind a proxy, keep it (Caddy and nginx’s proxy_set_header Host $host do).

Source

pub fn group(self, path: &str, name: &str, routes: impl Into<Routes>) -> Self

Adds routes under a path prefix and a name prefix, like Laravel’s Route::prefix('admin')->name('admin.')->group(…). Guards added to routes cover only them; guards added after the group cover everything added so far, as usual.

Routes::new().group(
    "/admin",
    "admin.",
    Routes::new()
        .get("/", dashboard).name("dashboard") // GET /admin, `admin.dashboard`
        .get("/users", users).name("users")    // GET /admin/users, `admin.users`
        .require_auth(),
)
§Panics

If path doesn’t start with / or ends with /.

Trait Implementations§

Source§

impl Default for Routes

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Router<AppState>> for Routes

Source§

fn from(router: Router<AppState>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more