Skip to main content

Resource

Struct Resource 

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

Source

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>,

Source

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

Set resource name.

Name is used for url generation.

Source

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")
    );
Source

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)),
);
Source

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")),
);
Source

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()),
    ])
);
Source

pub fn to<Args>( self, h: impl Handler<St, Args>, ) -> ResourceServices<St, In, Out, M, F>
where Args: FromRequest<St> + 'static, Args::Error: WebResponseError<St, St::Error>,

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)).

Source

pub fn to_with_state<Args>( self, h: impl HandlerSt<St, Out, Args>, ) -> ResourceServices<St, In, Out, M, F>
where Args: FromRequest<St> + 'static, Args::Error: WebResponseError<St, St::Error>,

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)).

Source

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")
        }))
);

Trait Implementations§

Source§

impl<St: State, In, Out, M, F> Debug for Resource<St, In, Out, M, F>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<St, In, Out = In, M = Identity, F = Filter<St, In>> !RefUnwindSafe for Resource<St, In, Out, M, F>

§

impl<St, In, Out = In, M = Identity, F = Filter<St, In>> !Send for Resource<St, In, Out, M, F>

§

impl<St, In, Out = In, M = Identity, F = Filter<St, In>> !Sync for Resource<St, In, Out, M, F>

§

impl<St, In, Out = In, M = Identity, F = Filter<St, In>> !UnwindSafe for Resource<St, In, Out, M, F>

§

impl<St, In, Out, M, F> Freeze for Resource<St, In, Out, M, F>
where M: Freeze, F: Freeze,

§

impl<St, In, Out, M, F> Unpin for Resource<St, In, Out, M, F>
where M: Unpin, F: Unpin, Out: Unpin, St: Unpin, In: Unpin,

§

impl<St, In, Out, M, F> UnsafeUnpin for Resource<St, In, Out, M, F>
where M: UnsafeUnpin, F: UnsafeUnpin,

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<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.