pub struct Resource<St: State, In, Out = In, M = Identity, F = Filter<St, In>> { /* private fields */ }Expand description
Groups routes and configuration for one or more URL patterns.
A resource is useful when several routes belong to the same path. Along
with those routes, it can have its own guards, filters, middleware, name,
and fallback service. Create one with web::resource(), then register it
with App::service() or Scope::service().
For each request, the router first checks the resource’s path and guards. If they do not match, it keeps looking for another resource or scope. Once this resource is selected, its middleware and filters run, followed by its routes in registration order. The first route whose guards all pass handles the request.
When none of the routes match, the resource uses its own fallback. By
default, that fallback returns 405 Method Not Allowed.
Use Resource::route() to add guarded routes, or Resource::to() to
add an unguarded handler that accepts any request reaching the resource.
use ntex::web::{self, App, HttpResponse};
App::default().service(
web::resource("/users")
.route(web::get().to(async || "users"))
.route(web::post().to(async || HttpResponse::Created()))
.default_service(web::to(async || {
HttpResponse::MethodNotAllowed().body("Use GET or POST")
})),
);Implementations§
Source§impl<St: State, In: 'static> Resource<St, In, In>
impl<St: State, In: 'static> Resource<St, In, In>
Sourcepub fn new<T: IntoPattern>(path: T) -> Resource<St, In, In>
pub fn new<T: IntoPattern>(path: T) -> Resource<St, In, In>
Create a resource for the given path pattern or patterns.
Same as web::resource().
Source§impl<St, In, Out, M, F> Resource<St, In, Out, M, F>where
St: State,
In: 'static,
Out: 'static,
F: ServiceFactory<St, WebRequest<In>, Res = WebRequest<Out>, Error = WebError<St, St::Error>, InitError = Failure>,
impl<St, In, Out, M, F> Resource<St, In, Out, M, F>where
St: State,
In: 'static,
Out: 'static,
F: ServiceFactory<St, WebRequest<In>, Res = WebRequest<Out>, Error = WebError<St, St::Error>, InitError = Failure>,
Sourcepub fn guard<G: Guard + 'static>(self, guard: G) -> Self
pub fn guard<G: Guard + 'static>(self, guard: G) -> Self
Add a match guard to this resource.
The resource is selected only when its path and all registered guards match. If a guard rejects the request, the router can try another resource with the same path; otherwise the containing scope or application fallback is used.
Resource guards run before route selection. Use Route::guard() when
the condition should choose between routes inside one resource.
use ntex::web::{self, guard, App};
App::default()
.service(
web::resource("/items")
.guard(guard::Header("accept", "application/json"))
.to(async || "JSON items")
)
.service(
web::resource("/items")
.guard(guard::Header("accept", "text/plain"))
.to(async || "Text items")
);Sourcepub fn filter<U, R>(
self,
filter: impl IntoServiceFactory<U, St, WebRequest<Out>>,
) -> Resource<St, In, R, M, impl ServiceFactory<St, WebRequest<In>, Res = WebRequest<R>, Error = WebError<St, St::Error>, InitError = Failure>>where
U: ServiceFactory<St, WebRequest<Out>, Res = WebRequest<R>>,
U::Error: WebResponseError<St, St::Error>,
U::InitError: IntoFailure,
pub fn filter<U, R>(
self,
filter: impl IntoServiceFactory<U, St, WebRequest<Out>>,
) -> Resource<St, In, R, M, impl ServiceFactory<St, WebRequest<In>, Res = WebRequest<R>, Error = WebError<St, St::Error>, InitError = Failure>>where
U: ServiceFactory<St, WebRequest<Out>, Res = WebRequest<R>>,
U::Error: WebResponseError<St, St::Error>,
U::InitError: IntoFailure,
Registers a request filter for this resource.
The filter runs after the resource’s path and guards match, but before its routes are checked. It therefore also runs when no route matches and the resource’s default service is used.
use std::convert::Infallible;
use ntex::web::{self, App, WebRequest};
async fn item(_state: &(), item_id: usize) -> String {
format!("Item {item_id}")
}
App::new().service(
web::resource("/item")
.filter(async |req: WebRequest<()>| {
Ok::<_, Infallible>(req.map_state(|()| 10usize))
})
.route(web::get().to_with_state(item)),
);Sourcepub fn middleware<U>(
self,
mw: U,
) -> Resource<St, In, Out, WebStack<St, U, M>, F>
pub fn middleware<U>( self, mw: U, ) -> Resource<St, In, Out, WebStack<St, U, M>, F>
Registers a middleware for this resource.
The middleware runs only after the resource’s path and guards match. It wraps the resource filter, routes, and fallback service, so it can inspect or modify both the request and response. It also runs when no route matches and the resource fallback handles the request.
use ntex::web::{self, middleware, App};
App::default().service(
web::resource("/items")
.middleware(middleware::Logger::default())
.route(web::get().to(async || "Items")),
);Sourcepub fn route<R>(self, route: R) -> ResourceServices<St, In, Out, M, F>where
R: IntoRoutes<St, Out>,
pub fn route<R>(self, route: R) -> ResourceServices<St, In, Out, M, F>where
R: IntoRoutes<St, Out>,
Add one or more routes to this resource.
Routes are checked in registration order after the resource path and
resource guards match. The first route whose method and custom guards
accept the request is called. If no route matches, the resource’s
default service is used; without a custom default, it returns
405 Method Not Allowed.
A single Route or a collection of routes can be supplied.
use ntex::web::{self, App, HttpResponse};
App::default().service(
web::resource("/items").route([
web::get().to(async || "list"),
web::post().to(async || HttpResponse::Created()),
web::delete().to(async || HttpResponse::NoContent()),
])
);Sourcepub fn to<Args>(
self,
h: impl Handler<St, Args>,
) -> ResourceServices<St, In, Out, M, F>
pub fn to<Args>( self, h: impl Handler<St, Args>, ) -> ResourceServices<St, In, Out, M, F>
Register route with a handler.
The route matches every request after this resource’s path and guards
match. The handler receives request extractor values and returns a type
implementing Responder.
use ntex::web::{self, App};
async fn show_user(id: web::types::Path<u32>) -> String {
format!("User {}", id.into_inner())
}
App::default()
.service(web::resource("/users/{id}").to(show_user));This is equivalent to resource.route(web::route().to(handler)).
Sourcepub fn to_with_state<Args>(
self,
h: impl HandlerSt<St, Out, Args>,
) -> ResourceServices<St, In, Out, M, F>
pub fn to_with_state<Args>( self, h: impl HandlerSt<St, Out, Args>, ) -> ResourceServices<St, In, Out, M, F>
Register a state-aware handler as a new 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}").to_with_state(index));This is equivalent to resource.route(web::route().to_with_state(handler)).
Sourcepub fn default_service<S>(
self,
f: impl IntoServiceFactory<S, St, WebRequest<Out>>,
) -> ResourceServices<St, In, Out, M, F>where
S: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
S::Error: WebResponseError<St, St::Error>,
S::InitError: IntoFailure,
pub fn default_service<S>(
self,
f: impl IntoServiceFactory<S, St, WebRequest<Out>>,
) -> ResourceServices<St, In, Out, M, F>where
S: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
S::Error: WebResponseError<St, St::Error>,
S::InitError: IntoFailure,
Set the fallback service for this resource.
The fallback is called after the resource path and guards match but none
of its routes match, commonly because the request method is unsupported.
Without a custom fallback, the resource returns
405 Method Not Allowed. It does not delegate to a scope or application
fallback.
use ntex::web::{self, App, HttpResponse};
App::default().service(
web::resource("/items")
.route(web::get().to(async || "items"))
.default_service(web::to(async || {
HttpResponse::MethodNotAllowed().body("Use GET")
}))
);