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
sourceimpl<T> Resource<T> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()>,
impl<T> Resource<T> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()>,
sourcepub fn guard<G: Guard + 'static>(self, guard: G) -> Self
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!"
}
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()))
);
}
sourcepub fn route(self, route: Route) -> Self
pub fn route(self, route: Route) -> Self
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))
);
}
sourcepub fn app_data<U: 'static>(self, data: U) -> Self
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))
);
sourcepub fn data<U: 'static>(self, data: U) -> Self
👎 Deprecated since 4.0.0: Use .app_data(Data::new(val))
instead.
pub fn data<U: 'static>(self, data: U) -> Self
Use .app_data(Data::new(val))
instead.
Add resource data after wrapping in Data<T>
.
Deprecated in favor of app_data
.
sourcepub fn to<F, I, R>(self, handler: F) -> Self where
F: Handler<I, R>,
I: FromRequest + 'static,
R: Future + 'static,
R::Output: Responder + 'static,
<R::Output as Responder>::Body: MessageBody,
<<R::Output as Responder>::Body as MessageBody>::Error: Into<Box<dyn Error>>,
pub fn to<F, I, R>(self, handler: F) -> Self where
F: Handler<I, R>,
I: FromRequest + 'static,
R: Future + 'static,
R::Output: Responder + 'static,
<R::Output as Responder>::Body: MessageBody,
<<R::Output as Responder>::Body as MessageBody>::Error: Into<Box<dyn Error>>,
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)));
sourcepub fn wrap<M>(
self,
mw: M
) -> Resource<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()>> where
M: Transform<T::Service, ServiceRequest, Response = ServiceResponse, Error = Error, InitError = ()>,
pub fn wrap<M>(
self,
mw: M
) -> Resource<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()>> where
M: Transform<T::Service, 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.
sourcepub fn wrap_fn<F, R>(
self,
mw: F
) -> Resource<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()>> where
F: Fn(ServiceRequest, &T::Service) -> R + Clone,
R: Future<Output = Result<ServiceResponse, Error>>,
pub fn wrap_fn<F, R>(
self,
mw: F
) -> Resource<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()>> where
F: Fn(ServiceRequest, &T::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)));
}
sourcepub 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,
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,
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
sourceimpl<T> HttpServiceFactory for Resource<T> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()> + 'static,
impl<T> HttpServiceFactory for Resource<T> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()> + 'static,
fn register(self, config: &mut AppService)
Auto Trait Implementations
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
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more