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>
impl<St: State, In: 'static> Route<St, In>
Sourcepub fn method(self, method: Method) -> Self
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() }))
);Sourcepub fn guard<F: Guard + 'static>(self, f: F) -> Self
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"))
);Sourcepub fn to<H, Args>(self, handler: H) -> Selfwhere
H: Handler<St, Args> + 'static,
Args: FromRequest<St> + 'static,
Args::Error: WebResponseError<St, St::Error>,
pub fn to<H, Args>(self, handler: H) -> Selfwhere
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))
);Sourcepub fn to_with_state<H, Args>(self, handler: H) -> Selfwhere
H: HandlerSt<St, In, Args> + 'static,
Args: FromRequest<St> + 'static,
Args::Error: WebResponseError<St, St::Error>,
pub fn to_with_state<H, Args>(self, handler: H) -> Selfwhere
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> IntoRoutes<St, In> for Route<St, In>
impl<St: State, In> IntoRoutes<St, In> for Route<St, In>
Source§impl<St: State, In: 'static> ServiceFactory<St, WebRequest<In>> for Route<St, In>
impl<St: State, In: 'static> ServiceFactory<St, WebRequest<In>> for Route<St, In>
Source§type Res = WebResponse
type Res = WebResponse
Source§async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError>
async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError>
Source§async fn pipeline(
&self,
st: St,
) -> Result<Pipeline<Req, Self::Res, Self::Error>, Self::InitError>where
Self: 'static,
St: 'static,
Req: 'static,
async fn pipeline(
&self,
st: St,
) -> Result<Pipeline<Req, Self::Res, Self::Error>, Self::InitError>where
Self: 'static,
St: 'static,
Req: 'static,
Pipeline.