Struct actix_web::Resource

source ·
pub struct Resource<T = ResourceEndpoint> { /* private fields */ }
Expand description

A collection of Routes that respond to the same path pattern.

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.

§Examples

use actix_web::{web, App, HttpResponse};

let app = App::new().service(
    web::resource("/")
        .get(|| HttpResponse::Ok())
        .post(|| async { "Hello World!" })
);

If no matching route is found, an empty 405 response is returned which includes an appropriate Allow header. This default behavior can be overridden using default_service().

Implementations§

source§

impl Resource

source

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

Constructs new resource that matches a path pattern.

source§

impl<T> Resource<T>
where T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>,

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 actix_web::{web, guard, App, HttpResponse};

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

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(|| HttpResponse::MethodNotAllowed()))
    );
source

pub fn route(self, route: Route) -> Self

Register a new route.

use actix_web::{web, guard, App, HttpResponse};

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(|| HttpResponse::Ok()))
);

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

use actix_web::{web, guard, App};

let app = App::new().service(
    web::resource("/container/")
         .route(web::get().to(get_handler))
         .route(web::post().to(post_handler))
         .route(web::delete().to(delete_handler))
);
source

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

Add resource data.

Data of different types from parent contexts will still be accessible. Any Data<T> types set here can be extracted in handlers using the Data<T> extractor.

§Examples
use std::cell::Cell;
use actix_web::{web, App, HttpRequest, HttpResponse, Responder};

struct MyData {
    count: std::cell::Cell<usize>,
}

async fn handler(req: HttpRequest, counter: web::Data<MyData>) -> impl Responder {
    // note this cannot use the Data<T> extractor because it was not added with it
    let incr = *req.app_data::<usize>().unwrap();
    assert_eq!(incr, 3);

    // update counter using other value from app data
    counter.count.set(counter.count.get() + incr);

    HttpResponse::Ok().body(counter.count.get().to_string())
}

let app = App::new().service(
    web::resource("/")
        .app_data(3usize)
        .app_data(web::Data::new(MyData { count: Default::default() }))
        .route(web::get().to(handler))
);
source

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

👎Deprecated since 4.0.0: Use .app_data(Data::new(val)) instead.

Add resource data after wrapping in Data<T>.

Deprecated in favor of app_data.

source

pub fn to<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

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

use actix_web::{App, HttpRequest, HttpResponse, web};

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

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

This is shortcut for:

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

pub fn wrap<M, B>( self, mw: M, ) -> Resource<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()>>
where M: Transform<T::Service, ServiceRequest, Response = ServiceResponse<B>, Error = Error, InitError = ()> + 'static, B: MessageBody,

Registers a resource middleware.

mw is a middleware component (type), that can modify the request and response across all routes managed by this Resource.

See App::wrap for more details.

source

pub fn wrap_fn<F, R, B>( self, mw: F, ) -> Resource<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()>>
where F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static, R: Future<Output = Result<ServiceResponse<B>, Error>>, B: MessageBody,

Registers a resource function middleware.

mw is a closure that runs during inbound and/or outbound processing in the request life-cycle (request -> response), modifying request/response as necessary, across all requests handled by the Resource.

See App::wrap_fn for examples and more details.

source

pub fn default_service<F, U>(self, f: F) -> Self
where F: IntoServiceFactory<U, ServiceRequest>, U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static, U::InitError: Debug,

Sets the default service to be used if no matching route is found.

Unlike Scopes, a Resource does not inherit its parent’s default service. You can use a Route as default service.

If a custom default service is not registered, an empty 405 Method Not Allowed response with an appropriate Allow header will be sent instead.

§Examples
use actix_web::{App, HttpResponse, web};

let resource = web::resource("/test")
    .route(web::get().to(HttpResponse::Ok))
    .default_service(web::to(|| {
        HttpResponse::BadRequest()
    }));

App::new().service(resource);
source§

impl<T> Resource<T>
where T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>,

Concise routes for well-known HTTP methods.

source

pub fn get<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

Adds a GET route.

Use route if you need to add additional guards.

§Examples
web::resource("/")
    .get(|| async { "Hello World!" })
source

pub fn post<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

Adds a POST route.

Use route if you need to add additional guards.

§Examples
web::resource("/")
    .post(|| async { "Hello World!" })
source

pub fn put<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

Adds a PUT route.

Use route if you need to add additional guards.

§Examples
web::resource("/")
    .put(|| async { "Hello World!" })
source

pub fn patch<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

Adds a PATCH route.

Use route if you need to add additional guards.

§Examples
web::resource("/")
    .patch(|| async { "Hello World!" })
source

pub fn delete<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

Adds a DELETE route.

Use route if you need to add additional guards.

§Examples
web::resource("/")
    .delete(|| async { "Hello World!" })
source

pub fn head<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

Adds a HEAD route.

Use route if you need to add additional guards.

§Examples
web::resource("/")
    .head(|| async { "Hello World!" })
source

pub fn trace<F, Args>(self, handler: F) -> Self
where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static,

Adds a TRACE route.

Use route if you need to add additional guards.

§Examples
web::resource("/")
    .trace(|| async { "Hello World!" })

Trait Implementations§

source§

impl<T, B> HttpServiceFactory for Resource<T>
where T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()> + 'static, B: MessageBody + 'static,

source§

fn register(self, config: &mut AppService)

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

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

§

impl<T = ResourceEndpoint> !UnwindSafe for Resource<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

source§

type Output = T

Should always be Self
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.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

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