Struct ntex::web::Resource

source ·
pub struct Resource<Err: ErrorRenderer, M = Identity, T = Filter<Err>> { /* private fields */ }
Expand description

Resource is an entry in resources table which corresponds to requested URL.

Resource in turn has at least one route. Route consists of an handlers objects and list of guards (objects that implement Guard trait). Resources and routes uses builder-like pattern for configuration. During request handling, resource object iterate through all routes and check guards for specific route, if request matches all guards, route considered matched and route handler get called.

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

fn main() {
    let app = App::new().service(
        web::resource("/")
            .route(web::get().to(|| async { HttpResponse::Ok() })));
}

If no matching route could be found, 405 response code get returned. Default behavior could be overriden with default_resource() method.

Implementations§

source§

impl<Err: ErrorRenderer> Resource<Err>

source

pub fn new<T: IntoPattern>(path: T) -> Resource<Err>

source§

impl<Err, M, T> Resource<Err, M, T>
where T: ServiceFactory<WebRequest<Err>, Response = WebRequest<Err>, Error = Err::Container, InitError = ()>, Err: ErrorRenderer,

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 match guard to a resource.

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

async fn index(data: web::types::Path<(String, String)>) -> &'static str {
    "Welcome!"
}

fn main() {
    let app = App::new()
        .service(
            web::resource("/app")
                .guard(guard::Header("content-type", "text/plain"))
                .route(web::get().to(index))
        )
        .service(
            web::resource("/app")
                .guard(guard::Header("content-type", "text/json"))
                .route(web::get().to(|| async { HttpResponse::MethodNotAllowed() }))
        );
}
source

pub fn state<D: 'static>(self, st: D) -> Self

Provide resource specific state. This method allows to add extractor configuration or specific state available via State<T> extractor. Provided state is available for all routes registered for the current resource. Resource state overrides state registered by App::state() method.

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

/// extract text data from request
async fn index(body: String) -> String {
    format!("Body {}!", body)
}

fn main() {
    let app = App::new().service(
        web::resource("/index.html")
          // limit size of the payload
          .state(web::types::PayloadConfig::new(4096))
          .route(
              // register handler
              web::get().to(index)
          ));
}
source

pub fn route<R>(self, route: R) -> Self
where R: IntoRoutes<Err>,

Register a new route.

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

fn main() {
    let app = App::new().service(
        web::resource("/").route(
            web::route()
                .guard(guard::Any(guard::Get()).or(guard::Put()))
                .guard(guard::Header("Content-Type", "text/plain"))
                .to(|| async { HttpResponse::Ok() }))
    );
}

Multiple routes could be added to a resource. Resource object uses match guards for route selection.

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

fn main() {
    let app = App::new().service(
        web::resource("/container/")
            .route([
                web::get().to(get_handler),
                web::post().to(post_handler),
                web::delete().to(delete_handler)
            ])
    );
}
source

pub fn to<F, Args>(self, handler: F) -> Self
where F: Handler<Args, Err> + 'static, Args: FromRequest<Err> + 'static, Args::Error: Into<Err::Container>,

Register a new route and add handler. This route matches all requests.

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

async fn index(req: HttpRequest) -> HttpResponse {
    unimplemented!()
}

App::new().service(web::resource("/").to(index));

This is shortcut for:

App::new().service(web::resource("/").route(web::route().to(index)));
source

pub fn filter<U, F>( self, filter: F ) -> Resource<Err, M, impl ServiceFactory<WebRequest<Err>, Response = WebRequest<Err>, Error = Err::Container, InitError = ()>>
where U: ServiceFactory<WebRequest<Err>, Response = WebRequest<Err>, Error = Err::Container>, F: IntoServiceFactory<U, WebRequest<Err>>,

Register request filter.

This is similar to App's filters, but filter get invoked on resource level.

source

pub fn wrap<U>(self, mw: U) -> Resource<Err, Stack<M, U>, T>

Register a resource middleware.

This is similar to App's middlewares, but middleware get invoked on resource level. Resource level middlewares are not allowed to change response type (i.e modify response’s body).

Note: middlewares get called in opposite order of middlewares registration.

source

pub fn default_service<F, S>(self, f: F) -> Self
where F: IntoServiceFactory<S, WebRequest<Err>>, S: ServiceFactory<WebRequest<Err>, Response = WebResponse, Error = Err::Container> + 'static, S::InitError: Debug,

Default service to be used if no matching route could be found. By default 405 response get returned. Resource does not use default handler from App or Scope.

Trait Implementations§

source§

impl<Err, M, T> WebServiceFactory<Err> for Resource<Err, M, T>
where T: ServiceFactory<WebRequest<Err>, Response = WebRequest<Err>, Error = Err::Container, InitError = ()> + 'static, M: Middleware<ServiceChain<AndThen<T::Service, ResourceRouter<Err>>, WebRequest<Err>>> + 'static, M::Service: Service<WebRequest<Err>, Response = WebResponse, Error = Err::Container>, Err: ErrorRenderer,

source§

fn register(self, config: &mut WebServiceConfig<Err>)

Auto Trait Implementations§

§

impl<Err, M, T> Freeze for Resource<Err, M, T>
where M: Freeze, T: Freeze,

§

impl<Err, M = Identity, T = Filter<Err>> !RefUnwindSafe for Resource<Err, M, T>

§

impl<Err, M = Identity, T = Filter<Err>> !Send for Resource<Err, M, T>

§

impl<Err, M = Identity, T = Filter<Err>> !Sync for Resource<Err, M, T>

§

impl<Err, M, T> Unpin for Resource<Err, M, T>
where Err: Unpin, M: Unpin, T: Unpin,

§

impl<Err, M = Identity, T = Filter<Err>> !UnwindSafe for Resource<Err, M, T>

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

§

type Output = T

Should always be Self
source§

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

§

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

§

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