Struct ntex::web::Resource[][src]

pub struct Resource<Err: ErrorRenderer, T = ResourceEndpoint<Err>> { /* fields omitted */ }
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

impl<Err: ErrorRenderer> Resource<Err>[src]

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

impl<Err, T> Resource<Err, T> where
    T: ServiceFactory<Config = (), Request = WebRequest<Err>, Response = WebResponse, Error = Err::Container, InitError = ()>,
    Err: ErrorRenderer
[src]

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

Set resource name.

Name is used for url generation.

pub fn guard<G: Guard + 'static>(self, guard: G) -> Self[src]

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

pub fn route<U>(self, route: U) -> Self where
    U: IntoRoutes<Err>, 
[src]

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

pub fn data<U: 'static>(self, data: U) -> Self[src]

Provide resource specific data. This method allows to add extractor configuration or specific state available via Data<T> extractor. Provided data is available for all routes registered for the current resource. Resource data overrides data registered by App::data() 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
          .app_data(web::types::PayloadConfig::new(4096))
          .route(
              web::get()
                 // register handler
                 .to(index)
          ));
}

pub fn app_data<U: 'static>(self, data: U) -> Self[src]

Set or override application data.

This method overrides data stored with App::app_data()

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

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

pub fn filter<F>(
    self,
    filter: F
) -> Resource<Err, impl ServiceFactory<Config = (), Request = WebRequest<Err>, Response = WebResponse, Error = Err::Container, InitError = ()>> where
    F: ServiceFactory<Config = (), Request = WebRequest<Err>, Response = Either<WebRequest<Err>, WebResponse>, Error = Err::Container, InitError = ()>, 
[src]

Register request filter.

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

pub fn wrap<M>(
    self,
    mw: M
) -> Resource<Err, impl ServiceFactory<Config = (), Request = WebRequest<Err>, Response = WebResponse, Error = Err::Container, InitError = ()>> where
    M: Transform<T::Service, Request = WebRequest<Err>, Response = WebResponse, Error = Err::Container, InitError = ()>, 
[src]

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.

pub fn wrap_fn<F, R>(
    self,
    mw: F
) -> Resource<Err, impl ServiceFactory<Config = (), Request = WebRequest<Err>, Response = WebResponse, Error = Err::Container, InitError = ()>> where
    F: Fn(WebRequest<Err>, &T::Service) -> R + Clone,
    R: Future<Output = Result<WebResponse, Err::Container>>, 
[src]

Register a resource middleware function.

This function accepts instance of WebRequest type and mutable reference to the next middleware in chain.

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

use ntex::service::Service;
use ntex::web::{self, App};
use ntex::http::header::{CONTENT_TYPE, HeaderValue};

async fn index() -> &'static str {
    "Welcome!"
}

fn main() {
    let app = App::new().service(
        web::resource("/index.html")
            .wrap_fn(|req, srv| {
                let fut = srv.call(req);
                async {
                    let mut res = fut.await?;
                    res.headers_mut().insert(
                       CONTENT_TYPE, HeaderValue::from_static("text/plain"),
                    );
                    Ok(res)
                }
            })
            .route(web::get().to(index)));
}

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

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

impl<Err, T> IntoServiceFactory<T> for Resource<Err, T> where
    T: ServiceFactory<Config = (), Request = WebRequest<Err>, Response = WebResponse, Error = Err::Container, InitError = ()>,
    Err: ErrorRenderer
[src]

fn into_factory(self) -> T[src]

Convert Self to a ServiceFactory

impl<Err, T> WebServiceFactory<Err> for Resource<Err, T> where
    T: ServiceFactory<Config = (), Request = WebRequest<Err>, Response = WebResponse, Error = Err::Container, InitError = ()> + 'static,
    Err: ErrorRenderer
[src]

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

Auto Trait Implementations

impl<Err, T = ResourceEndpoint<Err>> !RefUnwindSafe for Resource<Err, T>

impl<Err, T = ResourceEndpoint<Err>> !Send for Resource<Err, T>

impl<Err, T = ResourceEndpoint<Err>> !Sync for Resource<Err, T>

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

impl<Err, T = ResourceEndpoint<Err>> !UnwindSafe for Resource<Err, T>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T> Instrument for T[src]

fn instrument(self, span: Span) -> Instrumented<Self>[src]

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

fn in_current_span(self) -> Instrumented<Self>[src]

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>[src]

Performs the conversion.