2019-03-02 07:51:32 +01:00
|
|
|
use std::cell::RefCell;
|
2019-04-14 07:25:00 +02:00
|
|
|
use std::fmt;
|
2019-11-20 18:33:22 +01:00
|
|
|
use std::future::Future;
|
2019-03-02 07:51:32 +01:00
|
|
|
use std::marker::PhantomData;
|
2019-11-20 18:33:22 +01:00
|
|
|
use std::pin::Pin;
|
2019-03-02 07:51:32 +01:00
|
|
|
use std::rc::Rc;
|
2019-11-20 18:33:22 +01:00
|
|
|
use std::task::{Context, Poll};
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-03-03 01:24:14 +01:00
|
|
|
use actix_http::body::{Body, MessageBody};
|
2019-03-09 18:49:11 +01:00
|
|
|
use actix_service::boxed::{self, BoxedNewService};
|
2019-03-02 07:51:32 +01:00
|
|
|
use actix_service::{
|
2019-11-20 18:33:22 +01:00
|
|
|
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
|
2019-03-02 07:51:32 +01:00
|
|
|
};
|
2019-11-20 18:33:22 +01:00
|
|
|
use futures::future::{FutureExt, LocalBoxFuture};
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
|
2019-04-15 16:32:49 +02:00
|
|
|
use crate::config::{AppConfig, AppConfigInner, ServiceConfig};
|
2019-03-17 04:17:27 +01:00
|
|
|
use crate::data::{Data, DataFactory};
|
2019-04-13 23:50:54 +02:00
|
|
|
use crate::dev::ResourceDef;
|
|
|
|
use crate::error::Error;
|
2019-03-02 07:51:32 +01:00
|
|
|
use crate::resource::Resource;
|
2019-03-07 00:47:15 +01:00
|
|
|
use crate::route::Route;
|
|
|
|
use crate::service::{
|
2019-11-20 18:33:22 +01:00
|
|
|
AppServiceFactory, HttpServiceFactory, ServiceFactoryWrapper, ServiceRequest,
|
2019-03-07 00:47:15 +01:00
|
|
|
ServiceResponse,
|
|
|
|
};
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
|
2019-07-17 11:48:37 +02:00
|
|
|
type FnDataFactory =
|
2019-11-20 18:33:22 +01:00
|
|
|
Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>;
|
2019-03-02 07:51:32 +01:00
|
|
|
|
2019-03-03 07:03:45 +01:00
|
|
|
/// Application builder - structure that follows the builder pattern
|
|
|
|
/// for building application instances.
|
2019-04-13 23:50:54 +02:00
|
|
|
pub struct App<T, B> {
|
|
|
|
endpoint: T,
|
2019-11-20 18:33:22 +01:00
|
|
|
services: Vec<Box<dyn AppServiceFactory>>,
|
2019-04-13 23:50:54 +02:00
|
|
|
default: Option<Rc<HttpNewService>>,
|
|
|
|
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
2019-07-17 11:48:37 +02:00
|
|
|
data: Vec<Box<dyn DataFactory>>,
|
2019-06-28 06:43:52 +02:00
|
|
|
data_factories: Vec<FnDataFactory>,
|
2019-03-09 23:06:24 +01:00
|
|
|
config: AppConfigInner,
|
2019-04-13 23:50:54 +02:00
|
|
|
external: Vec<ResourceDef>,
|
|
|
|
_t: PhantomData<(B)>,
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
impl App<AppEntry, Body> {
|
2019-03-17 04:17:27 +01:00
|
|
|
/// Create application builder. Application can be configured with a builder-like pattern.
|
2019-03-02 07:51:32 +01:00
|
|
|
pub fn new() -> Self {
|
2019-04-13 23:50:54 +02:00
|
|
|
let fref = Rc::new(RefCell::new(None));
|
2019-03-02 20:53:05 +01:00
|
|
|
App {
|
2019-04-13 23:50:54 +02:00
|
|
|
endpoint: AppEntry::new(fref.clone()),
|
2019-03-17 04:17:27 +01:00
|
|
|
data: Vec::new(),
|
2019-06-28 06:43:52 +02:00
|
|
|
data_factories: Vec::new(),
|
2019-04-13 23:50:54 +02:00
|
|
|
services: Vec::new(),
|
|
|
|
default: None,
|
|
|
|
factory_ref: fref,
|
2019-03-09 23:06:24 +01:00
|
|
|
config: AppConfigInner::default(),
|
2019-04-13 23:50:54 +02:00
|
|
|
external: Vec::new(),
|
2019-03-02 20:53:05 +01:00
|
|
|
_t: PhantomData,
|
|
|
|
}
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
impl<T, B> App<T, B>
|
2019-03-02 20:53:05 +01:00
|
|
|
where
|
2019-04-13 23:50:54 +02:00
|
|
|
B: MessageBody,
|
2019-11-20 18:33:22 +01:00
|
|
|
T: ServiceFactory<
|
2019-05-12 17:34:51 +02:00
|
|
|
Config = (),
|
2019-04-13 23:50:54 +02:00
|
|
|
Request = ServiceRequest,
|
|
|
|
Response = ServiceResponse<B>,
|
2019-03-11 00:35:38 +01:00
|
|
|
Error = Error,
|
2019-03-02 20:53:05 +01:00
|
|
|
InitError = (),
|
|
|
|
>,
|
|
|
|
{
|
2019-04-10 21:43:31 +02:00
|
|
|
/// Set application data. Application data could be accessed
|
2019-03-17 04:17:27 +01:00
|
|
|
/// by using `Data<T>` extractor where `T` is data type.
|
2019-03-02 07:51:32 +01:00
|
|
|
///
|
|
|
|
/// **Note**: http server accepts an application factory rather than
|
|
|
|
/// an application instance. Http server constructs an application
|
2019-03-17 04:17:27 +01:00
|
|
|
/// instance for each thread, thus application data must be constructed
|
|
|
|
/// multiple times. If you want to share data between different
|
2019-03-02 07:51:32 +01:00
|
|
|
/// threads, a shared object should be used, e.g. `Arc`. Application
|
2019-03-17 04:17:27 +01:00
|
|
|
/// data does not need to be `Send` or `Sync`.
|
2019-03-03 07:11:24 +01:00
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use std::cell::Cell;
|
2019-03-07 20:43:46 +01:00
|
|
|
/// use actix_web::{web, App};
|
2019-03-03 07:11:24 +01:00
|
|
|
///
|
2019-03-17 04:17:27 +01:00
|
|
|
/// struct MyData {
|
2019-03-03 07:11:24 +01:00
|
|
|
/// counter: Cell<usize>,
|
|
|
|
/// }
|
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index(data: web::Data<MyData>) {
|
2019-03-17 04:17:27 +01:00
|
|
|
/// data.counter.set(data.counter.get() + 1);
|
2019-03-03 07:11:24 +01:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
2019-03-17 04:17:27 +01:00
|
|
|
/// .data(MyData{ counter: Cell::new(0) })
|
2019-03-07 00:47:15 +01:00
|
|
|
/// .service(
|
|
|
|
/// web::resource("/index.html").route(
|
|
|
|
/// web::get().to(index)));
|
2019-03-03 07:11:24 +01:00
|
|
|
/// }
|
|
|
|
/// ```
|
2019-05-12 18:42:05 +02:00
|
|
|
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
|
|
|
self.data.push(Box::new(Data::new(data)));
|
2019-03-02 07:51:32 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-06-28 06:43:52 +02:00
|
|
|
/// Set application data factory. This function is
|
|
|
|
/// similar to `.data()` but it accepts data factory. Data object get
|
|
|
|
/// constructed asynchronously during application initialization.
|
2019-11-20 18:33:22 +01:00
|
|
|
pub fn data_factory<F, Out, D, E>(mut self, data: F) -> Self
|
2019-06-28 06:43:52 +02:00
|
|
|
where
|
|
|
|
F: Fn() -> Out + 'static,
|
2019-11-20 18:33:22 +01:00
|
|
|
Out: Future<Output = Result<D, E>> + 'static,
|
|
|
|
D: 'static,
|
|
|
|
E: std::fmt::Debug,
|
2019-06-28 06:43:52 +02:00
|
|
|
{
|
|
|
|
self.data_factories.push(Box::new(move || {
|
2019-11-20 18:33:22 +01: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 06:43:52 +02:00
|
|
|
}));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-06-05 04:43:39 +02:00
|
|
|
/// Set application data. Application data could be accessed
|
|
|
|
/// by using `Data<T>` extractor where `T` is data type.
|
|
|
|
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
|
|
|
self.data.push(Box::new(data));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-04 00:09:31 +02: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.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// use actix_web::{web, middleware, App, HttpResponse};
|
|
|
|
///
|
|
|
|
/// // this function could be located in different module
|
2019-04-15 16:32:49 +02:00
|
|
|
/// fn config(cfg: &mut web::ServiceConfig) {
|
2019-04-04 00:09:31 +02:00
|
|
|
/// cfg.service(web::resource("/test")
|
|
|
|
/// .route(web::get().to(|| HttpResponse::Ok()))
|
|
|
|
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
|
|
|
|
/// );
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
|
|
|
/// .wrap(middleware::Logger::default())
|
|
|
|
/// .configure(config) // <- register resources
|
|
|
|
/// .route("/index.html", web::get().to(|| HttpResponse::Ok()));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn configure<F>(mut self, f: F) -> Self
|
2019-04-04 00:09:31 +02:00
|
|
|
where
|
2019-05-10 23:44:49 +02:00
|
|
|
F: FnOnce(&mut ServiceConfig),
|
2019-04-04 00:09:31 +02:00
|
|
|
{
|
2019-04-15 16:32:49 +02:00
|
|
|
let mut cfg = ServiceConfig::new();
|
2019-04-04 00:09:31 +02:00
|
|
|
f(&mut cfg);
|
|
|
|
self.data.extend(cfg.data);
|
2019-04-13 23:50:54 +02:00
|
|
|
self.services.extend(cfg.services);
|
|
|
|
self.external.extend(cfg.external);
|
|
|
|
self
|
2019-04-04 00:09:31 +02:00
|
|
|
}
|
|
|
|
|
2019-03-07 00:47:15 +01:00
|
|
|
/// Configure route for a specific path.
|
|
|
|
///
|
|
|
|
/// This is a simplified version of the `App::service()` method.
|
2019-03-17 04:17:27 +01:00
|
|
|
/// This method can be used multiple times with same path, in that case
|
2019-03-07 00:47:15 +01:00
|
|
|
/// multiple resources with one route would be registered for same resource path.
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-03-07 23:01:52 +01:00
|
|
|
/// use actix_web::{web, App, HttpResponse};
|
2019-03-07 00:47:15 +01:00
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index(data: web::Path<(String, String)>) -> &'static str {
|
2019-03-07 00:47:15 +01:00
|
|
|
/// "Welcome!"
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
|
|
|
/// .route("/test1", web::get().to(index))
|
|
|
|
/// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn route(self, path: &str, mut route: Route) -> Self {
|
2019-03-07 00:47:15 +01:00
|
|
|
self.service(
|
|
|
|
Resource::new(path)
|
|
|
|
.add_guards(route.take_guards())
|
|
|
|
.route(route),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Register http service.
|
2019-03-17 05:35:02 +01:00
|
|
|
///
|
|
|
|
/// Http service is any type that implements `HttpServiceFactory` trait.
|
|
|
|
///
|
|
|
|
/// Actix web provides several services implementations:
|
|
|
|
///
|
|
|
|
/// * *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 23:50:54 +02:00
|
|
|
pub fn service<F>(mut self, factory: F) -> Self
|
2019-03-06 07:10:08 +01:00
|
|
|
where
|
2019-04-13 23:50:54 +02:00
|
|
|
F: HttpServiceFactory + 'static,
|
2019-03-06 07:10:08 +01:00
|
|
|
{
|
2019-04-13 23:50:54 +02:00
|
|
|
self.services
|
|
|
|
.push(Box::new(ServiceFactoryWrapper::new(factory)));
|
|
|
|
self
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
|
2019-03-04 06:02:01 +01:00
|
|
|
/// Set server host name.
|
|
|
|
///
|
2019-03-17 04:17:27 +01:00
|
|
|
/// Host name is used by application router as a hostname for url
|
2019-03-04 06:02:01 +01:00
|
|
|
/// generation. Check [ConnectionInfo](./dev/struct.ConnectionInfo.
|
|
|
|
/// html#method.host) documentation for more information.
|
|
|
|
///
|
|
|
|
/// By default host name is set to a "localhost" value.
|
2019-03-09 19:53:00 +01:00
|
|
|
pub fn hostname(mut self, val: &str) -> Self {
|
2019-03-09 23:06:24 +01:00
|
|
|
self.config.host = val.to_owned();
|
2019-03-04 06:02:01 +01:00
|
|
|
self
|
|
|
|
}
|
2019-03-28 20:32:59 +01:00
|
|
|
|
2019-04-14 07:25:00 +02:00
|
|
|
/// Default service to be used if no matching resource could be found.
|
|
|
|
///
|
|
|
|
/// It is possible to use services like `Resource`, `Route`.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{web, App, HttpResponse};
|
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index() -> &'static str {
|
2019-04-14 07:25:00 +02: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.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// 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 17:47:06 +02:00
|
|
|
/// web::to(|| HttpResponse::NotFound())
|
2019-04-14 07:25:00 +02:00
|
|
|
/// );
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn default_service<F, U>(mut self, f: F) -> Self
|
2019-03-28 20:32:59 +01:00
|
|
|
where
|
2019-11-20 18:33:22 +01:00
|
|
|
F: IntoServiceFactory<U>,
|
|
|
|
U: ServiceFactory<
|
2019-05-12 17:34:51 +02:00
|
|
|
Config = (),
|
2019-04-13 23:50:54 +02:00
|
|
|
Request = ServiceRequest,
|
|
|
|
Response = ServiceResponse,
|
|
|
|
Error = Error,
|
|
|
|
> + 'static,
|
2019-04-14 07:25:00 +02:00
|
|
|
U::InitError: fmt::Debug,
|
2019-03-28 20:32:59 +01:00
|
|
|
{
|
2019-04-13 23:50:54 +02:00
|
|
|
// create and configure default resource
|
2019-11-20 18:33:22 +01:00
|
|
|
self.default = Some(Rc::new(boxed::factory(f.into_factory().map_init_err(
|
|
|
|
|e| log::error!("Can not construct default service: {:?}", e),
|
|
|
|
))));
|
2019-03-28 20:32:59 +01:00
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
self
|
2019-03-28 20:32:59 +01:00
|
|
|
}
|
2019-03-02 20:53:05 +01:00
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
/// Register an external resource.
|
2019-04-04 00:09:31 +02:00
|
|
|
///
|
2019-04-13 23:50:54 +02: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-04 00:09:31 +02:00
|
|
|
///
|
|
|
|
/// ```rust
|
2019-04-13 23:50:54 +02:00
|
|
|
/// use actix_web::{web, App, HttpRequest, HttpResponse, Result};
|
2019-04-04 00:09:31 +02:00
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index(req: HttpRequest) -> Result<HttpResponse> {
|
2019-04-13 23:50:54 +02:00
|
|
|
/// let url = req.url_for("youtube", &["asdlkjqme"])?;
|
|
|
|
/// assert_eq!(url.as_str(), "https://youtube.com/watch/asdlkjqme");
|
|
|
|
/// Ok(HttpResponse::Ok().into())
|
2019-04-04 00:09:31 +02:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
2019-04-13 23:50:54 +02:00
|
|
|
/// .service(web::resource("/index.html").route(
|
|
|
|
/// web::get().to(index)))
|
|
|
|
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}");
|
2019-04-04 00:09:31 +02:00
|
|
|
/// }
|
|
|
|
/// ```
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn external_resource<N, U>(mut self, name: N, url: U) -> Self
|
2019-04-04 00:09:31 +02:00
|
|
|
where
|
2019-04-13 23:50:54 +02:00
|
|
|
N: AsRef<str>,
|
|
|
|
U: AsRef<str>,
|
2019-04-04 00:09:31 +02:00
|
|
|
{
|
2019-04-13 23:50:54 +02:00
|
|
|
let mut rdef = ResourceDef::new(url.as_ref());
|
|
|
|
*rdef.name_mut() = name.as_ref().to_string();
|
|
|
|
self.external.push(rdef);
|
2019-04-04 00:09:31 +02:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
/// Registers middleware, in the form of a middleware component (type),
|
|
|
|
/// that runs during inbound and/or outbound processing in the request
|
|
|
|
/// lifecycle (request -> response), modifying request/response as
|
|
|
|
/// necessary, across all requests managed by the *Application*.
|
2019-03-04 06:02:01 +01:00
|
|
|
///
|
2019-04-29 18:26:12 +02:00
|
|
|
/// Use middleware when you need to read or modify *every* request or
|
2019-04-29 18:14:36 +02:00
|
|
|
/// response in some way.
|
|
|
|
///
|
2019-04-29 18:26:12 +02:00
|
|
|
/// Notice that the keyword for registering middleware is `wrap`. As you
|
2019-04-29 18:14:36 +02: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 18:26:12 +02:00
|
|
|
/// the builder chain. Consequently, the *first* middleware registered
|
2019-04-29 18:14:36 +02:00
|
|
|
/// in the builder chain is the *last* to execute during request processing.
|
2019-03-04 06:02:01 +01:00
|
|
|
///
|
|
|
|
/// ```rust
|
2019-04-13 23:50:54 +02:00
|
|
|
/// use actix_service::Service;
|
|
|
|
/// use actix_web::{middleware, web, App};
|
|
|
|
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};
|
2019-03-04 06:02:01 +01:00
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index() -> &'static str {
|
2019-03-07 00:47:15 +01:00
|
|
|
/// "Welcome!"
|
2019-03-04 06:02:01 +01:00
|
|
|
/// }
|
2019-03-02 07:51:32 +01:00
|
|
|
///
|
|
|
|
/// fn main() {
|
2019-03-03 07:03:45 +01:00
|
|
|
/// let app = App::new()
|
2019-04-13 23:50:54 +02:00
|
|
|
/// .wrap(middleware::Logger::default())
|
|
|
|
/// .route("/index.html", web::get().to(index));
|
2019-03-02 07:51:32 +01:00
|
|
|
/// }
|
|
|
|
/// ```
|
2019-11-20 18:33:22 +01:00
|
|
|
pub fn wrap<M, B1>(
|
2019-03-02 07:51:32 +01:00
|
|
|
self,
|
2019-11-20 18:33:22 +01:00
|
|
|
mw: M,
|
2019-04-13 23:50:54 +02:00
|
|
|
) -> App<
|
2019-11-20 18:33:22 +01:00
|
|
|
impl ServiceFactory<
|
2019-05-12 17:34:51 +02:00
|
|
|
Config = (),
|
2019-04-13 23:50:54 +02:00
|
|
|
Request = ServiceRequest,
|
2019-03-02 07:51:32 +01:00
|
|
|
Response = ServiceResponse<B1>,
|
2019-03-11 00:35:38 +01:00
|
|
|
Error = Error,
|
2019-03-02 07:51:32 +01:00
|
|
|
InitError = (),
|
|
|
|
>,
|
2019-04-13 23:50:54 +02:00
|
|
|
B1,
|
2019-03-02 07:51:32 +01:00
|
|
|
>
|
|
|
|
where
|
2019-03-05 06:37:57 +01:00
|
|
|
M: Transform<
|
2019-03-02 07:51:32 +01:00
|
|
|
T::Service,
|
2019-04-13 23:50:54 +02:00
|
|
|
Request = ServiceRequest,
|
2019-03-02 07:51:32 +01:00
|
|
|
Response = ServiceResponse<B1>,
|
2019-03-11 00:35:38 +01:00
|
|
|
Error = Error,
|
2019-03-02 07:51:32 +01:00
|
|
|
InitError = (),
|
|
|
|
>,
|
|
|
|
B1: MessageBody,
|
|
|
|
{
|
2019-04-13 23:50:54 +02:00
|
|
|
App {
|
2019-11-20 18:33:22 +01:00
|
|
|
endpoint: apply(mw, self.endpoint),
|
2019-03-17 04:17:27 +01:00
|
|
|
data: self.data,
|
2019-06-28 06:43:52 +02:00
|
|
|
data_factories: self.data_factories,
|
2019-03-02 07:51:32 +01:00
|
|
|
services: self.services,
|
|
|
|
default: self.default,
|
|
|
|
factory_ref: self.factory_ref,
|
2019-03-09 23:06:24 +01:00
|
|
|
config: self.config,
|
|
|
|
external: self.external,
|
2019-03-02 07:51:32 +01:00
|
|
|
_t: PhantomData,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-01 20:52:05 +02:00
|
|
|
/// Registers middleware, in the form of a closure, that runs during inbound
|
|
|
|
/// and/or outbound processing in the request lifecycle (request -> response),
|
|
|
|
/// modifying request/response as necessary, across all requests managed by
|
2019-04-13 23:50:54 +02:00
|
|
|
/// the *Application*.
|
2019-04-01 20:52:05 +02:00
|
|
|
///
|
|
|
|
/// Use middleware when you need to read or modify *every* request or response in some way.
|
|
|
|
///
|
2019-04-13 23:50:54 +02:00
|
|
|
/// ```rust
|
|
|
|
/// use actix_service::Service;
|
|
|
|
/// use actix_web::{web, App};
|
|
|
|
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};
|
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index() -> &'static str {
|
2019-04-13 23:50:54 +02:00
|
|
|
/// "Welcome!"
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let app = App::new()
|
2019-11-20 18:33:22 +01:00
|
|
|
/// .wrap_fn(|req, srv| {
|
|
|
|
/// let fut = srv.call(req);
|
|
|
|
/// async {
|
|
|
|
/// let mut res = fut.await?;
|
2019-04-13 23:50:54 +02:00
|
|
|
/// res.headers_mut().insert(
|
|
|
|
/// CONTENT_TYPE, HeaderValue::from_static("text/plain"),
|
|
|
|
/// );
|
2019-11-20 18:33:22 +01:00
|
|
|
/// Ok(res)
|
|
|
|
/// }
|
|
|
|
/// })
|
2019-04-13 23:50:54 +02:00
|
|
|
/// .route("/index.html", web::get().to(index));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-03-25 21:43:02 +01:00
|
|
|
pub fn wrap_fn<B1, F, R>(
|
|
|
|
self,
|
|
|
|
mw: F,
|
2019-04-13 23:50:54 +02:00
|
|
|
) -> App<
|
2019-11-20 18:33:22 +01:00
|
|
|
impl ServiceFactory<
|
2019-05-12 17:34:51 +02:00
|
|
|
Config = (),
|
2019-04-13 23:50:54 +02:00
|
|
|
Request = ServiceRequest,
|
2019-03-25 21:43:02 +01:00
|
|
|
Response = ServiceResponse<B1>,
|
|
|
|
Error = Error,
|
|
|
|
InitError = (),
|
|
|
|
>,
|
2019-04-13 23:50:54 +02:00
|
|
|
B1,
|
2019-03-25 21:43:02 +01:00
|
|
|
>
|
|
|
|
where
|
|
|
|
B1: MessageBody,
|
2019-04-13 23:50:54 +02:00
|
|
|
F: FnMut(ServiceRequest, &mut T::Service) -> R + Clone,
|
2019-11-20 18:33:22 +01:00
|
|
|
R: Future<Output = Result<ServiceResponse<B1>, Error>>,
|
2019-03-25 21:43:02 +01:00
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
App {
|
|
|
|
endpoint: apply_fn_factory(self.endpoint, mw),
|
|
|
|
data: self.data,
|
|
|
|
data_factories: self.data_factories,
|
|
|
|
services: self.services,
|
|
|
|
default: self.default,
|
|
|
|
factory_ref: self.factory_ref,
|
|
|
|
config: self.config,
|
|
|
|
external: self.external,
|
|
|
|
_t: PhantomData,
|
|
|
|
}
|
2019-03-25 21:43:02 +01:00
|
|
|
}
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
|
|
|
|
2019-11-20 18:33:22 +01:00
|
|
|
impl<T, B> IntoServiceFactory<AppInit<T, B>> for App<T, B>
|
2019-03-02 07:51:32 +01:00
|
|
|
where
|
2019-04-13 23:50:54 +02:00
|
|
|
B: MessageBody,
|
2019-11-20 18:33:22 +01:00
|
|
|
T: ServiceFactory<
|
2019-05-12 17:34:51 +02:00
|
|
|
Config = (),
|
2019-03-09 18:49:11 +01:00
|
|
|
Request = ServiceRequest,
|
2019-04-13 23:50:54 +02:00
|
|
|
Response = ServiceResponse<B>,
|
2019-03-11 00:35:38 +01:00
|
|
|
Error = Error,
|
2019-03-02 20:53:05 +01:00
|
|
|
InitError = (),
|
|
|
|
>,
|
2019-03-02 07:51:32 +01:00
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
fn into_factory(self) -> AppInit<T, B> {
|
2019-03-02 20:53:05 +01:00
|
|
|
AppInit {
|
2019-05-05 04:43:49 +02:00
|
|
|
data: Rc::new(self.data),
|
2019-06-28 06:43:52 +02:00
|
|
|
data_factories: Rc::new(self.data_factories),
|
2019-03-09 18:49:11 +01:00
|
|
|
endpoint: self.endpoint,
|
2019-05-05 04:43:49 +02:00
|
|
|
services: Rc::new(RefCell::new(self.services)),
|
2019-03-09 23:06:24 +01:00
|
|
|
external: RefCell::new(self.external),
|
2019-03-09 18:49:11 +01:00
|
|
|
default: self.default,
|
|
|
|
factory_ref: self.factory_ref,
|
2019-03-09 23:06:24 +01:00
|
|
|
config: RefCell::new(AppConfig(Rc::new(self.config))),
|
2019-03-02 07:51:32 +01:00
|
|
|
}
|
2019-03-02 20:53:05 +01:00
|
|
|
}
|
|
|
|
}
|
2019-03-04 06:40:03 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2019-03-09 18:49:11 +01:00
|
|
|
use actix_service::Service;
|
2019-04-24 06:21:49 +02:00
|
|
|
use bytes::Bytes;
|
2019-11-20 18:33:22 +01:00
|
|
|
use futures::future::{ok, Future};
|
2019-03-09 18:49:11 +01:00
|
|
|
|
2019-03-04 06:40:03 +01:00
|
|
|
use super::*;
|
2019-03-25 21:43:02 +01:00
|
|
|
use crate::http::{header, HeaderValue, Method, StatusCode};
|
2019-11-20 18:33:22 +01:00
|
|
|
use crate::middleware::DefaultHeaders;
|
2019-03-25 21:43:02 +01:00
|
|
|
use crate::service::{ServiceRequest, ServiceResponse};
|
2019-11-20 18:33:22 +01:00
|
|
|
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
|
2019-04-24 06:21:49 +02:00
|
|
|
use crate::{web, Error, HttpRequest, HttpResponse};
|
2019-03-04 06:40:03 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_default_resource() {
|
2019-11-20 18:33:22 +01:00
|
|
|
block_on(async {
|
|
|
|
let mut srv = init_service(
|
|
|
|
App::new().service(web::resource("/test").to(|| HttpResponse::Ok())),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
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);
|
|
|
|
|
|
|
|
let mut srv = init_service(
|
|
|
|
App::new()
|
|
|
|
.service(web::resource("/test").to(|| HttpResponse::Ok()))
|
|
|
|
.service(
|
|
|
|
web::resource("/test2")
|
|
|
|
.default_service(|r: ServiceRequest| {
|
|
|
|
ok(r.into_response(HttpResponse::Created()))
|
|
|
|
})
|
|
|
|
.route(web::get().to(|| HttpResponse::Ok())),
|
|
|
|
)
|
|
|
|
.default_service(|r: ServiceRequest| {
|
|
|
|
ok(r.into_response(HttpResponse::MethodNotAllowed()))
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/blah").to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/test2").to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
|
|
|
|
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 06:40:03 +01:00
|
|
|
}
|
|
|
|
|
2019-06-28 06:43:52 +02:00
|
|
|
#[test]
|
|
|
|
fn test_data_factory() {
|
2019-11-20 18:33:22 +01:00
|
|
|
block_on(async {
|
|
|
|
let mut srv =
|
|
|
|
init_service(App::new().data_factory(|| ok::<_, ()>(10usize)).service(
|
|
|
|
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
|
|
|
))
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let mut srv =
|
|
|
|
init_service(App::new().data_factory(|| ok::<_, ()>(10u32)).service(
|
|
|
|
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
|
|
|
))
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::default().to_request();
|
|
|
|
let resp = srv.call(req).await.unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
|
|
|
})
|
2019-06-28 06:43:52 +02:00
|
|
|
}
|
2019-03-25 21:43:02 +01:00
|
|
|
|
2019-04-13 23:50:54 +02:00
|
|
|
fn md<S, B>(
|
|
|
|
req: ServiceRequest,
|
2019-03-25 21:43:02 +01:00
|
|
|
srv: &mut S,
|
2019-11-20 18:33:22 +01:00
|
|
|
) -> impl Future<Output = Result<ServiceResponse<B>, Error>>
|
2019-03-25 21:43:02 +01:00
|
|
|
where
|
|
|
|
S: Service<
|
2019-04-13 23:50:54 +02:00
|
|
|
Request = ServiceRequest,
|
2019-03-25 21:43:02 +01:00
|
|
|
Response = ServiceResponse<B>,
|
|
|
|
Error = Error,
|
|
|
|
>,
|
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
let fut = srv.call(req);
|
|
|
|
async move {
|
|
|
|
let mut res = fut.await?;
|
2019-03-25 21:43:02 +01:00
|
|
|
res.headers_mut()
|
|
|
|
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
|
2019-11-20 18:33:22 +01:00
|
|
|
Ok(res)
|
|
|
|
}
|
2019-03-25 21:43:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_wrap() {
|
2019-11-20 18:33:22 +01:00
|
|
|
block_on(async {
|
|
|
|
let mut srv =
|
|
|
|
init_service(
|
|
|
|
App::new()
|
|
|
|
.wrap(DefaultHeaders::new().header(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("0001"),
|
|
|
|
))
|
|
|
|
.route("/test", web::get().to(|| HttpResponse::Ok())),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
|
|
|
let resp = call_service(&mut srv, req).await;
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
|
|
|
})
|
2019-03-25 21:43:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_router_wrap() {
|
2019-11-20 18:33:22 +01:00
|
|
|
block_on(async {
|
|
|
|
let mut srv =
|
|
|
|
init_service(
|
|
|
|
App::new()
|
|
|
|
.route("/test", web::get().to(|| HttpResponse::Ok()))
|
|
|
|
.wrap(DefaultHeaders::new().header(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("0001"),
|
|
|
|
)),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
|
|
|
let resp = call_service(&mut srv, req).await;
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
|
|
|
})
|
2019-03-25 21:43:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_wrap_fn() {
|
2019-11-20 18:33:22 +01:00
|
|
|
block_on(async {
|
|
|
|
let mut srv = init_service(
|
|
|
|
App::new()
|
|
|
|
.wrap_fn(|req, srv| {
|
|
|
|
let fut = srv.call(req);
|
|
|
|
async move {
|
|
|
|
let mut res = fut.await?;
|
|
|
|
res.headers_mut().insert(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("0001"),
|
|
|
|
);
|
|
|
|
Ok(res)
|
|
|
|
}
|
2019-03-25 21:43:02 +01:00
|
|
|
})
|
2019-11-20 18:33:22 +01:00
|
|
|
.service(web::resource("/test").to(|| HttpResponse::Ok())),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
|
|
|
let resp = call_service(&mut srv, req).await;
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
|
|
|
})
|
2019-03-25 21:43:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_router_wrap_fn() {
|
2019-11-20 18:33:22 +01:00
|
|
|
block_on(async {
|
|
|
|
let mut srv = init_service(
|
|
|
|
App::new()
|
|
|
|
.route("/test", web::get().to(|| HttpResponse::Ok()))
|
|
|
|
.wrap_fn(|req, srv| {
|
|
|
|
let fut = srv.call(req);
|
|
|
|
async {
|
|
|
|
let mut res = fut.await?;
|
|
|
|
res.headers_mut().insert(
|
|
|
|
header::CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("0001"),
|
|
|
|
);
|
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
|
|
|
let resp = call_service(&mut srv, req).await;
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(
|
|
|
|
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
HeaderValue::from_static("0001")
|
|
|
|
);
|
|
|
|
})
|
2019-03-25 21:43:02 +01:00
|
|
|
}
|
2019-04-24 06:21:49 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_external_resource() {
|
2019-11-20 18:33:22 +01:00
|
|
|
block_on(async {
|
|
|
|
let mut srv = init_service(
|
|
|
|
App::new()
|
|
|
|
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
|
|
|
|
.route(
|
|
|
|
"/test",
|
|
|
|
web::get().to(|req: HttpRequest| {
|
|
|
|
HttpResponse::Ok().body(format!(
|
|
|
|
"{}",
|
|
|
|
req.url_for("youtube", &["12345"]).unwrap()
|
|
|
|
))
|
|
|
|
}),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
let req = TestRequest::with_uri("/test").to_request();
|
|
|
|
let resp = call_service(&mut srv, req).await;
|
|
|
|
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 06:21:49 +02:00
|
|
|
}
|
2019-03-04 06:40:03 +01:00
|
|
|
}
|