logo

Struct actix_web::Resource[][src]

pub struct Resource<T = ResourceEndpoint> { /* 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 actix_web::{web, App, HttpResponse};

fn main() {
    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!"
}

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

Register a new route.

use actix_web::{web, 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(|| HttpResponse::Ok()))
    );
}

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

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

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

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 actix_web::{web, 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
          .data(String::configure(|cfg| {
               cfg.limit(4096)
          }))
          .route(
              web::get()
                 // register handler
                 .to(index)
          ));
}

Add resource data.

Data of different types from parent contexts will still be accessible.

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

use actix_web::*;

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

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.

Register a resource middleware function.

This function accepts instance of ServiceRequest 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 actix_service::Service;
use actix_web::{web, App};
use actix_web::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)));
}

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

Convert Self to a ServiceFactory

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

Performs the conversion.

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

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

Performs the conversion.

Should always be Self

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