2021-12-07 15:53:04 +00:00
|
|
|
use std::{cell::RefCell, fmt, future::Future, rc::Rc};
|
2019-03-02 06:51:32 +00:00
|
|
|
|
2021-12-07 15:53:04 +00:00
|
|
|
use actix_http::{body::MessageBody, Extensions, Request};
|
2019-03-02 06:51:32 +00:00
|
|
|
use actix_service::{
|
2021-12-04 19:40:47 +00:00
|
|
|
apply, apply_fn_factory, boxed, IntoServiceFactory, ServiceFactory, ServiceFactoryExt,
|
|
|
|
Transform,
|
2019-03-02 06:51:32 +00:00
|
|
|
};
|
2021-04-01 14:26:13 +00:00
|
|
|
use futures_util::future::FutureExt as _;
|
2019-03-02 06:51:32 +00:00
|
|
|
|
2021-12-04 19:40:47 +00:00
|
|
|
use crate::{
|
|
|
|
app_service::{AppEntry, AppInit, AppRoutingFactory},
|
|
|
|
config::ServiceConfig,
|
|
|
|
data::{Data, DataFactory, FnDataFactory},
|
|
|
|
dev::ResourceDef,
|
|
|
|
error::Error,
|
|
|
|
resource::Resource,
|
|
|
|
route::Route,
|
|
|
|
service::{
|
|
|
|
AppServiceFactory, BoxedHttpServiceFactory, HttpServiceFactory, ServiceFactoryWrapper,
|
|
|
|
ServiceRequest, ServiceResponse,
|
|
|
|
},
|
2019-03-06 23:47:15 +00:00
|
|
|
};
|
2019-03-02 06:51:32 +00:00
|
|
|
|
2019-03-03 06:03:45 +00:00
|
|
|
/// Application builder - structure that follows the builder pattern
|
|
|
|
/// for building application instances.
|
2021-12-07 15:53:04 +00:00
|
|
|
pub struct App<T> {
|
2019-04-13 21:50:54 +00:00
|
|
|
endpoint: T,
|
2019-11-20 17:33:22 +00:00
|
|
|
services: Vec<Box<dyn AppServiceFactory>>,
|
2021-12-04 19:40:47 +00:00
|
|
|
default: Option<Rc<BoxedHttpServiceFactory>>,
|
2019-04-13 21:50:54 +00:00
|
|
|
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
2019-06-28 04:43:52 +00:00
|
|
|
data_factories: Vec<FnDataFactory>,
|
2019-04-13 21:50:54 +00:00
|
|
|
external: Vec<ResourceDef>,
|
2019-12-20 11:13:09 +00:00
|
|
|
extensions: Extensions,
|
2019-03-02 06:51:32 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 15:53:04 +00:00
|
|
|
impl App<AppEntry> {
|
2019-03-17 03:17:27 +00:00
|
|
|
/// Create application builder. Application can be configured with a builder-like pattern.
|
2020-06-22 19:09:48 +00:00
|
|
|
#[allow(clippy::new_without_default)]
|
2019-03-02 06:51:32 +00:00
|
|
|
pub fn new() -> Self {
|
2021-06-25 12:19:42 +00:00
|
|
|
let factory_ref = Rc::new(RefCell::new(None));
|
|
|
|
|
2019-03-02 19:53:05 +00:00
|
|
|
App {
|
2021-06-25 12:19:42 +00:00
|
|
|
endpoint: AppEntry::new(factory_ref.clone()),
|
2019-06-28 04:43:52 +00:00
|
|
|
data_factories: Vec::new(),
|
2019-04-13 21:50:54 +00:00
|
|
|
services: Vec::new(),
|
|
|
|
default: None,
|
2021-06-25 12:19:42 +00:00
|
|
|
factory_ref,
|
2019-04-13 21:50:54 +00:00
|
|
|
external: Vec::new(),
|
2019-12-20 11:13:09 +00:00
|
|
|
extensions: Extensions::new(),
|
2019-03-02 19:53:05 +00:00
|
|
|
}
|
2019-03-02 06:51:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-07 15:53:04 +00:00
|
|
|
impl<T> App<T> {
|
2021-06-24 14:10:51 +00:00
|
|
|
/// Set application (root level) data.
|
2019-03-02 06:51:32 +00:00
|
|
|
///
|
2021-06-24 14:10:51 +00:00
|
|
|
/// Application data stored with `App::app_data()` method is available through the
|
|
|
|
/// [`HttpRequest::app_data`](crate::HttpRequest::app_data) method at runtime.
|
|
|
|
///
|
|
|
|
/// # [`Data<T>`]
|
|
|
|
/// Any [`Data<T>`] type added here can utilize it's extractor implementation in handlers.
|
|
|
|
/// Types not wrapped in `Data<T>` cannot use this extractor. See [its docs](Data<T>) for more
|
|
|
|
/// about its usage and patterns.
|
2019-03-03 06:11:24 +00:00
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2019-03-03 06:11:24 +00:00
|
|
|
/// use std::cell::Cell;
|
2021-06-24 14:10:51 +00:00
|
|
|
/// use actix_web::{web, App, HttpRequest, HttpResponse, Responder};
|
2019-03-03 06:11:24 +00:00
|
|
|
///
|
2019-03-17 03:17:27 +00:00
|
|
|
/// struct MyData {
|
2021-06-24 14:10:51 +00:00
|
|
|
/// count: std::cell::Cell<usize>,
|
2019-03-03 06:11:24 +00:00
|
|
|
/// }
|
|
|
|
///
|
2021-06-24 14:10:51 +00:00
|
|
|
/// 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())
|
2019-03-03 06:11:24 +00:00
|
|
|
/// }
|
|
|
|
///
|
2021-06-24 14:10:51 +00:00
|
|
|
/// let app = App::new().service(
|
|
|
|
/// web::resource("/")
|
|
|
|
/// .app_data(3usize)
|
|
|
|
/// .app_data(web::Data::new(MyData { count: Default::default() }))
|
|
|
|
/// .route(web::get().to(handler))
|
|
|
|
/// );
|
2019-03-03 06:11:24 +00:00
|
|
|
/// ```
|
2021-06-24 14:10:51 +00:00
|
|
|
///
|
|
|
|
/// # Shared Mutable State
|
|
|
|
/// [`HttpServer::new`](crate::HttpServer::new) accepts an application factory rather than an
|
|
|
|
/// application instance; the factory closure is called on each worker thread independently.
|
|
|
|
/// Therefore, if you want to share a data object between different workers, a shareable object
|
|
|
|
/// needs to be created first, outside the `HttpServer::new` closure and cloned into it.
|
|
|
|
/// [`Data<T>`] is an example of such a sharable object.
|
|
|
|
///
|
|
|
|
/// ```ignore
|
|
|
|
/// let counter = web::Data::new(AppStateWithCounter {
|
|
|
|
/// counter: Mutex::new(0),
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// HttpServer::new(move || {
|
|
|
|
/// // move counter object into the closure and clone for each worker
|
|
|
|
///
|
|
|
|
/// App::new()
|
|
|
|
/// .app_data(counter.clone())
|
|
|
|
/// .route("/", web::get().to(handler))
|
|
|
|
/// })
|
|
|
|
/// ```
|
|
|
|
pub fn app_data<U: 'static>(mut self, ext: U) -> Self {
|
|
|
|
self.extensions.insert(ext);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Add application (root) data after wrapping in `Data<T>`.
|
|
|
|
///
|
|
|
|
/// Deprecated in favor of [`app_data`](Self::app_data).
|
2021-06-22 14:50:58 +00:00
|
|
|
#[deprecated(since = "4.0.0", note = "Use `.app_data(Data::new(val))` instead.")]
|
2021-01-15 23:37:33 +00:00
|
|
|
pub fn data<U: 'static>(self, data: U) -> Self {
|
|
|
|
self.app_data(Data::new(data))
|
2019-03-02 06:51:32 +00:00
|
|
|
}
|
|
|
|
|
2021-06-22 14:50:58 +00:00
|
|
|
/// Add application data factory. This function is similar to `.data()` but it accepts a
|
|
|
|
/// "data factory". Data values are constructed asynchronously during application
|
|
|
|
/// initialization, before the server starts accepting requests.
|
2019-11-20 17:33:22 +00:00
|
|
|
pub fn data_factory<F, Out, D, E>(mut self, data: F) -> Self
|
2019-06-28 04:43:52 +00:00
|
|
|
where
|
|
|
|
F: Fn() -> Out + 'static,
|
2019-11-20 17:33:22 +00:00
|
|
|
Out: Future<Output = Result<D, E>> + 'static,
|
|
|
|
D: 'static,
|
|
|
|
E: std::fmt::Debug,
|
2019-06-28 04:43:52 +00:00
|
|
|
{
|
|
|
|
self.data_factories.push(Box::new(move || {
|
2019-11-20 17:33:22 +00:00
|
|
|
{
|
|
|
|
let fut = data();
|
|
|
|
async move {
|
|
|
|
match fut.await {
|
|
|
|
Err(e) => {
|
|
|
|
log::error!("Can not construct data instance: {:?}", e);
|
|
|
|
Err(())
|
|
|
|
}
|
|
|
|
Ok(data) => {
|
|
|
|
let data: Box<dyn DataFactory> = Box::new(Data::new(data));
|
|
|
|
Ok(data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
.boxed_local()
|
2019-06-28 04:43:52 +00:00
|
|
|
}));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-03 22:09:31 +00:00
|
|
|
/// Run external configuration as part of the application building
|
|
|
|
/// process
|
|
|
|
///
|
|
|
|
/// This function is useful for moving parts of configuration to a
|
|
|
|
/// different module or even library. For example,
|
|
|
|
/// some of the resource's configuration could be moved to different module.
|
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2021-01-15 23:37:33 +00:00
|
|
|
/// use actix_web::{web, App, HttpResponse};
|
2019-04-03 22:09:31 +00:00
|
|
|
///
|
|
|
|
/// // this function could be located in different module
|
2019-04-15 14:32:49 +00:00
|
|
|
/// fn config(cfg: &mut web::ServiceConfig) {
|
2019-04-03 22:09:31 +00:00
|
|
|
/// cfg.service(web::resource("/test")
|
|
|
|
/// .route(web::get().to(|| HttpResponse::Ok()))
|
|
|
|
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
|
|
|
|
/// );
|
|
|
|
/// }
|
|
|
|
///
|
2021-01-15 23:37:33 +00:00
|
|
|
/// App::new()
|
|
|
|
/// .configure(config) // <- register resources
|
|
|
|
/// .route("/index.html", web::get().to(|| HttpResponse::Ok()));
|
2019-04-03 22:09:31 +00:00
|
|
|
/// ```
|
2019-04-13 21:50:54 +00:00
|
|
|
pub fn configure<F>(mut self, f: F) -> Self
|
2019-04-03 22:09:31 +00:00
|
|
|
where
|
2019-05-10 21:44:49 +00:00
|
|
|
F: FnOnce(&mut ServiceConfig),
|
2019-04-03 22:09:31 +00:00
|
|
|
{
|
2019-04-15 14:32:49 +00:00
|
|
|
let mut cfg = ServiceConfig::new();
|
2019-04-03 22:09:31 +00:00
|
|
|
f(&mut cfg);
|
2019-04-13 21:50:54 +00:00
|
|
|
self.services.extend(cfg.services);
|
|
|
|
self.external.extend(cfg.external);
|
2021-01-15 23:37:33 +00:00
|
|
|
self.extensions.extend(cfg.app_data);
|
2019-04-13 21:50:54 +00:00
|
|
|
self
|
2019-04-03 22:09:31 +00:00
|
|
|
}
|
|
|
|
|
2019-03-06 23:47:15 +00:00
|
|
|
/// Configure route for a specific path.
|
|
|
|
///
|
|
|
|
/// This is a simplified version of the `App::service()` method.
|
2019-03-17 03:17:27 +00:00
|
|
|
/// This method can be used multiple times with same path, in that case
|
2019-03-06 23:47:15 +00:00
|
|
|
/// multiple resources with one route would be registered for same resource path.
|
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2019-03-07 22:01:52 +00:00
|
|
|
/// use actix_web::{web, App, HttpResponse};
|
2019-03-06 23:47:15 +00:00
|
|
|
///
|
2019-11-21 15:34:04 +00:00
|
|
|
/// async fn index(data: web::Path<(String, String)>) -> &'static str {
|
2019-03-06 23:47:15 +00:00
|
|
|
/// "Welcome!"
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
|
|
|
/// .route("/test1", web::get().to(index))
|
|
|
|
/// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-04-13 21:50:54 +00:00
|
|
|
pub fn route(self, path: &str, mut route: Route) -> Self {
|
2019-03-06 23:47:15 +00:00
|
|
|
self.service(
|
|
|
|
Resource::new(path)
|
|
|
|
.add_guards(route.take_guards())
|
|
|
|
.route(route),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-02-11 22:39:54 +00:00
|
|
|
/// Register HTTP service.
|
2019-03-17 04:35:02 +00:00
|
|
|
///
|
|
|
|
/// Http service is any type that implements `HttpServiceFactory` trait.
|
|
|
|
///
|
2021-02-10 12:12:03 +00:00
|
|
|
/// Actix Web provides several services implementations:
|
2019-03-17 04:35:02 +00:00
|
|
|
///
|
|
|
|
/// * *Resource* is an entry in resource table which corresponds to requested URL.
|
|
|
|
/// * *Scope* is a set of resources with common root path.
|
|
|
|
/// * "StaticFiles" is a service for static files support
|
2019-04-13 21:50:54 +00:00
|
|
|
pub fn service<F>(mut self, factory: F) -> Self
|
2019-03-06 06:10:08 +00:00
|
|
|
where
|
2019-04-13 21:50:54 +00:00
|
|
|
F: HttpServiceFactory + 'static,
|
2019-03-06 06:10:08 +00:00
|
|
|
{
|
2019-04-13 21:50:54 +00:00
|
|
|
self.services
|
|
|
|
.push(Box::new(ServiceFactoryWrapper::new(factory)));
|
|
|
|
self
|
2019-03-06 06:10:08 +00:00
|
|
|
}
|
|
|
|
|
2019-04-14 05:25:00 +00:00
|
|
|
/// Default service to be used if no matching resource could be found.
|
|
|
|
///
|
|
|
|
/// It is possible to use services like `Resource`, `Route`.
|
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2019-04-14 05:25:00 +00:00
|
|
|
/// use actix_web::{web, App, HttpResponse};
|
|
|
|
///
|
2019-11-21 15:34:04 +00:00
|
|
|
/// async fn index() -> &'static str {
|
2019-04-14 05:25:00 +00:00
|
|
|
/// "Welcome!"
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
|
|
|
/// .service(
|
|
|
|
/// web::resource("/index.html").route(web::get().to(index)))
|
|
|
|
/// .default_service(
|
|
|
|
/// web::route().to(|| HttpResponse::NotFound()));
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// It is also possible to use static files as default service.
|
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2019-04-14 05:25:00 +00:00
|
|
|
/// use actix_web::{web, App, HttpResponse};
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
|
|
|
/// .service(
|
|
|
|
/// web::resource("/index.html").to(|| HttpResponse::Ok()))
|
|
|
|
/// .default_service(
|
2019-06-15 15:47:06 +00:00
|
|
|
/// web::to(|| HttpResponse::NotFound())
|
2019-04-14 05:25:00 +00:00
|
|
|
/// );
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-12-04 19:40:47 +00:00
|
|
|
pub fn default_service<F, U>(mut self, svc: F) -> Self
|
2019-03-28 19:32:59 +00:00
|
|
|
where
|
2021-01-03 23:47:04 +00:00
|
|
|
F: IntoServiceFactory<U, ServiceRequest>,
|
2019-11-20 17:33:22 +00:00
|
|
|
U: ServiceFactory<
|
2021-01-03 23:47:04 +00:00
|
|
|
ServiceRequest,
|
2019-05-12 15:34:51 +00:00
|
|
|
Config = (),
|
2019-04-13 21:50:54 +00:00
|
|
|
Response = ServiceResponse,
|
|
|
|
Error = Error,
|
|
|
|
> + 'static,
|
2019-04-14 05:25:00 +00:00
|
|
|
U::InitError: fmt::Debug,
|
2019-03-28 19:32:59 +00:00
|
|
|
{
|
2021-12-04 19:40:47 +00:00
|
|
|
let svc = svc
|
|
|
|
.into_factory()
|
|
|
|
.map(|res| res.map_into_boxed_body())
|
|
|
|
.map_init_err(|e| log::error!("Can not construct default service: {:?}", e));
|
|
|
|
|
|
|
|
self.default = Some(Rc::new(boxed::factory(svc)));
|
2019-03-28 19:32:59 +00:00
|
|
|
|
2019-04-13 21:50:54 +00:00
|
|
|
self
|
2019-03-28 19:32:59 +00:00
|
|
|
}
|
2019-03-02 19:53:05 +00:00
|
|
|
|
2019-04-13 21:50:54 +00:00
|
|
|
/// Register an external resource.
|
2019-04-03 22:09:31 +00:00
|
|
|
///
|
2019-04-13 21:50:54 +00:00
|
|
|
/// External resources are useful for URL generation purposes only
|
|
|
|
/// and are never considered for matching at request time. Calls to
|
|
|
|
/// `HttpRequest::url_for()` will work as expected.
|
2019-04-03 22:09:31 +00:00
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2019-04-13 21:50:54 +00:00
|
|
|
/// use actix_web::{web, App, HttpRequest, HttpResponse, Result};
|
2019-04-03 22:09:31 +00:00
|
|
|
///
|
2019-11-21 15:34:04 +00:00
|
|
|
/// async fn index(req: HttpRequest) -> Result<HttpResponse> {
|
2019-04-13 21:50:54 +00:00
|
|
|
/// let url = req.url_for("youtube", &["asdlkjqme"])?;
|
|
|
|
/// assert_eq!(url.as_str(), "https://youtube.com/watch/asdlkjqme");
|
|
|
|
/// Ok(HttpResponse::Ok().into())
|
2019-04-03 22:09:31 +00:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
2019-04-13 21:50:54 +00:00
|
|
|
/// .service(web::resource("/index.html").route(
|
|
|
|
/// web::get().to(index)))
|
|
|
|
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}");
|
2019-04-03 22:09:31 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
2019-04-13 21:50:54 +00:00
|
|
|
pub fn external_resource<N, U>(mut self, name: N, url: U) -> Self
|
2019-04-03 22:09:31 +00:00
|
|
|
where
|
2019-04-13 21:50:54 +00:00
|
|
|
N: AsRef<str>,
|
|
|
|
U: AsRef<str>,
|
2019-04-03 22:09:31 +00:00
|
|
|
{
|
2019-04-13 21:50:54 +00:00
|
|
|
let mut rdef = ResourceDef::new(url.as_ref());
|
2021-08-06 21:42:31 +00:00
|
|
|
rdef.set_name(name.as_ref());
|
2019-04-13 21:50:54 +00:00
|
|
|
self.external.push(rdef);
|
2019-04-03 22:09:31 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-13 21:50:54 +00:00
|
|
|
/// Registers middleware, in the form of a middleware component (type),
|
|
|
|
/// that runs during inbound and/or outbound processing in the request
|
2020-04-21 03:09:35 +00:00
|
|
|
/// life-cycle (request -> response), modifying request/response as
|
2019-04-13 21:50:54 +00:00
|
|
|
/// necessary, across all requests managed by the *Application*.
|
2019-03-04 05:02:01 +00:00
|
|
|
///
|
2019-04-29 16:26:12 +00:00
|
|
|
/// Use middleware when you need to read or modify *every* request or
|
2019-04-29 16:14:36 +00:00
|
|
|
/// response in some way.
|
|
|
|
///
|
2019-04-29 16:26:12 +00:00
|
|
|
/// Notice that the keyword for registering middleware is `wrap`. As you
|
2019-04-29 16:14:36 +00:00
|
|
|
/// register middleware using `wrap` in the App builder, imagine wrapping
|
|
|
|
/// layers around an inner App. The first middleware layer exposed to a
|
|
|
|
/// Request is the outermost layer-- the *last* registered in
|
2019-04-29 16:26:12 +00:00
|
|
|
/// the builder chain. Consequently, the *first* middleware registered
|
2019-04-29 16:14:36 +00:00
|
|
|
/// in the builder chain is the *last* to execute during request processing.
|
2019-03-04 05:02:01 +00:00
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2019-04-13 21:50:54 +00:00
|
|
|
/// use actix_service::Service;
|
|
|
|
/// use actix_web::{middleware, web, App};
|
2021-12-05 14:37:20 +00:00
|
|
|
/// use actix_web::http::header::{CONTENT_TYPE, HeaderValue};
|
2019-03-04 05:02:01 +00:00
|
|
|
///
|
2019-11-21 15:34:04 +00:00
|
|
|
/// async fn index() -> &'static str {
|
2019-03-06 23:47:15 +00:00
|
|
|
/// "Welcome!"
|
2019-03-04 05:02:01 +00:00
|
|
|
/// }
|
2019-03-02 06:51:32 +00:00
|
|
|
///
|
|
|
|
/// fn main() {
|
2019-03-03 06:03:45 +00:00
|
|
|
/// let app = App::new()
|
2019-04-13 21:50:54 +00:00
|
|
|
/// .wrap(middleware::Logger::default())
|
|
|
|
/// .route("/index.html", web::get().to(index));
|
2019-03-02 06:51:32 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
2021-12-07 15:53:04 +00:00
|
|
|
pub fn wrap<M, B, B1>(
|
2019-03-02 06:51:32 +00:00
|
|
|
self,
|
2019-11-20 17:33:22 +00:00
|
|
|
mw: M,
|
2019-04-13 21:50:54 +00:00
|
|
|
) -> App<
|
2019-11-20 17:33:22 +00:00
|
|
|
impl ServiceFactory<
|
2021-01-03 23:47:04 +00:00
|
|
|
ServiceRequest,
|
2019-05-12 15:34:51 +00:00
|
|
|
Config = (),
|
2019-03-02 06:51:32 +00:00
|
|
|
Response = ServiceResponse<B1>,
|
2019-03-10 23:35:38 +00:00
|
|
|
Error = Error,
|
2019-03-02 06:51:32 +00:00
|
|
|
InitError = (),
|
|
|
|
>,
|
|
|
|
>
|
|
|
|
where
|
2021-12-07 15:53:04 +00:00
|
|
|
T: ServiceFactory<
|
|
|
|
ServiceRequest,
|
|
|
|
Response = ServiceResponse<B>,
|
|
|
|
Error = Error,
|
|
|
|
Config = (),
|
|
|
|
InitError = (),
|
|
|
|
>,
|
|
|
|
B: MessageBody,
|
2019-03-05 05:37:57 +00:00
|
|
|
M: Transform<
|
2019-03-02 06:51:32 +00:00
|
|
|
T::Service,
|
2021-01-03 23:47:04 +00:00
|
|
|
ServiceRequest,
|
2019-03-02 06:51:32 +00:00
|
|
|
Response = ServiceResponse<B1>,
|
2019-03-10 23:35:38 +00:00
|
|
|
Error = Error,
|
2019-03-02 06:51:32 +00:00
|
|
|
InitError = (),
|
|
|
|
>,
|
|
|
|
B1: MessageBody,
|
|
|
|
{
|
2019-04-13 21:50:54 +00:00
|
|
|
App {
|
2019-11-20 17:33:22 +00:00
|
|
|
endpoint: apply(mw, self.endpoint),
|
2019-06-28 04:43:52 +00:00
|
|
|
data_factories: self.data_factories,
|
2019-03-02 06:51:32 +00:00
|
|
|
services: self.services,
|
|
|
|
default: self.default,
|
|
|
|
factory_ref: self.factory_ref,
|
2019-03-09 22:06:24 +00:00
|
|
|
external: self.external,
|
2019-12-20 11:13:09 +00:00
|
|
|
extensions: self.extensions,
|
2019-03-02 06:51:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-01 18:52:05 +00:00
|
|
|
/// Registers middleware, in the form of a closure, that runs during inbound
|
2020-04-21 03:09:35 +00:00
|
|
|
/// and/or outbound processing in the request life-cycle (request -> response),
|
2019-04-01 18:52:05 +00:00
|
|
|
/// modifying request/response as necessary, across all requests managed by
|
2019-04-13 21:50:54 +00:00
|
|
|
/// the *Application*.
|
2019-04-01 18:52:05 +00:00
|
|
|
///
|
|
|
|
/// Use middleware when you need to read or modify *every* request or response in some way.
|
|
|
|
///
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2019-04-13 21:50:54 +00:00
|
|
|
/// use actix_service::Service;
|
|
|
|
/// use actix_web::{web, App};
|
2021-12-05 14:37:20 +00:00
|
|
|
/// use actix_web::http::header::{CONTENT_TYPE, HeaderValue};
|
2019-04-13 21:50:54 +00:00
|
|
|
///
|
2019-11-21 15:34:04 +00:00
|
|
|
/// async fn index() -> &'static str {
|
2019-04-13 21:50:54 +00:00
|
|
|
/// "Welcome!"
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
2019-11-20 17:33:22 +00:00
|
|
|
/// .wrap_fn(|req, srv| {
|
|
|
|
/// let fut = srv.call(req);
|
|
|
|
/// async {
|
|
|
|
/// let mut res = fut.await?;
|
2019-04-13 21:50:54 +00:00
|
|
|
/// res.headers_mut().insert(
|
|
|
|
/// CONTENT_TYPE, HeaderValue::from_static("text/plain"),
|
|
|
|
/// );
|
2019-11-20 17:33:22 +00:00
|
|
|
/// Ok(res)
|
|
|
|
/// }
|
|
|
|
/// })
|
2019-04-13 21:50:54 +00:00
|
|
|
/// .route("/index.html", web::get().to(index));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-12-07 15:53:04 +00:00
|
|
|
pub fn wrap_fn<F, R, B, B1>(
|
2019-03-25 20:43:02 +00:00
|
|
|
self,
|
|
|
|
mw: F,
|
2019-04-13 21:50:54 +00:00
|
|
|
) -> App<
|
2019-11-20 17:33:22 +00:00
|
|
|
impl ServiceFactory<
|
2021-01-03 23:47:04 +00:00
|
|
|
ServiceRequest,
|
2019-05-12 15:34:51 +00:00
|
|
|
Config = (),
|
2019-03-25 20:43:02 +00:00
|
|
|
Response = ServiceResponse<B1>,
|
|
|
|
Error = Error,
|
|
|
|
InitError = (),
|
|
|
|
>,
|
|
|
|
>
|
|
|
|
where
|
2021-12-07 15:53:04 +00:00
|
|
|
T: ServiceFactory<
|
|
|
|
ServiceRequest,
|
|
|
|
Response = ServiceResponse<B>,
|
|
|
|
Error = Error,
|
|
|
|
Config = (),
|
|
|
|
InitError = (),
|
|
|
|
>,
|
|
|
|
B: MessageBody,
|
2021-02-07 01:00:40 +00:00
|
|
|
F: Fn(ServiceRequest, &T::Service) -> R + Clone,
|
2019-11-20 17:33:22 +00:00
|
|
|
R: Future<Output = Result<ServiceResponse<B1>, Error>>,
|
2021-12-07 15:53:04 +00:00
|
|
|
B1: MessageBody,
|
2019-03-25 20:43:02 +00:00
|
|
|
{
|
2019-11-20 17:33:22 +00:00
|
|
|
App {
|
|
|
|
endpoint: apply_fn_factory(self.endpoint, mw),
|
|
|
|
data_factories: self.data_factories,
|
|
|
|
services: self.services,
|
|
|
|
default: self.default,
|
|
|
|
factory_ref: self.factory_ref,
|
|
|
|
external: self.external,
|
2019-12-20 11:13:09 +00:00
|
|
|
extensions: self.extensions,
|
2019-11-20 17:33:22 +00:00
|
|
|
}
|
2019-03-25 20:43:02 +00:00
|
|
|
}
|
2019-03-02 06:51:32 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 15:53:04 +00:00
|
|
|
impl<T, B> IntoServiceFactory<AppInit<T, B>, Request> for App<T>
|
2019-03-02 06:51:32 +00:00
|
|
|
where
|
2019-04-13 21:50:54 +00:00
|
|
|
B: MessageBody,
|
2019-11-20 17:33:22 +00:00
|
|
|
T: ServiceFactory<
|
2021-01-03 23:47:04 +00:00
|
|
|
ServiceRequest,
|
2019-05-12 15:34:51 +00:00
|
|
|
Config = (),
|
2019-04-13 21:50:54 +00:00
|
|
|
Response = ServiceResponse<B>,
|
2019-03-10 23:35:38 +00:00
|
|
|
Error = Error,
|
2019-03-02 19:53:05 +00:00
|
|
|
InitError = (),
|
|
|
|
>,
|
2021-01-06 11:35:30 +00:00
|
|
|
T::Future: 'static,
|
2019-03-02 06:51:32 +00:00
|
|
|
{
|
2019-11-20 17:33:22 +00:00
|
|
|
fn into_factory(self) -> AppInit<T, B> {
|
2019-03-02 19:53:05 +00:00
|
|
|
AppInit {
|
2021-01-06 11:35:30 +00:00
|
|
|
async_data_factories: self.data_factories.into_boxed_slice().into(),
|
2019-03-09 17:49:11 +00:00
|
|
|
endpoint: self.endpoint,
|
2019-05-05 02:43:49 +00:00
|
|
|
services: Rc::new(RefCell::new(self.services)),
|
2019-03-09 22:06:24 +00:00
|
|
|
external: RefCell::new(self.external),
|
2019-03-09 17:49:11 +00:00
|
|
|
default: self.default,
|
|
|
|
factory_ref: self.factory_ref,
|
2019-12-20 11:13:09 +00:00
|
|
|
extensions: RefCell::new(Some(self.extensions)),
|
2019-03-02 06:51:32 +00:00
|
|
|
}
|
2019-03-02 19:53:05 +00:00
|
|
|
}
|
|
|
|
}
|
2019-03-04 05:40:03 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2019-03-09 17:49:11 +00:00
|
|
|
use actix_service::Service;
|
2021-04-01 14:26:13 +00:00
|
|
|
use actix_utils::future::{err, ok};
|
2019-04-24 04:21:49 +00:00
|
|
|
use bytes::Bytes;
|
2019-03-09 17:49:11 +00:00
|
|
|
|
2019-03-04 05:40:03 +00:00
|
|
|
use super::*;
|
2021-12-05 14:37:20 +00:00
|
|
|
use crate::http::{
|
|
|
|
header::{self, HeaderValue},
|
|
|
|
Method, StatusCode,
|
|
|
|
};
|
2019-11-20 17:33:22 +00:00
|
|
|
use crate::middleware::DefaultHeaders;
|
2019-11-26 05:25:50 +00:00
|
|
|
use crate::service::ServiceRequest;
|
2021-02-11 23:03:17 +00:00
|
|
|
use crate::test::{call_service, init_service, read_body, try_init_service, TestRequest};
|
2019-11-26 05:25:50 +00:00
|
|
|
use crate::{web, HttpRequest, HttpResponse};
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_default_resource() {
|
2021-02-11 23:03:17 +00:00
|
|
|
let srv =
|
|
|
|
init_service(App::new().service(web::resource("/test").to(HttpResponse::Ok))).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/blah").to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
|
|
|
|
2021-02-07 01:00:40 +00:00
|
|
|
let srv = init_service(
|
2019-11-26 05:25:50 +00:00
|
|
|
App::new()
|
2020-07-21 23:28:33 +00:00
|
|
|
.service(web::resource("/test").to(HttpResponse::Ok))
|
2019-11-26 05:25:50 +00:00
|
|
|
.service(
|
|
|
|
web::resource("/test2")
|
|
|
|
.default_service(|r: ServiceRequest| {
|
|
|
|
ok(r.into_response(HttpResponse::Created()))
|
|
|
|
})
|
2020-07-21 23:28:33 +00:00
|
|
|
.route(web::get().to(HttpResponse::Ok)),
|
2019-11-26 05:25:50 +00:00
|
|
|
)
|
|
|
|
.default_service(|r: ServiceRequest| {
|
|
|
|
ok(r.into_response(HttpResponse::MethodNotAllowed()))
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
.await;
|
2019-11-20 17:33:22 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::with_uri("/blah").to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
2019-11-20 17:33:22 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::with_uri("/test2").to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
2019-11-20 17:33:22 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::with_uri("/test2")
|
|
|
|
.method(Method::POST)
|
|
|
|
.to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::CREATED);
|
2019-03-04 05:40:03 +00:00
|
|
|
}
|
|
|
|
|
2021-06-22 14:50:58 +00:00
|
|
|
// allow deprecated App::data
|
|
|
|
#[allow(deprecated)]
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_data_factory() {
|
2021-02-11 23:03:17 +00:00
|
|
|
let srv = init_service(
|
|
|
|
App::new()
|
|
|
|
.data_factory(|| ok::<_, ()>(10usize))
|
|
|
|
.service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())),
|
|
|
|
)
|
|
|
|
.await;
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
|
2021-02-11 23:03:17 +00:00
|
|
|
let srv = init_service(
|
|
|
|
App::new()
|
|
|
|
.data_factory(|| ok::<_, ()>(10u32))
|
|
|
|
.service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())),
|
|
|
|
)
|
|
|
|
.await;
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
2019-06-28 04:43:52 +00:00
|
|
|
}
|
2019-03-25 20:43:02 +00:00
|
|
|
|
2021-06-22 14:50:58 +00:00
|
|
|
// allow deprecated App::data
|
|
|
|
#[allow(deprecated)]
|
2020-04-29 06:38:53 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_data_factory_errors() {
|
2021-02-11 23:03:17 +00:00
|
|
|
let srv = try_init_service(
|
|
|
|
App::new()
|
|
|
|
.data_factory(|| err::<u32, _>(()))
|
|
|
|
.service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())),
|
|
|
|
)
|
|
|
|
.await;
|
2020-05-21 08:56:53 +00:00
|
|
|
|
2020-04-29 06:38:53 +00:00
|
|
|
assert!(srv.is_err());
|
|
|
|
}
|
|
|
|
|
2019-12-20 11:13:09 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_extension() {
|
2021-02-11 23:03:17 +00:00
|
|
|
let srv = init_service(App::new().app_data(10usize).service(web::resource("/").to(
|
|
|
|
|req: HttpRequest| {
|
2019-12-20 11:13:09 +00:00
|
|
|
assert_eq!(*req.app_data::<usize>().unwrap(), 10);
|
|
|
|
HttpResponse::Ok()
|
2021-02-11 23:03:17 +00:00
|
|
|
},
|
|
|
|
)))
|
2019-12-20 11:13:09 +00:00
|
|
|
.await;
|
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_wrap() {
|
2021-02-07 01:00:40 +00:00
|
|
|
let srv = init_service(
|
2019-11-26 05:25:50 +00:00
|
|
|
App::new()
|
|
|
|
.wrap(
|
|
|
|
DefaultHeaders::new()
|
|
|
|
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
|
|
|
|
)
|
2020-07-21 23:28:33 +00:00
|
|
|
.route("/test", web::get().to(HttpResponse::Ok)),
|
2019-11-26 05:25:50 +00:00
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
2021-02-07 01:00:40 +00:00
|
|
|
let resp = call_service(&srv, req).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
2019-03-25 20:43:02 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_router_wrap() {
|
2021-02-07 01:00:40 +00:00
|
|
|
let srv = init_service(
|
2019-11-26 05:25:50 +00:00
|
|
|
App::new()
|
2020-07-21 23:28:33 +00:00
|
|
|
.route("/test", web::get().to(HttpResponse::Ok))
|
2019-11-26 05:25:50 +00:00
|
|
|
.wrap(
|
|
|
|
DefaultHeaders::new()
|
|
|
|
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
2021-02-07 01:00:40 +00:00
|
|
|
let resp = call_service(&srv, req).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
2019-03-25 20:43:02 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_wrap_fn() {
|
2021-02-07 01:00:40 +00:00
|
|
|
let srv = init_service(
|
2019-11-26 05:25:50 +00:00
|
|
|
App::new()
|
|
|
|
.wrap_fn(|req, srv| {
|
|
|
|
let fut = srv.call(req);
|
|
|
|
async move {
|
|
|
|
let mut res = fut.await?;
|
2021-02-11 23:03:17 +00:00
|
|
|
res.headers_mut()
|
|
|
|
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
|
2019-11-26 05:25:50 +00:00
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
})
|
2020-07-21 23:28:33 +00:00
|
|
|
.service(web::resource("/test").to(HttpResponse::Ok)),
|
2019-11-26 05:25:50 +00:00
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
2021-02-07 01:00:40 +00:00
|
|
|
let resp = call_service(&srv, req).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
2019-03-25 20:43:02 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_router_wrap_fn() {
|
2021-02-07 01:00:40 +00:00
|
|
|
let srv = init_service(
|
2019-11-26 05:25:50 +00:00
|
|
|
App::new()
|
2020-07-21 23:28:33 +00:00
|
|
|
.route("/test", web::get().to(HttpResponse::Ok))
|
2019-11-26 05:25:50 +00:00
|
|
|
.wrap_fn(|req, srv| {
|
|
|
|
let fut = srv.call(req);
|
|
|
|
async {
|
|
|
|
let mut res = fut.await?;
|
2021-02-11 23:03:17 +00:00
|
|
|
res.headers_mut()
|
|
|
|
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
|
2019-11-26 05:25:50 +00:00
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
2021-02-07 01:00:40 +00:00
|
|
|
let resp = call_service(&srv, req).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
2019-03-25 20:43:02 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_external_resource() {
|
2021-02-07 01:00:40 +00:00
|
|
|
let srv = init_service(
|
2019-11-26 05:25:50 +00:00
|
|
|
App::new()
|
|
|
|
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
|
|
|
|
.route(
|
|
|
|
"/test",
|
|
|
|
web::get().to(|req: HttpRequest| {
|
2021-02-11 23:03:17 +00:00
|
|
|
HttpResponse::Ok()
|
|
|
|
.body(req.url_for("youtube", &["12345"]).unwrap().to_string())
|
2019-11-20 17:33:22 +00:00
|
|
|
}),
|
2019-11-26 05:25:50 +00:00
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
2021-02-07 01:00:40 +00:00
|
|
|
let resp = call_service(&srv, req).await;
|
2019-11-26 05:25:50 +00:00
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
let body = read_body(resp).await;
|
|
|
|
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
|
2019-04-24 04:21:49 +00:00
|
|
|
}
|
2019-03-04 05:40:03 +00:00
|
|
|
}
|