mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-04 01:51:30 +02:00
Compare commits
8 Commits
http-v1.0.
...
web-v2.0.0
Author | SHA1 | Date | |
---|---|---|---|
2b4256baab | |||
e5a50f423d | |||
8b8a9a995d | |||
74fa4060c2 | |||
c877840c07 | |||
20248daeda | |||
a08d8dab70 | |||
fbbb4a86e9 |
15
CHANGES.md
15
CHANGES.md
@ -1,11 +1,24 @@
|
||||
# Changes
|
||||
|
||||
## [2.0.0] - 2019-12-xx
|
||||
## [2.0.0-rc] - 2019-12-20
|
||||
|
||||
### Changed
|
||||
|
||||
* Move `BodyEncoding` to `dev` module #1220
|
||||
|
||||
* Allow to set `peer_addr` for TestRequest #1074
|
||||
|
||||
* Make web::Data deref to Arc<T> #1214
|
||||
|
||||
* Rename `App::register_data()` to `App::app_data()`
|
||||
|
||||
* `HttpRequest::app_data<T>()` returns `Option<&T>` instead of `Option<&Data<T>>`
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix `AppConfig::secure()` is always false. #1202
|
||||
|
||||
|
||||
## [2.0.0-alpha.6] - 2019-12-15
|
||||
|
||||
### Fixed
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "2.0.0-alpha.6"
|
||||
version = "2.0.0-rc"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
|
@ -1,5 +1,10 @@
|
||||
## 2.0.0
|
||||
|
||||
* `App::register_data()` renamed to `App::app_data()` and accepts any type `T: 'static`.
|
||||
Stored data is available via `HttpRequest::app_data()` method at runtime.
|
||||
|
||||
* Extractor configuration must be registered with `App::app_data()` instead of `App::data()`
|
||||
|
||||
* Sync handlers has been removed. `.to_async()` method has been renamed to `.to()`
|
||||
|
||||
replace `fn` with `async fn` to convert sync handler to async
|
||||
|
@ -17,7 +17,7 @@ name = "actix_cors"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "2.0.0-alpha.5"
|
||||
actix-web = "2.0.0-rc"
|
||||
actix-service = "1.0.0"
|
||||
derive_more = "0.99.2"
|
||||
futures = "0.3.1"
|
||||
|
@ -18,8 +18,8 @@ name = "actix_files"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "2.0.0-alpha.6", default-features = false }
|
||||
actix-http = "1.0.0"
|
||||
actix-web = { version = "2.0.0-rc", default-features = false }
|
||||
actix-http = "1.0.1"
|
||||
actix-service = "1.0.0"
|
||||
bitflags = "1"
|
||||
bytes = "0.5.3"
|
||||
@ -33,4 +33,4 @@ v_htmlescape = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "1.0.0"
|
||||
actix-web = { version = "2.0.0-alpha.6", features=["openssl"] }
|
||||
actix-web = { version = "2.0.0-rc", features=["openssl"] }
|
||||
|
@ -17,7 +17,7 @@ name = "actix_identity"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "2.0.0-alpha.5", default-features = false, features = ["secure-cookies"] }
|
||||
actix-web = { version = "2.0.0-rc", default-features = false, features = ["secure-cookies"] }
|
||||
actix-service = "1.0.0"
|
||||
futures = "0.3.1"
|
||||
serde = "1.0"
|
||||
@ -26,5 +26,5 @@ time = "0.1.42"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "1.0.0"
|
||||
actix-http = "1.0.0"
|
||||
actix-http = "1.0.1"
|
||||
bytes = "0.5.3"
|
@ -16,7 +16,7 @@ name = "actix_multipart"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "2.0.0-alpha.5", default-features = false }
|
||||
actix-web = { version = "2.0.0-rc", default-features = false }
|
||||
actix-service = "1.0.0"
|
||||
actix-utils = "1.0.3"
|
||||
bytes = "0.5.3"
|
||||
|
@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
|
||||
## [0.3.0-alpha.4] - 2019-12-xx
|
||||
|
||||
* Allow access to sessions also from not mutable references to the request
|
||||
|
||||
## [0.3.0-alpha.3] - 2019-12-xx
|
||||
|
||||
* Add access to the session from RequestHead for use of session from guard methods
|
||||
|
@ -22,7 +22,7 @@ default = ["cookie-session"]
|
||||
cookie-session = ["actix-web/secure-cookies"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = "2.0.0-alpha.5"
|
||||
actix-web = "2.0.0-rc"
|
||||
actix-service = "1.0.0"
|
||||
bytes = "0.5.3"
|
||||
derive_more = "0.99.2"
|
||||
|
@ -85,23 +85,23 @@ pub struct Session(Rc<RefCell<SessionInner>>);
|
||||
|
||||
/// Helper trait that allows to get session
|
||||
pub trait UserSession {
|
||||
fn get_session(&mut self) -> Session;
|
||||
fn get_session(&self) -> Session;
|
||||
}
|
||||
|
||||
impl UserSession for HttpRequest {
|
||||
fn get_session(&mut self) -> Session {
|
||||
fn get_session(&self) -> Session {
|
||||
Session::get_session(&mut *self.extensions_mut())
|
||||
}
|
||||
}
|
||||
|
||||
impl UserSession for ServiceRequest {
|
||||
fn get_session(&mut self) -> Session {
|
||||
fn get_session(&self) -> Session {
|
||||
Session::get_session(&mut *self.extensions_mut())
|
||||
}
|
||||
}
|
||||
|
||||
impl UserSession for RequestHead {
|
||||
fn get_session(&mut self) -> Session {
|
||||
fn get_session(&self) -> Session {
|
||||
Session::get_session(&mut *self.extensions_mut())
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-actors"
|
||||
version = "2.0.0-alpha.1"
|
||||
version = "2.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix actors support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -16,9 +16,9 @@ name = "actix_web_actors"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.9.0-alpha.1"
|
||||
actix-web = "2.0.0-alpha.5"
|
||||
actix-http = "1.0.0"
|
||||
actix = "0.9.0"
|
||||
actix-web = "2.0.0-rc"
|
||||
actix-http = "1.0.1"
|
||||
actix-codec = "0.2.0"
|
||||
bytes = "0.5.2"
|
||||
futures = "0.3.1"
|
||||
|
@ -18,5 +18,5 @@ proc-macro2 = "^1"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = { version = "1.0.0" }
|
||||
actix-web = { version = "2.0.0-alpha.4" }
|
||||
actix-web = { version = "2.0.0-rc" }
|
||||
futures = { version = "0.3.1" }
|
||||
|
@ -55,8 +55,8 @@ rust-tls = { version = "0.16.0", package="rustls", optional = true, features = [
|
||||
|
||||
[dev-dependencies]
|
||||
actix-connect = { version = "1.0.1", features=["openssl"] }
|
||||
actix-web = { version = "2.0.0-alpha.5", features=["openssl"] }
|
||||
actix-http = { version = "1.0.0", features=["openssl"] }
|
||||
actix-web = { version = "2.0.0-rc", features=["openssl"] }
|
||||
actix-http = { version = "1.0.1", features=["openssl"] }
|
||||
actix-http-test = { version = "1.0.0", features=["openssl"] }
|
||||
actix-utils = "1.0.3"
|
||||
actix-server = "1.0.0"
|
||||
|
@ -14,8 +14,8 @@ use rand::Rng;
|
||||
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::test_server;
|
||||
use actix_service::pipeline_factory;
|
||||
use actix_web::dev::BodyEncoding;
|
||||
use actix_service::{map_config, pipeline_factory, IntoServiceFactory};
|
||||
use actix_web::dev::{AppConfig, BodyEncoding};
|
||||
use actix_web::http::Cookie;
|
||||
use actix_web::middleware::Compress;
|
||||
use actix_web::{
|
||||
@ -170,10 +170,12 @@ async fn test_connection_reuse() {
|
||||
ok(io)
|
||||
})
|
||||
.and_then(
|
||||
HttpService::new(
|
||||
HttpService::new(map_config(
|
||||
App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||
)
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok())))
|
||||
.into_factory(),
|
||||
|_| AppConfig::default(),
|
||||
))
|
||||
.tcp(),
|
||||
)
|
||||
});
|
||||
@ -206,10 +208,12 @@ async fn test_connection_force_close() {
|
||||
ok(io)
|
||||
})
|
||||
.and_then(
|
||||
HttpService::new(
|
||||
HttpService::new(map_config(
|
||||
App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||
)
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok())))
|
||||
.into_factory(),
|
||||
|_| AppConfig::default(),
|
||||
))
|
||||
.tcp(),
|
||||
)
|
||||
});
|
||||
@ -235,19 +239,22 @@ async fn test_connection_server_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let srv = test_server(move || {
|
||||
let srv =
|
||||
test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
.and_then(
|
||||
HttpService::new(
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.route(web::to(|| HttpResponse::Ok().force_close().finish())),
|
||||
),
|
||||
)
|
||||
HttpService::new(map_config(
|
||||
App::new()
|
||||
.service(web::resource("/").route(web::to(|| {
|
||||
HttpResponse::Ok().force_close().finish()
|
||||
})))
|
||||
.into_factory(),
|
||||
|_| AppConfig::default(),
|
||||
))
|
||||
.tcp(),
|
||||
)
|
||||
});
|
||||
@ -280,8 +287,14 @@ async fn test_connection_wait_queue() {
|
||||
ok(io)
|
||||
})
|
||||
.and_then(
|
||||
HttpService::new(App::new().service(
|
||||
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||
HttpService::new(map_config(
|
||||
App::new()
|
||||
.service(
|
||||
web::resource("/")
|
||||
.route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||
)
|
||||
.into_factory(),
|
||||
|_| AppConfig::default(),
|
||||
))
|
||||
.tcp(),
|
||||
)
|
||||
@ -317,19 +330,22 @@ async fn test_connection_wait_queue_force_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let srv = test_server(move || {
|
||||
let srv =
|
||||
test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
.and_then(
|
||||
HttpService::new(
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
|
||||
),
|
||||
)
|
||||
HttpService::new(map_config(
|
||||
App::new()
|
||||
.service(web::resource("/").route(web::to(|| {
|
||||
HttpResponse::Ok().force_close().body(STR)
|
||||
})))
|
||||
.into_factory(),
|
||||
|_| AppConfig::default(),
|
||||
))
|
||||
.tcp(),
|
||||
)
|
||||
});
|
||||
|
@ -4,9 +4,9 @@ use std::sync::Arc;
|
||||
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::test_server;
|
||||
use actix_service::{pipeline_factory, ServiceFactory};
|
||||
use actix_service::{map_config, pipeline_factory, IntoServiceFactory, ServiceFactory};
|
||||
use actix_web::http::Version;
|
||||
use actix_web::{web, App, HttpResponse};
|
||||
use actix_web::{dev::AppConfig, web, App, HttpResponse};
|
||||
use futures::future::ok;
|
||||
use open_ssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
|
||||
use rust_tls::ClientConfig;
|
||||
@ -62,8 +62,14 @@ async fn _test_connection_reuse_h2() {
|
||||
})
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||
.h2(map_config(
|
||||
App::new()
|
||||
.service(
|
||||
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||
)
|
||||
.into_factory(),
|
||||
|_| AppConfig::default(),
|
||||
))
|
||||
.openssl(ssl_acceptor())
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
|
@ -4,9 +4,9 @@ use std::sync::Arc;
|
||||
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::test_server;
|
||||
use actix_service::{pipeline_factory, ServiceFactory};
|
||||
use actix_service::{map_config, pipeline_factory, IntoServiceFactory, ServiceFactory};
|
||||
use actix_web::http::Version;
|
||||
use actix_web::{web, App, HttpResponse};
|
||||
use actix_web::{dev::AppConfig, web, App, HttpResponse};
|
||||
use futures::future::ok;
|
||||
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
|
||||
|
||||
@ -44,8 +44,14 @@ async fn test_connection_reuse_h2() {
|
||||
})
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||
.h2(map_config(
|
||||
App::new()
|
||||
.service(
|
||||
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||
)
|
||||
.into_factory(),
|
||||
|_| AppConfig::default(),
|
||||
))
|
||||
.openssl(ssl_acceptor())
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
|
57
src/app.rs
57
src/app.rs
@ -5,6 +5,7 @@ use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::body::{Body, MessageBody};
|
||||
use actix_http::Extensions;
|
||||
use actix_service::boxed::{self, BoxServiceFactory};
|
||||
use actix_service::{
|
||||
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
|
||||
@ -12,7 +13,7 @@ use actix_service::{
|
||||
use futures::future::{FutureExt, LocalBoxFuture};
|
||||
|
||||
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
|
||||
use crate::config::{AppConfig, AppConfigInner, ServiceConfig};
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::data::{Data, DataFactory};
|
||||
use crate::dev::ResourceDef;
|
||||
use crate::error::Error;
|
||||
@ -36,8 +37,8 @@ pub struct App<T, B> {
|
||||
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||
data: Vec<Box<dyn DataFactory>>,
|
||||
data_factories: Vec<FnDataFactory>,
|
||||
config: AppConfigInner,
|
||||
external: Vec<ResourceDef>,
|
||||
extensions: Extensions,
|
||||
_t: PhantomData<B>,
|
||||
}
|
||||
|
||||
@ -52,8 +53,8 @@ impl App<AppEntry, Body> {
|
||||
services: Vec::new(),
|
||||
default: None,
|
||||
factory_ref: fref,
|
||||
config: AppConfigInner::default(),
|
||||
external: Vec::new(),
|
||||
extensions: Extensions::new(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -77,8 +78,9 @@ where
|
||||
/// an application instance. Http server constructs an application
|
||||
/// instance for each thread, thus application data must be constructed
|
||||
/// multiple times. If you want to share data between different
|
||||
/// threads, a shared object should be used, e.g. `Arc`. Application
|
||||
/// data does not need to be `Send` or `Sync`.
|
||||
/// threads, a shared object should be used, e.g. `Arc`. Internally `Data` type
|
||||
/// uses `Arc` so data could be created outside of app factory and clones could
|
||||
/// be stored via `App::app_data()` method.
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::cell::Cell;
|
||||
@ -135,10 +137,15 @@ where
|
||||
self
|
||||
}
|
||||
|
||||
/// 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));
|
||||
/// Set application level arbitrary data item.
|
||||
///
|
||||
/// Application data stored with `App::app_data()` method is available
|
||||
/// via `HttpRequest::app_data()` method at runtime.
|
||||
///
|
||||
/// This method could be used for storing `Data<T>` as well, in that case
|
||||
/// data could be accessed by using `Data<T>` extractor.
|
||||
pub fn app_data<U: 'static>(mut self, ext: U) -> Self {
|
||||
self.extensions.insert(ext);
|
||||
self
|
||||
}
|
||||
|
||||
@ -225,18 +232,6 @@ where
|
||||
self
|
||||
}
|
||||
|
||||
/// Set server host name.
|
||||
///
|
||||
/// Host name is used by application router as a hostname for url generation.
|
||||
/// Check [ConnectionInfo](./dev/struct.ConnectionInfo.html#method.host)
|
||||
/// documentation for more information.
|
||||
///
|
||||
/// By default host name is set to a "localhost" value.
|
||||
pub fn hostname(mut self, val: &str) -> Self {
|
||||
self.config.host = val.to_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Default service to be used if no matching resource could be found.
|
||||
///
|
||||
/// It is possible to use services like `Resource`, `Route`.
|
||||
@ -383,8 +378,8 @@ where
|
||||
services: self.services,
|
||||
default: self.default,
|
||||
factory_ref: self.factory_ref,
|
||||
config: self.config,
|
||||
external: self.external,
|
||||
extensions: self.extensions,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -445,8 +440,8 @@ where
|
||||
services: self.services,
|
||||
default: self.default,
|
||||
factory_ref: self.factory_ref,
|
||||
config: self.config,
|
||||
external: self.external,
|
||||
extensions: self.extensions,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -472,7 +467,7 @@ where
|
||||
external: RefCell::new(self.external),
|
||||
default: self.default,
|
||||
factory_ref: self.factory_ref,
|
||||
config: RefCell::new(AppConfig(Rc::new(self.config))),
|
||||
extensions: RefCell::new(Some(self.extensions)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -556,6 +551,20 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_extension() {
|
||||
let mut srv = init_service(App::new().app_data(10usize).service(
|
||||
web::resource("/").to(|req: HttpRequest| {
|
||||
assert_eq!(*req.app_data::<usize>().unwrap(), 10);
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = srv.call(req).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_wrap() {
|
||||
let mut srv = init_service(
|
||||
|
@ -39,9 +39,9 @@ where
|
||||
>,
|
||||
{
|
||||
pub(crate) endpoint: T,
|
||||
pub(crate) extensions: RefCell<Option<Extensions>>,
|
||||
pub(crate) data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||
pub(crate) data_factories: Rc<Vec<FnDataFactory>>,
|
||||
pub(crate) config: RefCell<AppConfig>,
|
||||
pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>,
|
||||
pub(crate) default: Option<Rc<HttpNewService>>,
|
||||
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||
@ -58,7 +58,7 @@ where
|
||||
InitError = (),
|
||||
>,
|
||||
{
|
||||
type Config = ();
|
||||
type Config = AppConfig;
|
||||
type Request = Request;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = T::Error;
|
||||
@ -66,7 +66,7 @@ where
|
||||
type Service = AppInitService<T::Service, B>;
|
||||
type Future = AppInitResult<T, B>;
|
||||
|
||||
fn new_service(&self, _: ()) -> Self::Future {
|
||||
fn new_service(&self, config: AppConfig) -> Self::Future {
|
||||
// update resource default service
|
||||
let default = self.default.clone().unwrap_or_else(|| {
|
||||
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| {
|
||||
@ -75,11 +75,7 @@ where
|
||||
});
|
||||
|
||||
// App config
|
||||
let mut config = AppService::new(
|
||||
self.config.borrow().clone(),
|
||||
default.clone(),
|
||||
self.data.clone(),
|
||||
);
|
||||
let mut config = AppService::new(config, default.clone(), self.data.clone());
|
||||
|
||||
// register services
|
||||
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
|
||||
@ -119,6 +115,12 @@ where
|
||||
data: self.data.clone(),
|
||||
data_factories: Vec::new(),
|
||||
data_factories_fut: self.data_factories.iter().map(|f| f()).collect(),
|
||||
extensions: Some(
|
||||
self.extensions
|
||||
.borrow_mut()
|
||||
.take()
|
||||
.unwrap_or_else(Extensions::new),
|
||||
),
|
||||
config,
|
||||
rmap,
|
||||
_t: PhantomData,
|
||||
@ -139,6 +141,7 @@ where
|
||||
data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||
data_factories: Vec<Box<dyn DataFactory>>,
|
||||
data_factories_fut: Vec<LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>,
|
||||
extensions: Option<Extensions>,
|
||||
_t: PhantomData<B>,
|
||||
}
|
||||
|
||||
@ -177,7 +180,7 @@ where
|
||||
|
||||
if this.endpoint.is_some() && this.data_factories_fut.is_empty() {
|
||||
// create app data container
|
||||
let mut data = Extensions::new();
|
||||
let mut data = this.extensions.take().unwrap();
|
||||
for f in this.data.iter() {
|
||||
f.create(&mut data);
|
||||
}
|
||||
|
@ -124,14 +124,20 @@ impl AppService {
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppConfig(pub(crate) Rc<AppConfigInner>);
|
||||
pub struct AppConfig(Rc<AppConfigInner>);
|
||||
|
||||
impl AppConfig {
|
||||
pub(crate) fn new(inner: AppConfigInner) -> Self {
|
||||
AppConfig(Rc::new(inner))
|
||||
struct AppConfigInner {
|
||||
secure: bool,
|
||||
host: String,
|
||||
addr: SocketAddr,
|
||||
}
|
||||
|
||||
/// Set server host name.
|
||||
impl AppConfig {
|
||||
pub(crate) fn new(secure: bool, addr: SocketAddr, host: String) -> Self {
|
||||
AppConfig(Rc::new(AppConfigInner { secure, addr, host }))
|
||||
}
|
||||
|
||||
/// Server host name.
|
||||
///
|
||||
/// Host name is used by application router as a hostname for url generation.
|
||||
/// Check [ConnectionInfo](./struct.ConnectionInfo.html#method.host)
|
||||
@ -153,19 +159,13 @@ impl AppConfig {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AppConfigInner {
|
||||
pub(crate) secure: bool,
|
||||
pub(crate) host: String,
|
||||
pub(crate) addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl Default for AppConfigInner {
|
||||
fn default() -> AppConfigInner {
|
||||
AppConfigInner {
|
||||
secure: false,
|
||||
addr: "127.0.0.1:8080".parse().unwrap(),
|
||||
host: "localhost:8080".to_owned(),
|
||||
}
|
||||
impl Default for AppConfig {
|
||||
fn default() -> Self {
|
||||
AppConfig::new(
|
||||
false,
|
||||
"127.0.0.1:8080".parse().unwrap(),
|
||||
"localhost:8080".to_owned(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
28
src/data.rs
28
src/data.rs
@ -56,7 +56,7 @@ pub(crate) trait DataFactory {
|
||||
///
|
||||
/// let app = App::new()
|
||||
/// // Store `MyData` in application storage.
|
||||
/// .register_data(data.clone())
|
||||
/// .app_data(data.clone())
|
||||
/// .service(
|
||||
/// web::resource("/index.html").route(
|
||||
/// web::get().to(index)));
|
||||
@ -87,10 +87,10 @@ impl<T> Data<T> {
|
||||
}
|
||||
|
||||
impl<T> Deref for Data<T> {
|
||||
type Target = T;
|
||||
type Target = Arc<T>;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
self.0.as_ref()
|
||||
fn deref(&self) -> &Arc<T> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
@ -107,8 +107,8 @@ impl<T: 'static> FromRequest for Data<T> {
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
if let Some(st) = req.get_app_data::<T>() {
|
||||
ok(st)
|
||||
if let Some(st) = req.app_data::<Data<T>>() {
|
||||
ok(st.clone())
|
||||
} else {
|
||||
log::debug!(
|
||||
"Failed to construct App-level Data extractor. \
|
||||
@ -144,9 +144,11 @@ mod tests {
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_data_extractor() {
|
||||
let mut srv =
|
||||
init_service(App::new().data(10usize).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
let mut srv = init_service(App::new().data("TEST".to_string()).service(
|
||||
web::resource("/").to(|data: web::Data<String>| {
|
||||
assert_eq!(data.to_lowercase(), "test");
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
))
|
||||
.await;
|
||||
|
||||
@ -165,9 +167,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_register_data_extractor() {
|
||||
async fn test_app_data_extractor() {
|
||||
let mut srv =
|
||||
init_service(App::new().register_data(Data::new(10usize)).service(
|
||||
init_service(App::new().app_data(Data::new(10usize)).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
))
|
||||
.await;
|
||||
@ -177,7 +179,7 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let mut srv =
|
||||
init_service(App::new().register_data(Data::new(10u32)).service(
|
||||
init_service(App::new().app_data(Data::new(10u32)).service(
|
||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||
))
|
||||
.await;
|
||||
@ -220,7 +222,7 @@ mod tests {
|
||||
let mut srv = init_service(App::new().data(1usize).service(
|
||||
web::resource("/").data(10usize).route(web::get().to(
|
||||
|data: web::Data<usize>| {
|
||||
assert_eq!(*data, 10);
|
||||
assert_eq!(**data, 10);
|
||||
let _ = data.clone();
|
||||
HttpResponse::Ok()
|
||||
},
|
||||
|
@ -8,7 +8,6 @@ use actix_router::{Path, Url};
|
||||
use futures::future::{ok, Ready};
|
||||
|
||||
use crate::config::AppConfig;
|
||||
use crate::data::Data;
|
||||
use crate::error::UrlGenerationError;
|
||||
use crate::extract::FromRequest;
|
||||
use crate::info::ConnectionInfo;
|
||||
@ -207,25 +206,15 @@ impl HttpRequest {
|
||||
&self.0.config
|
||||
}
|
||||
|
||||
/// Get an application data stored with `App::data()` method during
|
||||
/// Get an application data stored with `App::extension()` method during
|
||||
/// application configuration.
|
||||
pub fn app_data<T: 'static>(&self) -> Option<&T> {
|
||||
if let Some(st) = self.0.app_data.get::<Data<T>>() {
|
||||
if let Some(st) = self.0.app_data.get::<T>() {
|
||||
Some(&st)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get an application data stored with `App::data()` method during
|
||||
/// application configuration.
|
||||
pub fn get_app_data<T: 'static>(&self) -> Option<Data<T>> {
|
||||
if let Some(st) = self.0.app_data.get::<Data<T>>() {
|
||||
Some(st.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpMessage for HttpRequest {
|
||||
@ -467,8 +456,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_app_data() {
|
||||
let mut srv = init_service(App::new().data(10usize).service(
|
||||
async fn test_data() {
|
||||
let mut srv = init_service(App::new().app_data(10usize).service(
|
||||
web::resource("/").to(|req: HttpRequest| {
|
||||
if req.app_data::<usize>().is_some() {
|
||||
HttpResponse::Ok()
|
||||
@ -483,7 +472,7 @@ mod tests {
|
||||
let resp = call_service(&mut srv, req).await;
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let mut srv = init_service(App::new().data(10u32).service(
|
||||
let mut srv = init_service(App::new().app_data(10u32).service(
|
||||
web::resource("/").to(|req: HttpRequest| {
|
||||
if req.app_data::<usize>().is_some() {
|
||||
HttpResponse::Ok()
|
||||
|
@ -192,16 +192,13 @@ where
|
||||
/// }
|
||||
/// ```
|
||||
pub fn data<U: 'static>(self, data: U) -> Self {
|
||||
self.register_data(Data::new(data))
|
||||
self.app_data(Data::new(data))
|
||||
}
|
||||
|
||||
/// Set or override application data.
|
||||
///
|
||||
/// This method has the same effect as [`Resource::data`](#method.data),
|
||||
/// except that instead of taking a value of some type `T`, it expects a
|
||||
/// value of type `Data<T>`. Use a `Data<T>` extractor to retrieve its
|
||||
/// value.
|
||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
||||
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
|
||||
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
|
||||
if self.data.is_none() {
|
||||
self.data = Some(Extensions::new());
|
||||
}
|
||||
@ -754,19 +751,19 @@ mod tests {
|
||||
App::new()
|
||||
.data(1.0f64)
|
||||
.data(1usize)
|
||||
.register_data(web::Data::new('-'))
|
||||
.app_data(web::Data::new('-'))
|
||||
.service(
|
||||
web::resource("/test")
|
||||
.data(10usize)
|
||||
.register_data(web::Data::new('*'))
|
||||
.app_data(web::Data::new('*'))
|
||||
.guard(guard::Get())
|
||||
.to(
|
||||
|data1: web::Data<usize>,
|
||||
data2: web::Data<char>,
|
||||
data3: web::Data<f64>| {
|
||||
assert_eq!(*data1, 10);
|
||||
assert_eq!(*data2, '*');
|
||||
assert_eq!(*data3, 1.0);
|
||||
assert_eq!(**data1, 10);
|
||||
assert_eq!(**data2, '*');
|
||||
assert_eq!(**data3, 1.0);
|
||||
HttpResponse::Ok()
|
||||
},
|
||||
),
|
||||
|
24
src/scope.rs
24
src/scope.rs
@ -148,15 +148,13 @@ where
|
||||
/// }
|
||||
/// ```
|
||||
pub fn data<U: 'static>(self, data: U) -> Self {
|
||||
self.register_data(Data::new(data))
|
||||
self.app_data(Data::new(data))
|
||||
}
|
||||
|
||||
/// Set or override application data.
|
||||
///
|
||||
/// This method has the same effect as [`Scope::data`](#method.data), except
|
||||
/// that instead of taking a value of some type `T`, it expects a value of
|
||||
/// type `Data<T>`. Use a `Data<T>` extractor to retrieve its value.
|
||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
||||
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
|
||||
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
|
||||
if self.data.is_none() {
|
||||
self.data = Some(Extensions::new());
|
||||
}
|
||||
@ -1108,7 +1106,7 @@ mod tests {
|
||||
web::scope("app").data(10usize).route(
|
||||
"/t",
|
||||
web::get().to(|data: web::Data<usize>| {
|
||||
assert_eq!(*data, 10);
|
||||
assert_eq!(**data, 10);
|
||||
let _ = data.clone();
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
@ -1122,21 +1120,17 @@ mod tests {
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_override_register_data() {
|
||||
let mut srv = init_service(
|
||||
App::new().register_data(web::Data::new(1usize)).service(
|
||||
web::scope("app")
|
||||
.register_data(web::Data::new(10usize))
|
||||
.route(
|
||||
async fn test_override_app_data() {
|
||||
let mut srv = init_service(App::new().app_data(web::Data::new(1usize)).service(
|
||||
web::scope("app").app_data(web::Data::new(10usize)).route(
|
||||
"/t",
|
||||
web::get().to(|data: web::Data<usize>| {
|
||||
assert_eq!(*data, 10);
|
||||
assert_eq!(**data, 10);
|
||||
let _ = data.clone();
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
))
|
||||
.await;
|
||||
|
||||
let req = TestRequest::with_uri("/app/t").to_request();
|
||||
|
@ -6,7 +6,9 @@ use actix_http::{
|
||||
body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response,
|
||||
};
|
||||
use actix_server::{Server, ServerBuilder};
|
||||
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
|
||||
use actix_service::{
|
||||
map_config, pipeline_factory, IntoServiceFactory, Service, ServiceFactory,
|
||||
};
|
||||
use futures::future::ok;
|
||||
|
||||
use net2::TcpBuilder;
|
||||
@ -16,12 +18,15 @@ use actix_tls::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
|
||||
#[cfg(feature = "rustls")]
|
||||
use actix_tls::rustls::ServerConfig as RustlsServerConfig;
|
||||
|
||||
use crate::config::AppConfig;
|
||||
|
||||
struct Socket {
|
||||
scheme: &'static str,
|
||||
addr: net::SocketAddr,
|
||||
}
|
||||
|
||||
struct Config {
|
||||
host: Option<String>,
|
||||
keep_alive: KeepAlive,
|
||||
client_timeout: u64,
|
||||
client_shutdown: u64,
|
||||
@ -52,14 +57,13 @@ pub struct HttpServer<F, I, S, B>
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoServiceFactory<S>,
|
||||
S: ServiceFactory<Config = (), Request = Request>,
|
||||
S: ServiceFactory<Config = AppConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
B: MessageBody,
|
||||
{
|
||||
pub(super) factory: F,
|
||||
pub(super) host: Option<String>,
|
||||
config: Arc<Mutex<Config>>,
|
||||
backlog: i32,
|
||||
sockets: Vec<Socket>,
|
||||
@ -71,7 +75,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoServiceFactory<S>,
|
||||
S: ServiceFactory<Config = (), Request = Request>,
|
||||
S: ServiceFactory<Config = AppConfig, Request = Request>,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
@ -82,8 +86,8 @@ where
|
||||
pub fn new(factory: F) -> Self {
|
||||
HttpServer {
|
||||
factory,
|
||||
host: None,
|
||||
config: Arc::new(Mutex::new(Config {
|
||||
host: None,
|
||||
keep_alive: KeepAlive::Timeout(5),
|
||||
client_timeout: 5000,
|
||||
client_shutdown: 5000,
|
||||
@ -184,8 +188,8 @@ where
|
||||
/// documentation for more information.
|
||||
///
|
||||
/// By default host name is set to a "localhost" value.
|
||||
pub fn server_hostname<T: AsRef<str>>(mut self, val: T) -> Self {
|
||||
self.host = Some(val.as_ref().to_owned());
|
||||
pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
|
||||
self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
|
||||
self
|
||||
}
|
||||
|
||||
@ -246,11 +250,17 @@ where
|
||||
lst,
|
||||
move || {
|
||||
let c = cfg.lock().unwrap();
|
||||
let cfg = AppConfig::new(
|
||||
false,
|
||||
addr,
|
||||
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
|
||||
);
|
||||
|
||||
HttpService::build()
|
||||
.keep_alive(c.keep_alive)
|
||||
.client_timeout(c.client_timeout)
|
||||
.local_addr(addr)
|
||||
.finish(factory())
|
||||
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.tcp()
|
||||
},
|
||||
)?;
|
||||
@ -288,11 +298,16 @@ where
|
||||
lst,
|
||||
move || {
|
||||
let c = cfg.lock().unwrap();
|
||||
let cfg = AppConfig::new(
|
||||
true,
|
||||
addr,
|
||||
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
|
||||
);
|
||||
HttpService::build()
|
||||
.keep_alive(c.keep_alive)
|
||||
.client_timeout(c.client_timeout)
|
||||
.client_disconnect(c.client_shutdown)
|
||||
.finish(factory())
|
||||
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.openssl(acceptor.clone())
|
||||
},
|
||||
)?;
|
||||
@ -330,11 +345,16 @@ where
|
||||
lst,
|
||||
move || {
|
||||
let c = cfg.lock().unwrap();
|
||||
let cfg = AppConfig::new(
|
||||
true,
|
||||
addr,
|
||||
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
|
||||
);
|
||||
HttpService::build()
|
||||
.keep_alive(c.keep_alive)
|
||||
.client_timeout(c.client_timeout)
|
||||
.client_disconnect(c.client_shutdown)
|
||||
.finish(factory())
|
||||
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.rustls(config.clone())
|
||||
},
|
||||
)?;
|
||||
@ -435,24 +455,31 @@ where
|
||||
|
||||
let cfg = self.config.clone();
|
||||
let factory = self.factory.clone();
|
||||
// todo duplicated:
|
||||
self.sockets.push(Socket {
|
||||
scheme: "http",
|
||||
addr: net::SocketAddr::new(
|
||||
let socket_addr = net::SocketAddr::new(
|
||||
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
||||
8080,
|
||||
),
|
||||
);
|
||||
self.sockets.push(Socket {
|
||||
scheme: "http",
|
||||
addr: socket_addr,
|
||||
});
|
||||
|
||||
let addr = format!("actix-web-service-{:?}", lst.local_addr()?);
|
||||
|
||||
self.builder = self.builder.listen_uds(addr, lst, move || {
|
||||
let c = cfg.lock().unwrap();
|
||||
let config = AppConfig::new(
|
||||
false,
|
||||
socket_addr,
|
||||
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
|
||||
);
|
||||
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None))).and_then(
|
||||
HttpService::build()
|
||||
.keep_alive(c.keep_alive)
|
||||
.client_timeout(c.client_timeout)
|
||||
.finish(factory()),
|
||||
.finish(map_config(factory().into_factory(), move |_| {
|
||||
config.clone()
|
||||
})),
|
||||
)
|
||||
})?;
|
||||
Ok(self)
|
||||
@ -470,12 +497,13 @@ where
|
||||
|
||||
let cfg = self.config.clone();
|
||||
let factory = self.factory.clone();
|
||||
self.sockets.push(Socket {
|
||||
scheme: "http",
|
||||
addr: net::SocketAddr::new(
|
||||
let socket_addr = net::SocketAddr::new(
|
||||
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
||||
8080,
|
||||
),
|
||||
);
|
||||
self.sockets.push(Socket {
|
||||
scheme: "http",
|
||||
addr: socket_addr,
|
||||
});
|
||||
|
||||
self.builder = self.builder.bind_uds(
|
||||
@ -483,12 +511,19 @@ where
|
||||
addr,
|
||||
move || {
|
||||
let c = cfg.lock().unwrap();
|
||||
let config = AppConfig::new(
|
||||
false,
|
||||
socket_addr,
|
||||
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
|
||||
);
|
||||
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None)))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.keep_alive(c.keep_alive)
|
||||
.client_timeout(c.client_timeout)
|
||||
.finish(factory()),
|
||||
.finish(map_config(factory().into_factory(), move |_| {
|
||||
config.clone()
|
||||
})),
|
||||
)
|
||||
},
|
||||
)?;
|
||||
@ -500,7 +535,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoServiceFactory<S>,
|
||||
S: ServiceFactory<Config = (), Request = Request>,
|
||||
S: ServiceFactory<Config = AppConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
112
src/test.rs
112
src/test.rs
@ -1,5 +1,6 @@
|
||||
//! Various helpers for Actix applications to use during testing.
|
||||
use std::convert::TryFrom;
|
||||
use std::net::SocketAddr;
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc;
|
||||
use std::{fmt, net, thread, time};
|
||||
@ -12,7 +13,9 @@ use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
|
||||
use actix_router::{Path, ResourceDef, Url};
|
||||
use actix_rt::System;
|
||||
use actix_server::Server;
|
||||
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||
use actix_service::{
|
||||
map_config, IntoService, IntoServiceFactory, Service, ServiceFactory,
|
||||
};
|
||||
use awc::error::PayloadError;
|
||||
use awc::{Client, ClientRequest, ClientResponse, Connector};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
@ -25,7 +28,7 @@ use serde_json;
|
||||
|
||||
pub use actix_http::test::TestBuffer;
|
||||
|
||||
use crate::config::{AppConfig, AppConfigInner};
|
||||
use crate::config::AppConfig;
|
||||
use crate::data::Data;
|
||||
use crate::dev::{Body, MessageBody, Payload};
|
||||
use crate::request::HttpRequestPool;
|
||||
@ -79,7 +82,7 @@ pub async fn init_service<R, S, B, E>(
|
||||
where
|
||||
R: IntoServiceFactory<S>,
|
||||
S: ServiceFactory<
|
||||
Config = (),
|
||||
Config = AppConfig,
|
||||
Request = Request,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = E,
|
||||
@ -87,7 +90,7 @@ where
|
||||
S::InitError: std::fmt::Debug,
|
||||
{
|
||||
let srv = app.into_factory();
|
||||
srv.new_service(()).await.unwrap()
|
||||
srv.new_service(AppConfig::default()).await.unwrap()
|
||||
}
|
||||
|
||||
/// Calls service and waits for response future completion.
|
||||
@ -296,8 +299,9 @@ where
|
||||
pub struct TestRequest {
|
||||
req: HttpTestRequest,
|
||||
rmap: ResourceMap,
|
||||
config: AppConfigInner,
|
||||
config: AppConfig,
|
||||
path: Path<Url>,
|
||||
peer_addr: Option<SocketAddr>,
|
||||
app_data: Extensions,
|
||||
}
|
||||
|
||||
@ -306,8 +310,9 @@ impl Default for TestRequest {
|
||||
TestRequest {
|
||||
req: HttpTestRequest::default(),
|
||||
rmap: ResourceMap::new(ResourceDef::new("")),
|
||||
config: AppConfigInner::default(),
|
||||
config: AppConfig::default(),
|
||||
path: Path::new(Url::new(Uri::default())),
|
||||
peer_addr: None,
|
||||
app_data: Extensions::new(),
|
||||
}
|
||||
}
|
||||
@ -407,6 +412,12 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set peer addr
|
||||
pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
|
||||
self.peer_addr = Some(addr);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set request payload
|
||||
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
|
||||
self.req.set_payload(data);
|
||||
@ -440,6 +451,13 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set application data. This is equivalent of `App::app_data()` method
|
||||
/// for testing purpose.
|
||||
pub fn app_data<T: 'static>(mut self, data: T) -> Self {
|
||||
self.app_data.insert(data);
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// Set request config
|
||||
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
|
||||
@ -449,12 +467,15 @@ impl TestRequest {
|
||||
|
||||
/// Complete request creation and generate `Request` instance
|
||||
pub fn to_request(mut self) -> Request {
|
||||
self.req.finish()
|
||||
let mut req = self.req.finish();
|
||||
req.head_mut().peer_addr = self.peer_addr;
|
||||
req
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `ServiceRequest` instance
|
||||
pub fn to_srv_request(mut self) -> ServiceRequest {
|
||||
let (head, payload) = self.req.finish().into_parts();
|
||||
let (mut head, payload) = self.req.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
ServiceRequest::new(HttpRequest::new(
|
||||
@ -462,7 +483,7 @@ impl TestRequest {
|
||||
head,
|
||||
payload,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
self.config.clone(),
|
||||
Rc::new(self.app_data),
|
||||
HttpRequestPool::create(),
|
||||
))
|
||||
@ -475,7 +496,8 @@ impl TestRequest {
|
||||
|
||||
/// Complete request creation and generate `HttpRequest` instance
|
||||
pub fn to_http_request(mut self) -> HttpRequest {
|
||||
let (head, payload) = self.req.finish().into_parts();
|
||||
let (mut head, payload) = self.req.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
HttpRequest::new(
|
||||
@ -483,7 +505,7 @@ impl TestRequest {
|
||||
head,
|
||||
payload,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
self.config.clone(),
|
||||
Rc::new(self.app_data),
|
||||
HttpRequestPool::create(),
|
||||
)
|
||||
@ -491,7 +513,8 @@ impl TestRequest {
|
||||
|
||||
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
||||
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
||||
let (head, payload) = self.req.finish().into_parts();
|
||||
let (mut head, payload) = self.req.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
let req = HttpRequest::new(
|
||||
@ -499,7 +522,7 @@ impl TestRequest {
|
||||
head,
|
||||
Payload::None,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
self.config.clone(),
|
||||
Rc::new(self.app_data),
|
||||
HttpRequestPool::create(),
|
||||
);
|
||||
@ -538,7 +561,7 @@ pub fn start<F, I, S, B>(factory: F) -> TestServer
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoServiceFactory<S>,
|
||||
S: ServiceFactory<Config = (), Request = Request> + 'static,
|
||||
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<HttpResponse<B>> + 'static,
|
||||
@ -577,7 +600,7 @@ pub fn start_with<F, I, S, B>(cfg: TestServerConfig, factory: F) -> TestServer
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoServiceFactory<S>,
|
||||
S: ServiceFactory<Config = (), Request = Request> + 'static,
|
||||
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<HttpResponse<B>> + 'static,
|
||||
@ -607,63 +630,87 @@ where
|
||||
match cfg.stream {
|
||||
StreamType::Tcp => match cfg.tp {
|
||||
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(false, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.h1(factory())
|
||||
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.tcp()
|
||||
}),
|
||||
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(false, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.h2(factory())
|
||||
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.tcp()
|
||||
}),
|
||||
HttpVer::Both => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(false, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.finish(factory())
|
||||
.finish(map_config(factory().into_factory(), move |_| {
|
||||
cfg.clone()
|
||||
}))
|
||||
.tcp()
|
||||
}),
|
||||
},
|
||||
#[cfg(feature = "openssl")]
|
||||
StreamType::Openssl(acceptor) => match cfg.tp {
|
||||
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.h1(factory())
|
||||
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.openssl(acceptor.clone())
|
||||
}),
|
||||
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.h2(factory())
|
||||
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.openssl(acceptor.clone())
|
||||
}),
|
||||
HttpVer::Both => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.finish(factory())
|
||||
.finish(map_config(factory().into_factory(), move |_| {
|
||||
cfg.clone()
|
||||
}))
|
||||
.openssl(acceptor.clone())
|
||||
}),
|
||||
},
|
||||
#[cfg(feature = "rustls")]
|
||||
StreamType::Rustls(config) => match cfg.tp {
|
||||
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.h1(factory())
|
||||
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.rustls(config.clone())
|
||||
}),
|
||||
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.h2(factory())
|
||||
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
|
||||
.rustls(config.clone())
|
||||
}),
|
||||
HttpVer::Both => builder.listen("test", tcp, move || {
|
||||
let cfg =
|
||||
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||
HttpService::build()
|
||||
.client_timeout(ctimeout)
|
||||
.finish(factory())
|
||||
.finish(map_config(factory().into_factory(), move |_| {
|
||||
cfg.clone()
|
||||
}))
|
||||
.rustls(config.clone())
|
||||
}),
|
||||
},
|
||||
@ -924,19 +971,24 @@ mod tests {
|
||||
.set(header::Date(SystemTime::now().into()))
|
||||
.param("test", "123")
|
||||
.data(10u32)
|
||||
.app_data(20u64)
|
||||
.peer_addr("127.0.0.1:8081".parse().unwrap())
|
||||
.to_http_request();
|
||||
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
||||
assert!(req.headers().contains_key(header::DATE));
|
||||
assert_eq!(
|
||||
req.head().peer_addr,
|
||||
Some("127.0.0.1:8081".parse().unwrap())
|
||||
);
|
||||
assert_eq!(&req.match_info()["test"], "123");
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
let data = req.get_app_data::<u32>().unwrap();
|
||||
assert!(req.get_app_data::<u64>().is_none());
|
||||
assert_eq!(*data, 10);
|
||||
let data = req.app_data::<Data<u32>>().unwrap();
|
||||
assert!(req.app_data::<Data<u64>>().is_none());
|
||||
assert_eq!(*data.get_ref(), 10);
|
||||
|
||||
assert!(req.app_data::<u64>().is_none());
|
||||
let data = req.app_data::<u32>().unwrap();
|
||||
assert_eq!(*data, 10);
|
||||
assert!(req.app_data::<u32>().is_none());
|
||||
let data = req.app_data::<u64>().unwrap();
|
||||
assert_eq!(*data, 20);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
|
@ -190,7 +190,7 @@ impl<T: Serialize> Responder for Form<T> {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/index.html")
|
||||
/// // change `Form` extractor configuration
|
||||
/// .data(
|
||||
/// .app_data(
|
||||
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
|
||||
/// )
|
||||
/// .route(web::get().to(index))
|
||||
|
@ -224,7 +224,8 @@ where
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/index.html").data(
|
||||
/// web::resource("/index.html")
|
||||
/// .app_data(
|
||||
/// // change json extractor configuration
|
||||
/// web::Json::<Info>::configure(|cfg| {
|
||||
/// cfg.limit(4096)
|
||||
@ -462,7 +463,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
||||
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
||||
let msg = MyObject {
|
||||
name: "invalid request".to_string(),
|
||||
};
|
||||
@ -514,7 +515,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().limit(10))
|
||||
.app_data(JsonConfig::default().limit(10))
|
||||
.to_http_parts();
|
||||
|
||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||
@ -531,7 +532,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(
|
||||
.app_data(
|
||||
JsonConfig::default()
|
||||
.limit(10)
|
||||
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
|
||||
@ -604,7 +605,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().limit(4096))
|
||||
.app_data(JsonConfig::default().limit(4096))
|
||||
.to_http_parts();
|
||||
|
||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||
@ -622,7 +623,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||
}))
|
||||
.to_http_parts();
|
||||
@ -642,7 +643,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||
}))
|
||||
.to_http_parts();
|
||||
|
@ -15,6 +15,8 @@ use crate::FromRequest;
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||
/// Extract typed information from the request's path.
|
||||
///
|
||||
/// [**PathConfig**](struct.PathConfig.html) allows to configure extraction process.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```rust
|
||||
@ -212,7 +214,7 @@ where
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/messages/{folder}")
|
||||
/// .data(PathConfig::default().error_handler(|err, req| {
|
||||
/// .app_data(PathConfig::default().error_handler(|err, req| {
|
||||
/// error::InternalError::from_response(
|
||||
/// err,
|
||||
/// HttpResponse::Conflict().finish(),
|
||||
@ -358,7 +360,7 @@ mod tests {
|
||||
#[actix_rt::test]
|
||||
async fn test_custom_err_handler() {
|
||||
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
|
||||
.data(PathConfig::default().error_handler(|err, _| {
|
||||
.app_data(PathConfig::default().error_handler(|err, _| {
|
||||
error::InternalError::from_response(
|
||||
err,
|
||||
HttpResponse::Conflict().finish(),
|
||||
|
@ -176,7 +176,7 @@ impl FromRequest for Bytes {
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/index.html")
|
||||
/// .data(String::configure(|cfg| { // <- limit size of the payload
|
||||
/// .app_data(String::configure(|cfg| { // <- limit size of the payload
|
||||
/// cfg.limit(4096)
|
||||
/// }))
|
||||
/// .route(web::get().to(index)) // <- register handler with extractor params
|
||||
|
@ -19,6 +19,8 @@ use crate::request::HttpRequest;
|
||||
/// be decoded into any type which depends upon data ordering e.g. tuples or tuple-structs.
|
||||
/// Attempts to do so will *fail at runtime*.
|
||||
///
|
||||
/// [**QueryConfig**](struct.QueryConfig.html) allows to configure extraction process.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```rust
|
||||
@ -185,7 +187,7 @@ where
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/index.html").data(
|
||||
/// web::resource("/index.html").app_data(
|
||||
/// // change query extractor configuration
|
||||
/// web::Query::<Info>::configure(|cfg| {
|
||||
/// cfg.error_handler(|err, req| { // <- create custom error response
|
||||
@ -273,7 +275,7 @@ mod tests {
|
||||
#[actix_rt::test]
|
||||
async fn test_custom_error_responder() {
|
||||
let req = TestRequest::with_uri("/name/user1/")
|
||||
.data(QueryConfig::default().error_handler(|e, _| {
|
||||
.app_data(QueryConfig::default().error_handler(|e, _| {
|
||||
let resp = HttpResponse::UnprocessableEntity().finish();
|
||||
InternalError::from_response(e, resp).into()
|
||||
}))
|
||||
|
@ -55,5 +55,5 @@ time = "0.1"
|
||||
open-ssl = { version="0.10", package="openssl", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = "2.0.0-alpha.5"
|
||||
actix-http = "1.0.0"
|
||||
actix-web = "2.0.0-rc"
|
||||
actix-http = "1.0.1"
|
||||
|
@ -5,8 +5,7 @@ use std::{net, thread, time::Duration};
|
||||
#[cfg(feature = "openssl")]
|
||||
use open_ssl::ssl::SslAcceptorBuilder;
|
||||
|
||||
use actix_http::Response;
|
||||
use actix_web::{web, App, HttpServer};
|
||||
use actix_web::{web, App, HttpResponse, HttpServer};
|
||||
|
||||
fn unused_addr() -> net::SocketAddr {
|
||||
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
||||
@ -28,7 +27,7 @@ async fn test_start() {
|
||||
|
||||
let srv = HttpServer::new(|| {
|
||||
App::new().service(
|
||||
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
|
||||
web::resource("/").route(web::to(|| HttpResponse::Ok().body("test"))),
|
||||
)
|
||||
})
|
||||
.workers(1)
|
||||
@ -91,6 +90,8 @@ fn ssl_acceptor() -> std::io::Result<SslAcceptorBuilder> {
|
||||
#[actix_rt::test]
|
||||
#[cfg(feature = "openssl")]
|
||||
async fn test_start_ssl() {
|
||||
use actix_web::HttpRequest;
|
||||
|
||||
let addr = unused_addr();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
@ -99,9 +100,10 @@ async fn test_start_ssl() {
|
||||
let builder = ssl_acceptor().unwrap();
|
||||
|
||||
let srv = HttpServer::new(|| {
|
||||
App::new().service(
|
||||
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
|
||||
)
|
||||
App::new().service(web::resource("/").route(web::to(|req: HttpRequest| {
|
||||
assert!(req.app_config().secure());
|
||||
HttpResponse::Ok().body("test")
|
||||
})))
|
||||
})
|
||||
.workers(1)
|
||||
.shutdown_timeout(1)
|
||||
|
@ -675,7 +675,7 @@ async fn test_brotli_encoding_large() {
|
||||
let srv = test::start_with(test::config().h1(), || {
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.data(web::PayloadConfig::new(320_000))
|
||||
.app_data(web::PayloadConfig::new(320_000))
|
||||
.route(web::to(move |body: Bytes| {
|
||||
HttpResponse::Ok().streaming(TestBody::new(body, 10240))
|
||||
})),
|
||||
|
Reference in New Issue
Block a user