Skip to main content

Route

Struct Route 

Source
pub struct Route<St: State, In = ()> { /* private fields */ }
Expand description

Connects a handler to the requests it should handle.

A route belongs to a Resource. It does not define a path itself; instead, its method and custom guards decide which requests within that resource should reach its handler.

Routes are checked in registration order. A route matches when the request method matches one of its configured methods and every custom guard accepts the request. Without a method or custom guard, it matches any request that reaches the resource.

If a route does not match, the resource tries the next one. When no route matches, the resource fallback runs and returns 405 Method Not Allowed by default.

Use helpers such as web::get() and web::post() to create method-specific routes, then attach a handler with Route::to() or Route::to_with_state(). Handler arguments are populated through FromRequest, and the returned value is converted into a response through Responder.

A route without an explicitly configured handler returns 404 Not Found when called.

use ntex::web::{self, App, HttpResponse};

App::default().service(
    web::resource("/users/{id}")
        .route(web::get().to(async || "user"))
        .route(web::delete().to(async || HttpResponse::NoContent())),
);

Implementations§

Source§

impl<St: State, In: 'static> Route<St, In>

Source

pub fn new() -> Route<St, In>

Create new route which matches any request.

Source§

impl<St: State, In: 'static> Route<St, In>

Source

pub fn method(self, method: Method) -> Self

Add method guard to the route.

App::default().service(web::resource("/path").route(
    web::route()
        .method(ntex::http::Method::CONNECT)
        .guard(guard::Header("content-type", "text/plain"))
        .to(async |req: HttpRequest| { HttpResponse::Ok() }))
);
Source

pub fn guard<F: Guard + 'static>(self, f: F) -> Self

Add a match guard to this route.

All guards registered on the route must accept the request. Guards are evaluated after the containing resource has matched. If a guard rejects the request, the resource tries its next route; if no route matches, the resource’s default service is used.

Method restrictions added by Route::method() are evaluated together with these guards.

use ntex::web::{self, guard, App};

App::default().service(
    web::resource("/items")
        .route(
            web::get()
                .guard(guard::Header("accept", "application/json"))
                .to(async || "JSON items")
        )
        .route(web::get().to(async || "Default items"))
);
Source

pub fn to<H, Args>(self, handler: H) -> Self
where H: Handler<St, Args> + 'static, Args: FromRequest<St> + 'static, Args::Error: WebResponseError<St, St::Error>,

Set the handler for this route.

Handler arguments are populated through FromRequest. Each argument must implement FromRequest trait and are evaluated before the handler is called. If extraction fails, the error is converted into a response.

The handler’s return value must implement Responder. Use Route::to_with_state() when the handler also needs a borrowed application state and the current request state.

use std::collections::HashMap;
use ntex::web;

#[derive(serde::Deserialize)]
struct UserPath {
    user_id: u32,
}

async fn show_user(
    path: web::types::Path<UserPath>,
    query: web::types::Query<HashMap<String, String>>,
) -> String {
    let format = query.get("format").map(String::as_str).unwrap_or("text");
    format!("User {} as {format}", path.user_id)
}

web::App::default().service(
    web::resource("/users/{user_id}")
        .route(web::get().to(show_user))
);
Source

pub fn to_with_state<H, Args>(self, handler: H) -> Self
where H: HandlerSt<St, In, Args> + 'static, Args: FromRequest<St> + 'static, Args::Error: WebResponseError<St, St::Error>,

Set a state-aware handler for this route.

The handler receives a shared reference to the application state, followed by the current request state and any request extractors.

use ntex::web;

struct AppState {
    greeting: &'static str,
}

impl web::State for AppState {
    type Error = web::DefaultError;
}

async fn index(
    state: &AppState,
    request_state: (),
    name: web::types::Path<String>,
) -> String {
    let _ = request_state;
    format!("{}, {}!", state.greeting, name.into_inner())
}

web::App::<AppState>::new().service(
    web::resource("/{name}").route(web::get().to_with_state(index))
);

Trait Implementations§

Source§

impl<St: State, In> Debug for Route<St, In>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<St: State, In: 'static> Default for Route<St, In>

Source§

fn default() -> Self

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

impl<St: State, In> IntoRoutes<St, In> for Route<St, In>

Source§

fn routes(self) -> Vec<Route<St, In>>

Convert into a list of routes.
Source§

impl<St: State, In: 'static> ServiceFactory<St, WebRequest<In>> for Route<St, In>

Source§

type Res = WebResponse

Response produced by the created services.
Source§

type Error = WebError<St, <St as State>::Error>

Error produced by the created services.
Source§

type Service = RouteService<St, In>

The type of Service produced by this factory.
Source§

type InitError = Failure

Error that can occur while constructing a service.
Source§

async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError>

Asynchronously creates a service using the supplied state.
Source§

async fn pipeline( &self, st: St, ) -> Result<Pipeline<Req, Self::Res, Self::Error>, Self::InitError>
where Self: 'static, St: 'static, Req: 'static,

Creates a service and wraps it with its state in a Pipeline.
Source§

fn map<F, Res>( self, f: F, ) -> ServiceChainFactory<MapFactory<F, Self, Res>, St, Req>
where Self: Sized, F: Fn(Self::Res) -> Res + Clone,

Returns a factory whose services map responses to a different type.
Source§

fn map_err<F, E>( self, f: F, ) -> ServiceChainFactory<MapErrFactory<F, Self, E>, St, Req>
where Self: Sized, F: Fn(Self::Error) -> E + Clone,

Returns a factory whose services map errors to a different type.
Source§

fn map_init_err<F, E>( self, f: F, ) -> ServiceChainFactory<MapInitErr<F, Self, E>, St, Req>
where Self: Sized, F: Fn(Self::InitError) -> E + Clone,

Maps this factory’s initialization error to a different error, returning a new service factory.
Source§

fn and_then<U, F>( self, f: F, ) -> ServiceChainFactory<AndThenFactory<Self, U>, St, Req>
where Self: Sized, U: ServiceFactory<St, Self::Res, Error = Self::Error, InitError = Self::InitError>, F: IntoServiceFactory<U, St, Self::Res>,

Chains another factory after this factory’s services. Read more
Source§

fn boxed( self, ) -> BoxServiceFactory<St, Req, Self::Res, Self::Error, Self::InitError>
where St: 'static, Req: 'static, Self: Sized + 'static,

Creates a boxed service factory.

Auto Trait Implementations§

§

impl<St, In = ()> !RefUnwindSafe for Route<St, In>

§

impl<St, In = ()> !Send for Route<St, In>

§

impl<St, In = ()> !Sync for Route<St, In>

§

impl<St, In = ()> !UnwindSafe for Route<St, In>

§

impl<St, In> Freeze for Route<St, In>

§

impl<St, In> Unpin for Route<St, In>

§

impl<St, In> UnsafeUnpin for Route<St, In>

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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<Sf, St, Req> IntoServiceFactory<Sf, St, Req> for Sf
where Sf: ServiceFactory<St, Req>,

Source§

fn into_factory(self) -> Sf

Converts this value into a service factory.
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.