Resource

Struct Resource 

Source
pub struct Resource<T = ResourceEndpoint> { /* 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 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§

Source§

impl Resource

Source

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

Source§

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

Source

pub fn name(self, name: &str) -> Resource<T>

Set resource name.

Name is used for url generation.

Source

pub fn guard<G>(self, guard: G) -> Resource<T>
where G: Guard + 'static,

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

pub fn route(self, route: Route) -> Resource<T>

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

pub fn data<U>(self, data: U) -> Resource<T>
where U: 'static,

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

pub fn app_data<U>(self, data: U) -> Resource<T>
where U: 'static,

Add resource data.

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

Source

pub fn to<F, I, R, U>(self, handler: F) -> Resource<T>
where F: Factory<I, R, U>, I: FromRequest + 'static, R: Future<Output = U> + 'static, U: Responder + 'static,

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

pub fn wrap<M>( self, mw: M, ) -> Resource<impl ServiceFactory<Config = (), Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = ()>>
where M: Transform<<T as ServiceFactory>::Service, Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = ()>,

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 wrap_fn<F, R>( self, mw: F, ) -> Resource<impl ServiceFactory<Config = (), Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = ()>>
where F: FnMut(ServiceRequest, &mut <T as ServiceFactory>::Service) -> R + Clone, R: Future<Output = Result<ServiceResponse, Error>>,

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

pub fn default_service<F, U>(self, f: F) -> Resource<T>
where F: IntoServiceFactory<U>, U: ServiceFactory<Config = (), Request = ServiceRequest, Response = ServiceResponse, Error = Error> + 'static, <U as ServiceFactory>::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<T> HttpServiceFactory for Resource<T>
where T: ServiceFactory<Config = (), Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = ()> + 'static,

Source§

fn register(self, config: &mut AppService)

Source§

impl<T> IntoServiceFactory<T> for Resource<T>
where T: ServiceFactory<Config = (), Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = ()>,

Source§

fn into_factory(self) -> T

Convert Self to a ServiceFactory

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

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoSql for T

Source§

fn into_sql<T>(self) -> Self::Expression
where Self: Sized + AsExpression<T>,

Convert self to an expression for Diesel’s query builder. Read more
Source§

fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
where &'a Self: AsExpression<T>,

Convert &self to an expression for Diesel’s query builder. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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
Source§

impl<T> ErasedDestructor for T
where T: 'static,