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("/")
        .route(web::get().to(|| HttpResponse::Ok())));

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

Implementations

Set resource name.

Name is used for url generation.

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

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

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

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

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.

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.

Default service to be used if no matching route could be found.

You can use a Route as default service.

If a default service is not registered, an empty 405 Method Not Allowed response will be sent to the client instead. Unlike Scopes, a Resource does not inherit its parent’s default service.

Trait Implementations

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Converts self into T using Into<T>. Read more

Extract a subset of the possible types in a coproduct (or get the remaining possibilities) Read more

Causes self to use its Binary implementation when Debug-formatted.

Causes self to use its Display implementation when Debug-formatted. Read more

Causes self to use its LowerExp implementation when Debug-formatted. Read more

Causes self to use its LowerHex implementation when Debug-formatted. Read more

Causes self to use its Octal implementation when Debug-formatted.

Causes self to use its Pointer implementation when Debug-formatted. Read more

Causes self to use its UpperExp implementation when Debug-formatted. Read more

Causes self to use its UpperHex implementation when Debug-formatted. Read more

Returns the argument unchanged.

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

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

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Performs the indexed conversion.

Pipes by value. This is generally the method you want to use. Read more

Borrows self and passes that borrow into the pipe function. Read more

Mutably borrows self and passes that borrow into the pipe function. Read more

Borrows self, then passes self.borrow() into the pipe function. Read more

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more

Borrows self, then passes self.as_ref() into the pipe function.

Mutably borrows self, then passes self.as_mut() into the pipe function. Read more

Borrows self, then passes self.deref() into the pipe function.

Mutably borrows self, then passes self.deref_mut() into the pipe function. Read more

The alignment of pointer.

The type for initializers.

Initializes a with the given initializer. Read more

Dereferences the given pointer. Read more

Mutably dereferences the given pointer. Read more

Drops the object pointed to by the given pointer. Read more

Should always be Self

Consumes the current HList and returns an HList with the requested shape. Read more

Immutable access to a value. Read more

Mutable access to a value. Read more

Immutable access to the Borrow<B> of a value. Read more

Mutable access to the BorrowMut<B> of a value. Read more

Immutable access to the AsRef<R> view of a value. Read more

Mutable access to the AsMut<R> view of a value. Read more

Immutable access to the Deref::Target of a value. Read more

Mutable access to the Deref::Target of a value. Read more

Calls .tap() only in debug builds, and is erased in release builds.

Calls .tap_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref_mut() only in debug builds, and is erased in release builds. Read more

Attempts to convert self into T using TryInto<T>. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more