1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-15 22:34:47 +02:00

Compare commits

...

18 Commits

Author SHA1 Message Date
Nikolay Kim
3d1af19080 prepare actix-http release 2019-05-04 19:51:13 -07:00
Nikolay Kim
fa78da8156 unify route and app data, it allows to provide global extractor config #775 2019-05-04 19:43:49 -07:00
Nikolay Kim
01cfcf3b75 update changes 2019-05-04 08:42:27 -07:00
James
7ef4f5ac0b Make request headers optional in CORS preflight (#816) 2019-05-04 08:41:37 -07:00
Nikolay Kim
fc19ce41c4 Clean up response extensions in response pool #817 2019-05-03 15:26:34 -07:00
Otavio Salvador
6e00eef63a awc: Fix typo on ResponseError documentation (#815)
* awc: Fix typo on ResponseError documentation

Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>

* http: Fix typo on ResponseError documentation

Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>

* http: Expand type names for openssl related errors documentation

Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
2019-05-03 14:30:00 -07:00
Nikolay Kim
337c2febe3 add more tests 2019-05-02 09:49:10 -07:00
Nikolay Kim
f27beab016 fix case for transfer-encoding header name 2019-05-02 09:30:00 -07:00
Max Bo
4f1c6d1bb7 Update MIGRATION.md (#811) 2019-05-02 09:26:51 -07:00
Nikolay Kim
6b34909537 Fix NormalizePath middleware impl #806 2019-05-01 12:40:56 -07:00
Douman
87284f0951 Add doctest to verify NormalizePath middleware (#809) 2019-05-01 11:47:51 -07:00
Nikolay Kim
24bd5b1344 update readmes 2019-04-29 20:47:21 -07:00
Nikolay Kim
94a0d1a6bc remove old api doc refs 2019-04-29 18:42:21 -07:00
Nikolay Kim
f4e1205cbb fix reactor drop panic 2019-04-29 10:14:08 -07:00
Nikolay Kim
d2c1791067 add async handler test with blocking call 2019-04-29 09:45:37 -07:00
Nikolay Kim
f4b4875cb1 Add helper function for executing futures test::block_fn() 2019-04-29 09:34:14 -07:00
Nikolay Kim
29a841529f Allow to construct Data instances to avoid double Arc for Send + Sync types. 2019-04-29 09:26:12 -07:00
Darin
b51b5b763c added clarification to docs regarding middleware processing sequence, added delete method to TestRequest (#799)
* added clarification to docs regarding middleware processing sequnce

* added delete method to TestRequest, doc, and test
2019-04-29 09:14:36 -07:00
35 changed files with 595 additions and 483 deletions

View File

@@ -1,5 +1,32 @@
# Changes # Changes
## [1.0.0-beta.3] - 2019-05-04
### Added
* Add helper function for executing futures `test::block_fn()`
### Changed
* Extractor configuration could be registered with `App::data()`
or with `Resource::data()` #775
* Route data is unified with app data, `Route::data()` moved to resource
level to `Resource::data()`
* CORS handling without headers #702
* Allow to construct `Data` instances to avoid double `Arc` for `Send + Sync` types.
### Fixed
* Fix `NormalizePath` middleware impl #806
### Deleted
* `App::data_factory()` is deleted.
## [1.0.0-beta.2] - 2019-04-24 ## [1.0.0-beta.2] - 2019-04-24
### Added ### Added

View File

@@ -164,7 +164,7 @@
* `HttpRequest::body()`, `HttpRequest::urlencoded()`, `HttpRequest::json()`, `HttpRequest::multipart()` * `HttpRequest::body()`, `HttpRequest::urlencoded()`, `HttpRequest::json()`, `HttpRequest::multipart()`
method have been removed. Use `Bytes`, `String`, `Form`, `Json`, `Multipart` extractors instead. method have been removed. Use `Bytes`, `String`, `Form`, `Json`, `Multipart` extractors instead.
instead if instead of
```rust ```rust
fn index(req: &HttpRequest) -> Responder { fn index(req: &HttpRequest) -> Responder {
@@ -173,6 +173,7 @@
... ...
}) })
} }
```
use use

View File

@@ -1 +1,9 @@
# Static files support for actix web [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-files)](https://crates.io/crates/actix-files) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Static files support for actix web [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-files)](https://crates.io/crates/actix-files) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [User Guide](https://actix.rs/docs/)
* [API Documentation](https://docs.rs/actix-files/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-files](https://crates.io/crates/actix-files)
* Minimum supported Rust version: 1.33 or later

View File

@@ -66,6 +66,7 @@ impl NamedFile {
/// let mut file = File::create("foo.txt")?; /// let mut file = File::create("foo.txt")?;
/// file.write_all(b"Hello, world!")?; /// file.write_all(b"Hello, world!")?;
/// let named_file = NamedFile::from_file(file, "bar.txt")?; /// let named_file = NamedFile::from_file(file, "bar.txt")?;
/// # std::fs::remove_file("foo.txt");
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```

View File

@@ -1 +1,8 @@
# Framed app for actix web [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-framed)](https://crates.io/crates/actix-framed) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Framed app for actix web [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-framed)](https://crates.io/crates/actix-framed) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [API Documentation](https://docs.rs/actix-framed/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-framed](https://crates.io/crates/actix-framed)
* Minimum supported Rust version: 1.33 or later

View File

@@ -1,5 +1,12 @@
# Changes # Changes
## [0.1.5] - 2019-05-04
### Fixed
* Clean up response extensions in response pool #817
## [0.1.4] - 2019-04-24 ## [0.1.4] - 2019-04-24
### Added ### Added

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-http" name = "actix-http"
version = "0.1.4" version = "0.1.5"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http primitives" description = "Actix http primitives"
readme = "README.md" readme = "README.md"

View File

@@ -137,7 +137,7 @@ impl<E: ResponseError> ResponseError for TimeoutError<E> {
#[display(fmt = "UnknownError")] #[display(fmt = "UnknownError")]
struct UnitError; struct UnitError;
/// `InternalServerError` for `JsonError` /// `InternalServerError` for `UnitError`
impl ResponseError for UnitError {} impl ResponseError for UnitError {}
/// `InternalServerError` for `JsonError` /// `InternalServerError` for `JsonError`
@@ -150,11 +150,11 @@ impl ResponseError for FormError {}
impl ResponseError for TimerError {} impl ResponseError for TimerError {}
#[cfg(feature = "ssl")] #[cfg(feature = "ssl")]
/// `InternalServerError` for `SslError` /// `InternalServerError` for `openssl::ssl::Error`
impl ResponseError for openssl::ssl::Error {} impl ResponseError for openssl::ssl::Error {}
#[cfg(feature = "ssl")] #[cfg(feature = "ssl")]
/// `InternalServerError` for `SslError` /// `InternalServerError` for `openssl::ssl::HandshakeError`
impl ResponseError for openssl::ssl::HandshakeError<tokio_tcp::TcpStream> {} impl ResponseError for openssl::ssl::HandshakeError<tokio_tcp::TcpStream> {}
/// Return `BAD_REQUEST` for `de::value::Error` /// Return `BAD_REQUEST` for `de::value::Error`

View File

@@ -82,7 +82,7 @@ pub(crate) trait MessageType: Sized {
if camel_case { if camel_case {
dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n") dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n")
} else { } else {
dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n") dst.put_slice(b"\r\ntransfer-encoding: chunked\r\n")
} }
} else { } else {
skip_len = false; skip_len = false;
@@ -564,5 +564,18 @@ mod tests {
bytes.take().freeze(), bytes.take().freeze(),
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: xml\r\nContent-Type: plain/text\r\n\r\n") Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: xml\r\nContent-Type: plain/text\r\n\r\n")
); );
head.set_camel_case_headers(false);
let _ = head.encode_headers(
&mut bytes,
Version::HTTP_11,
BodySize::Stream,
ConnectionType::KeepAlive,
&ServiceConfig::default(),
);
assert_eq!(
bytes.take().freeze(),
Bytes::from_static(b"\r\ntransfer-encoding: chunked\r\ndate: date\r\ncontent-type: xml\r\ncontent-type: plain/text\r\n\r\n")
);
} }
} }

View File

@@ -449,6 +449,7 @@ impl BoxedResponsePool {
fn release(&self, msg: Box<ResponseHead>) { fn release(&self, msg: Box<ResponseHead>) {
let v = &mut self.0.borrow_mut(); let v = &mut self.0.borrow_mut();
if v.len() < 128 { if v.len() < 128 {
msg.extensions.borrow_mut().clear();
v.push(msg); v.push(msg);
} }
} }

View File

@@ -1 +1,8 @@
# Multipart support for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-multipart)](https://crates.io/crates/actix-multipart) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Multipart support for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-multipart)](https://crates.io/crates/actix-multipart) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [API Documentation](https://docs.rs/actix-multipart/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-multipart](https://crates.io/crates/actix-multipart)
* Minimum supported Rust version: 1.33 or later

View File

@@ -1 +1,9 @@
# Session for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-session)](https://crates.io/crates/actix-session) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Session for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-session)](https://crates.io/crates/actix-session) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [User Guide](https://actix.rs/docs/)
* [API Documentation](https://docs.rs/actix-session/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-session](https://crates.io/crates/actix-session)
* Minimum supported Rust version: 1.33 or later

View File

@@ -1 +1,8 @@
Actix actors support for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-web-actors)](https://crates.io/crates/actix-web-actors) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Actix actors support for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-web-actors)](https://crates.io/crates/actix-web-actors) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [API Documentation](https://docs.rs/actix-web-actors/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-web-actors](https://crates.io/crates/actix-web-actors)
* Minimum supported Rust version: 1.33 or later

View File

@@ -1,7 +1,7 @@
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::TestServer; use actix_http_test::TestServer;
use actix_web::{http, App, HttpResponse, Responder}; use actix_web::{http, App, HttpResponse, Responder};
use actix_web_codegen::get; use actix_web_codegen::{get, post, put};
use futures::{future, Future}; use futures::{future, Future};
#[get("/test")] #[get("/test")]
@@ -9,6 +9,16 @@ fn test() -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
#[put("/test")]
fn put_test() -> impl Responder {
HttpResponse::Created()
}
#[post("/test")]
fn post_test() -> impl Responder {
HttpResponse::NoContent()
}
#[get("/test")] #[get("/test")]
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> { fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
future::ok(HttpResponse::Ok().finish()) future::ok(HttpResponse::Ok().finish())
@@ -21,11 +31,28 @@ fn auto_sync() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
#[test] #[test]
fn test_body() { fn test_body() {
let mut srv = TestServer::new(|| HttpService::new(App::new().service(test))); let mut srv = TestServer::new(|| {
HttpService::new(
App::new()
.service(post_test)
.service(put_test)
.service(test),
)
});
let request = srv.request(http::Method::GET, srv.url("/test")); let request = srv.request(http::Method::GET, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap(); let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
let request = srv.request(http::Method::PUT, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
assert_eq!(response.status(), http::StatusCode::CREATED);
let request = srv.request(http::Method::POST, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
let mut srv = TestServer::new(|| HttpService::new(App::new().service(auto_sync))); let mut srv = TestServer::new(|| HttpService::new(App::new().service(auto_sync)));
let request = srv.request(http::Method::GET, srv.url("/test")); let request = srv.request(http::Method::GET, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap(); let response = srv.block_on(request.send()).unwrap();

View File

@@ -8,10 +8,13 @@ keywords = ["actix", "http", "framework", "async", "web"]
homepage = "https://actix.rs" homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git" repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/awc/" documentation = "https://docs.rs/awc/"
categories = ["network-programming", "asynchronous",
"web-programming::http-client",
"web-programming::websocket"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
workspace = ".."
edition = "2018" edition = "2018"
workspace = ".."
[lib] [lib]
name = "awc" name = "awc"

View File

@@ -65,7 +65,7 @@ pub enum JsonPayloadError {
Payload(PayloadError), Payload(PayloadError),
} }
/// Return `InternlaServerError` for `JsonPayloadError` /// Return `InternalServerError` for `JsonPayloadError`
impl ResponseError for JsonPayloadError { impl ResponseError for JsonPayloadError {
fn error_response(&self) -> Response { fn error_response(&self) -> Response {
Response::new(StatusCode::INTERNAL_SERVER_ERROR) Response::new(StatusCode::INTERNAL_SERVER_ERROR)

View File

@@ -95,21 +95,8 @@ where
/// web::get().to(index))); /// web::get().to(index)));
/// } /// }
/// ``` /// ```
pub fn data<S: 'static>(mut self, data: S) -> Self { pub fn data<U: Into<Data<U>> + 'static>(mut self, data: U) -> Self {
self.data.push(Box::new(Data::new(data))); self.data.push(Box::new(data.into()));
self
}
/// Set application data factory. This function is
/// similar to `.data()` but it accepts data factory. Data object get
/// constructed asynchronously during application initialization.
pub fn data_factory<F, R>(mut self, data: F) -> Self
where
F: Fn() -> R + 'static,
R: IntoFuture + 'static,
R::Error: std::fmt::Debug,
{
self.data.push(Box::new(data));
self self
} }
@@ -301,7 +288,15 @@ where
/// lifecycle (request -> response), modifying request/response as /// lifecycle (request -> response), modifying request/response as
/// necessary, across all requests managed by the *Application*. /// necessary, across all requests managed by the *Application*.
/// ///
/// Use middleware when you need to read or modify *every* request or response in some way. /// Use middleware when you need to read or modify *every* request or
/// response in some way.
///
/// Notice that the keyword for registering middleware is `wrap`. As you
/// 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
/// the builder chain. Consequently, the *first* middleware registered
/// in the builder chain is the *last* to execute during request processing.
/// ///
/// ```rust /// ```rust
/// use actix_service::Service; /// use actix_service::Service;
@@ -417,9 +412,9 @@ where
{ {
fn into_new_service(self) -> AppInit<T, B> { fn into_new_service(self) -> AppInit<T, B> {
AppInit { AppInit {
data: self.data, data: Rc::new(self.data),
endpoint: self.endpoint, endpoint: self.endpoint,
services: RefCell::new(self.services), services: Rc::new(RefCell::new(self.services)),
external: RefCell::new(self.external), external: RefCell::new(self.external),
default: self.default, default: self.default,
factory_ref: self.factory_ref, factory_ref: self.factory_ref,
@@ -437,7 +432,9 @@ mod tests {
use super::*; use super::*;
use crate::http::{header, HeaderValue, Method, StatusCode}; use crate::http::{header, HeaderValue, Method, StatusCode};
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::{ServiceRequest, ServiceResponse};
use crate::test::{block_on, call_service, init_service, read_body, TestRequest}; use crate::test::{
block_fn, block_on, call_service, init_service, read_body, TestRequest,
};
use crate::{web, Error, HttpRequest, HttpResponse}; use crate::{web, Error, HttpRequest, HttpResponse};
#[test] #[test]
@@ -446,7 +443,7 @@ mod tests {
App::new().service(web::resource("/test").to(|| HttpResponse::Ok())), App::new().service(web::resource("/test").to(|| HttpResponse::Ok())),
); );
let req = TestRequest::with_uri("/test").to_request(); let req = TestRequest::with_uri("/test").to_request();
let resp = block_on(srv.call(req)).unwrap(); let resp = block_fn(|| srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/blah").to_request(); let req = TestRequest::with_uri("/blah").to_request();
@@ -483,24 +480,24 @@ mod tests {
assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(resp.status(), StatusCode::CREATED);
} }
#[test] // #[test]
fn test_data_factory() { // fn test_data_factory() {
let mut srv = // let mut srv =
init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service( // init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), // web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
)); // ));
let req = TestRequest::default().to_request(); // let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap(); // let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK); // assert_eq!(resp.status(), StatusCode::OK);
let mut srv = // let mut srv =
init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service( // init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), // web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
)); // ));
let req = TestRequest::default().to_request(); // let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap(); // let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); // assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} // }
fn md<S, B>( fn md<S, B>(
req: ServiceRequest, req: ServiceRequest,

View File

@@ -2,7 +2,7 @@ use std::cell::RefCell;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::rc::Rc; use std::rc::Rc;
use actix_http::{Request, Response}; use actix_http::{Extensions, Request, Response};
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url}; use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::boxed::{self, BoxedNewService, BoxedService}; use actix_service::boxed::{self, BoxedNewService, BoxedService};
@@ -11,7 +11,7 @@ use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use crate::config::{AppConfig, AppService}; use crate::config::{AppConfig, AppService};
use crate::data::{DataFactory, DataFactoryResult}; use crate::data::DataFactory;
use crate::error::Error; use crate::error::Error;
use crate::guard::Guard; use crate::guard::Guard;
use crate::request::{HttpRequest, HttpRequestPool}; use crate::request::{HttpRequest, HttpRequestPool};
@@ -38,9 +38,9 @@ where
>, >,
{ {
pub(crate) endpoint: T, pub(crate) endpoint: T,
pub(crate) data: Vec<Box<DataFactory>>, pub(crate) data: Rc<Vec<Box<DataFactory>>>,
pub(crate) config: RefCell<AppConfig>, pub(crate) config: RefCell<AppConfig>,
pub(crate) services: RefCell<Vec<Box<ServiceFactory>>>, pub(crate) services: Rc<RefCell<Vec<Box<ServiceFactory>>>>,
pub(crate) default: Option<Rc<HttpNewService>>, pub(crate) default: Option<Rc<HttpNewService>>,
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>, pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
pub(crate) external: RefCell<Vec<ResourceDef>>, pub(crate) external: RefCell<Vec<ResourceDef>>,
@@ -70,6 +70,7 @@ where
}))) })))
}); });
// App config
{ {
let mut c = self.config.borrow_mut(); let mut c = self.config.borrow_mut();
let loc_cfg = Rc::get_mut(&mut c.0).unwrap(); let loc_cfg = Rc::get_mut(&mut c.0).unwrap();
@@ -77,7 +78,11 @@ where
loc_cfg.addr = cfg.local_addr(); loc_cfg.addr = cfg.local_addr();
} }
let mut config = AppService::new(self.config.borrow().clone(), default.clone()); let mut config = AppService::new(
self.config.borrow().clone(),
default.clone(),
self.data.clone(),
);
// register services // register services
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new()) std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
@@ -86,12 +91,13 @@ where
let mut rmap = ResourceMap::new(ResourceDef::new("")); let mut rmap = ResourceMap::new(ResourceDef::new(""));
let (config, services) = config.into_services();
// complete pipeline creation // complete pipeline creation
*self.factory_ref.borrow_mut() = Some(AppRoutingFactory { *self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
default, default,
services: Rc::new( services: Rc::new(
config services
.into_services()
.into_iter() .into_iter()
.map(|(mut rdef, srv, guards, nested)| { .map(|(mut rdef, srv, guards, nested)| {
rmap.add(&mut rdef, nested); rmap.add(&mut rdef, nested);
@@ -110,11 +116,17 @@ where
let rmap = Rc::new(rmap); let rmap = Rc::new(rmap);
rmap.finish(rmap.clone()); rmap.finish(rmap.clone());
// create app data container
let mut data = Extensions::new();
for f in self.data.iter() {
f.create(&mut data);
}
AppInitResult { AppInitResult {
endpoint: None, endpoint: None,
endpoint_fut: self.endpoint.new_service(&()), endpoint_fut: self.endpoint.new_service(&()),
data: self.data.iter().map(|s| s.construct()).collect(), data: Rc::new(data),
config: self.config.borrow().clone(), config,
rmap, rmap,
_t: PhantomData, _t: PhantomData,
} }
@@ -128,8 +140,8 @@ where
endpoint: Option<T::Service>, endpoint: Option<T::Service>,
endpoint_fut: T::Future, endpoint_fut: T::Future,
rmap: Rc<ResourceMap>, rmap: Rc<ResourceMap>,
data: Vec<Box<DataFactoryResult>>,
config: AppConfig, config: AppConfig,
data: Rc<Extensions>,
_t: PhantomData<B>, _t: PhantomData<B>,
} }
@@ -146,27 +158,18 @@ where
type Error = T::InitError; type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut idx = 0;
let mut extensions = self.config.0.extensions.borrow_mut();
while idx < self.data.len() {
if let Async::Ready(_) = self.data[idx].poll_result(&mut extensions)? {
self.data.remove(idx);
} else {
idx += 1;
}
}
if self.endpoint.is_none() { if self.endpoint.is_none() {
if let Async::Ready(srv) = self.endpoint_fut.poll()? { if let Async::Ready(srv) = self.endpoint_fut.poll()? {
self.endpoint = Some(srv); self.endpoint = Some(srv);
} }
} }
if self.endpoint.is_some() && self.data.is_empty() { if self.endpoint.is_some() {
Ok(Async::Ready(AppInitService { Ok(Async::Ready(AppInitService {
service: self.endpoint.take().unwrap(), service: self.endpoint.take().unwrap(),
rmap: self.rmap.clone(), rmap: self.rmap.clone(),
config: self.config.clone(), config: self.config.clone(),
data: self.data.clone(),
pool: HttpRequestPool::create(), pool: HttpRequestPool::create(),
})) }))
} else { } else {
@@ -183,6 +186,7 @@ where
service: T, service: T,
rmap: Rc<ResourceMap>, rmap: Rc<ResourceMap>,
config: AppConfig, config: AppConfig,
data: Rc<Extensions>,
pool: &'static HttpRequestPool, pool: &'static HttpRequestPool,
} }
@@ -207,6 +211,7 @@ where
inner.path.get_mut().update(&head.uri); inner.path.get_mut().update(&head.uri);
inner.path.reset(); inner.path.reset();
inner.head = head; inner.head = head;
inner.app_data = self.data.clone();
req req
} else { } else {
HttpRequest::new( HttpRequest::new(
@@ -214,6 +219,7 @@ where
head, head,
self.rmap.clone(), self.rmap.clone(),
self.config.clone(), self.config.clone(),
self.data.clone(),
self.pool, self.pool,
) )
}; };

View File

@@ -1,11 +1,9 @@
use std::cell::{Ref, RefCell};
use std::net::SocketAddr; use std::net::SocketAddr;
use std::rc::Rc; use std::rc::Rc;
use actix_http::Extensions; use actix_http::Extensions;
use actix_router::ResourceDef; use actix_router::ResourceDef;
use actix_service::{boxed, IntoNewService, NewService}; use actix_service::{boxed, IntoNewService, NewService};
use futures::IntoFuture;
use crate::data::{Data, DataFactory}; use crate::data::{Data, DataFactory};
use crate::error::Error; use crate::error::Error;
@@ -33,14 +31,20 @@ pub struct AppService {
Option<Guards>, Option<Guards>,
Option<Rc<ResourceMap>>, Option<Rc<ResourceMap>>,
)>, )>,
route_data: Rc<Vec<Box<DataFactory>>>,
} }
impl AppService { impl AppService {
/// Crate server settings instance /// Crate server settings instance
pub(crate) fn new(config: AppConfig, default: Rc<HttpNewService>) -> Self { pub(crate) fn new(
config: AppConfig,
default: Rc<HttpNewService>,
route_data: Rc<Vec<Box<DataFactory>>>,
) -> Self {
AppService { AppService {
config, config,
default, default,
route_data,
root: true, root: true,
services: Vec::new(), services: Vec::new(),
} }
@@ -53,13 +57,16 @@ impl AppService {
pub(crate) fn into_services( pub(crate) fn into_services(
self, self,
) -> Vec<( ) -> (
AppConfig,
Vec<(
ResourceDef, ResourceDef,
HttpNewService, HttpNewService,
Option<Guards>, Option<Guards>,
Option<Rc<ResourceMap>>, Option<Rc<ResourceMap>>,
)> { )>,
self.services ) {
(self.config, self.services)
} }
pub(crate) fn clone_config(&self) -> Self { pub(crate) fn clone_config(&self) -> Self {
@@ -68,6 +75,7 @@ impl AppService {
default: self.default.clone(), default: self.default.clone(),
services: Vec::new(), services: Vec::new(),
root: false, root: false,
route_data: self.route_data.clone(),
} }
} }
@@ -81,6 +89,15 @@ impl AppService {
self.default.clone() self.default.clone()
} }
/// Set global route data
pub fn set_route_data(&self, extensions: &mut Extensions) -> bool {
for f in self.route_data.iter() {
f.create(extensions);
}
!self.route_data.is_empty()
}
/// Register http service
pub fn register_service<F, S>( pub fn register_service<F, S>(
&mut self, &mut self,
rdef: ResourceDef, rdef: ResourceDef,
@@ -133,24 +150,12 @@ impl AppConfig {
pub fn local_addr(&self) -> SocketAddr { pub fn local_addr(&self) -> SocketAddr {
self.0.addr self.0.addr
} }
/// Resource map
pub fn rmap(&self) -> &ResourceMap {
&self.0.rmap
}
/// Application extensions
pub fn extensions(&self) -> Ref<Extensions> {
self.0.extensions.borrow()
}
} }
pub(crate) struct AppConfigInner { pub(crate) struct AppConfigInner {
pub(crate) secure: bool, pub(crate) secure: bool,
pub(crate) host: String, pub(crate) host: String,
pub(crate) addr: SocketAddr, pub(crate) addr: SocketAddr,
pub(crate) rmap: ResourceMap,
pub(crate) extensions: RefCell<Extensions>,
} }
impl Default for AppConfigInner { impl Default for AppConfigInner {
@@ -159,8 +164,6 @@ impl Default for AppConfigInner {
secure: false, secure: false,
addr: "127.0.0.1:8080".parse().unwrap(), addr: "127.0.0.1:8080".parse().unwrap(),
host: "localhost:8080".to_owned(), host: "localhost:8080".to_owned(),
rmap: ResourceMap::new(ResourceDef::new("")),
extensions: RefCell::new(Extensions::new()),
} }
} }
} }
@@ -188,23 +191,8 @@ impl ServiceConfig {
/// by using `Data<T>` extractor where `T` is data type. /// by using `Data<T>` extractor where `T` is data type.
/// ///
/// This is same as `App::data()` method. /// This is same as `App::data()` method.
pub fn data<S: 'static>(&mut self, data: S) -> &mut Self { pub fn data<S: Into<Data<S>> + 'static>(&mut self, data: S) -> &mut Self {
self.data.push(Box::new(Data::new(data))); self.data.push(Box::new(data.into()));
self
}
/// Set application data factory. This function is
/// similar to `.data()` but it accepts data factory. Data object get
/// constructed asynchronously during application initialization.
///
/// This is same as `App::data_dactory()` method.
pub fn data_factory<F, R>(&mut self, data: F) -> &mut Self
where
F: Fn() -> R + 'static,
R: IntoFuture + 'static,
R::Error: std::fmt::Debug,
{
self.data.push(Box::new(data));
self self
} }
@@ -254,8 +242,6 @@ impl ServiceConfig {
mod tests { mod tests {
use actix_service::Service; use actix_service::Service;
use bytes::Bytes; use bytes::Bytes;
use futures::Future;
use tokio_timer::sleep;
use super::*; use super::*;
use crate::http::{Method, StatusCode}; use crate::http::{Method, StatusCode};
@@ -277,37 +263,37 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
#[test] // #[test]
fn test_data_factory() { // fn test_data_factory() {
let cfg = |cfg: &mut ServiceConfig| { // let cfg = |cfg: &mut ServiceConfig| {
cfg.data_factory(|| { // cfg.data_factory(|| {
sleep(std::time::Duration::from_millis(50)).then(|_| { // sleep(std::time::Duration::from_millis(50)).then(|_| {
println!("READY"); // println!("READY");
Ok::<_, ()>(10usize) // Ok::<_, ()>(10usize)
}) // })
}); // });
}; // };
let mut srv = // let mut srv =
init_service(App::new().configure(cfg).service( // init_service(App::new().configure(cfg).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()), // web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
)); // ));
let req = TestRequest::default().to_request(); // let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap(); // let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK); // assert_eq!(resp.status(), StatusCode::OK);
let cfg2 = |cfg: &mut ServiceConfig| { // let cfg2 = |cfg: &mut ServiceConfig| {
cfg.data_factory(|| Ok::<_, ()>(10u32)); // cfg.data_factory(|| Ok::<_, ()>(10u32));
}; // };
let mut srv = init_service( // let mut srv = init_service(
App::new() // App::new()
.service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())) // .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()))
.configure(cfg2), // .configure(cfg2),
); // );
let req = TestRequest::default().to_request(); // let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap(); // let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); // assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} // }
#[test] #[test]
fn test_external_resource() { fn test_external_resource() {

View File

@@ -3,7 +3,6 @@ use std::sync::Arc;
use actix_http::error::{Error, ErrorInternalServerError}; use actix_http::error::{Error, ErrorInternalServerError};
use actix_http::Extensions; use actix_http::Extensions;
use futures::{Async, Future, IntoFuture, Poll};
use crate::dev::Payload; use crate::dev::Payload;
use crate::extract::FromRequest; use crate::extract::FromRequest;
@@ -11,11 +10,7 @@ use crate::request::HttpRequest;
/// Application data factory /// Application data factory
pub(crate) trait DataFactory { pub(crate) trait DataFactory {
fn construct(&self) -> Box<DataFactoryResult>; fn create(&self, extensions: &mut Extensions) -> bool;
}
pub(crate) trait DataFactoryResult {
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()>;
} }
/// Application data. /// Application data.
@@ -33,29 +28,33 @@ pub(crate) trait DataFactoryResult {
/// instance for each thread, thus application data must be constructed /// instance for each thread, thus application data must be constructed
/// multiple times. If you want to share data between different /// multiple times. If you want to share data between different
/// threads, a shareable object should be used, e.g. `Send + Sync`. Application /// threads, a shareable object should be used, e.g. `Send + Sync`. Application
/// data does not need to be `Send` or `Sync`. Internally `Data` instance /// data does not need to be `Send` or `Sync`. Internally `Data` type
/// uses `Arc`. /// uses `Arc`. if your data implements `Send` + `Sync` traits you can
/// use `web::Data::new()` and avoid double `Arc`.
/// ///
/// If route data is not set for a handler, using `Data<T>` extractor would /// If route data is not set for a handler, using `Data<T>` extractor would
/// cause *Internal Server Error* response. /// cause *Internal Server Error* response.
/// ///
/// ```rust /// ```rust
/// use std::cell::Cell; /// use std::sync::Mutex;
/// use actix_web::{web, App}; /// use actix_web::{web, App};
/// ///
/// struct MyData { /// struct MyData {
/// counter: Cell<usize>, /// counter: usize,
/// } /// }
/// ///
/// /// Use `Data<T>` extractor to access data in handler. /// /// Use `Data<T>` extractor to access data in handler.
/// fn index(data: web::Data<MyData>) { /// fn index(data: web::Data<Mutex<MyData>>) {
/// data.counter.set(data.counter.get() + 1); /// let mut data = data.lock().unwrap();
/// data.counter += 1;
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));
///
/// let app = App::new() /// let app = App::new()
/// // Store `MyData` in application storage. /// // Store `MyData` in application storage.
/// .data(MyData{ counter: Cell::new(0) }) /// .data(data.clone())
/// .service( /// .service(
/// web::resource("/index.html").route( /// web::resource("/index.html").route(
/// web::get().to(index))); /// web::get().to(index)));
@@ -65,7 +64,12 @@ pub(crate) trait DataFactoryResult {
pub struct Data<T>(Arc<T>); pub struct Data<T>(Arc<T>);
impl<T> Data<T> { impl<T> Data<T> {
pub(crate) fn new(state: T) -> Data<T> { /// Create new `Data` instance.
///
/// Internally `Data` type uses `Arc`. if your data implements
/// `Send` + `Sync` traits you can use `web::Data::new()` and
/// avoid double `Arc`.
pub fn new(state: T) -> Data<T> {
Data(Arc::new(state)) Data(Arc::new(state))
} }
@@ -89,6 +93,12 @@ impl<T> Clone for Data<T> {
} }
} }
impl<T> From<T> for Data<T> {
fn from(data: T) -> Self {
Data::new(data)
}
}
impl<T: 'static> FromRequest for Data<T> { impl<T: 'static> FromRequest for Data<T> {
type Config = (); type Config = ();
type Error = Error; type Error = Error;
@@ -96,8 +106,8 @@ impl<T: 'static> FromRequest for Data<T> {
#[inline] #[inline]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
if let Some(st) = req.app_config().extensions().get::<Data<T>>() { if let Some(st) = req.get_app_data::<T>() {
Ok(st.clone()) Ok(st)
} else { } else {
log::debug!( log::debug!(
"Failed to construct App-level Data extractor. \ "Failed to construct App-level Data extractor. \
@@ -112,142 +122,12 @@ impl<T: 'static> FromRequest for Data<T> {
} }
impl<T: 'static> DataFactory for Data<T> { impl<T: 'static> DataFactory for Data<T> {
fn construct(&self) -> Box<DataFactoryResult> { fn create(&self, extensions: &mut Extensions) -> bool {
Box::new(DataFut { st: self.clone() }) if !extensions.contains::<Data<T>>() {
} let _ = extensions.insert(Data(self.0.clone()));
} true
struct DataFut<T> {
st: Data<T>,
}
impl<T: 'static> DataFactoryResult for DataFut<T> {
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
extensions.insert(self.st.clone());
Ok(Async::Ready(()))
}
}
impl<F, Out> DataFactory for F
where
F: Fn() -> Out + 'static,
Out: IntoFuture + 'static,
Out::Error: std::fmt::Debug,
{
fn construct(&self) -> Box<DataFactoryResult> {
Box::new(DataFactoryFut {
fut: (*self)().into_future(),
})
}
}
struct DataFactoryFut<T, F>
where
F: Future<Item = T>,
F::Error: std::fmt::Debug,
{
fut: F,
}
impl<T: 'static, F> DataFactoryResult for DataFactoryFut<T, F>
where
F: Future<Item = T>,
F::Error: std::fmt::Debug,
{
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
match self.fut.poll() {
Ok(Async::Ready(s)) => {
extensions.insert(Data::new(s));
Ok(Async::Ready(()))
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(e) => {
log::error!("Can not construct application state: {:?}", e);
Err(())
}
}
}
}
/// Route data.
///
/// Route data is an arbitrary data attached to specific route.
/// Route data could be added to route during route configuration process
/// with `Route::data()` method. Route data is also used as an extractor
/// configuration storage. Route data could be accessed in handler
/// via `RouteData<T>` extractor.
///
/// If route data is not set for a handler, using `RouteData` extractor
/// would cause *Internal Server Error* response.
///
/// ```rust
/// # use std::cell::Cell;
/// use actix_web::{web, App};
///
/// struct MyData {
/// counter: Cell<usize>,
/// }
///
/// /// Use `RouteData<T>` extractor to access data in handler.
/// fn index(data: web::RouteData<MyData>) {
/// data.counter.set(data.counter.get() + 1);
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html").route(
/// web::get()
/// // Store `MyData` in route storage
/// .data(MyData{ counter: Cell::new(0) })
/// // Route data could be used as extractor configuration storage,
/// // limit size of the payload
/// .data(web::PayloadConfig::new(4096))
/// // register handler
/// .to(index)
/// ));
/// }
/// ```
pub struct RouteData<T>(Arc<T>);
impl<T> RouteData<T> {
pub(crate) fn new(state: T) -> RouteData<T> {
RouteData(Arc::new(state))
}
/// Get referecnce to inner data object.
pub fn get_ref(&self) -> &T {
self.0.as_ref()
}
}
impl<T> Deref for RouteData<T> {
type Target = T;
fn deref(&self) -> &T {
self.0.as_ref()
}
}
impl<T> Clone for RouteData<T> {
fn clone(&self) -> RouteData<T> {
RouteData(self.0.clone())
}
}
impl<T: 'static> FromRequest for RouteData<T> {
type Config = ();
type Error = Error;
type Future = Result<Self, Error>;
#[inline]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
if let Some(st) = req.route_data::<T>() {
Ok(st.clone())
} else { } else {
log::debug!("Failed to construct Route-level Data extractor"); false
Err(ErrorInternalServerError(
"Route data is not configured, to configure use Route::data()",
))
} }
} }
} }
@@ -282,8 +162,9 @@ mod tests {
#[test] #[test]
fn test_route_data_extractor() { fn test_route_data_extractor() {
let mut srv = init_service(App::new().service(web::resource("/").route( let mut srv =
web::get().data(10usize).to(|data: web::RouteData<usize>| { init_service(App::new().service(web::resource("/").data(10usize).route(
web::get().to(|data: web::Data<usize>| {
let _ = data.clone(); let _ = data.clone();
HttpResponse::Ok() HttpResponse::Ok()
}), }),
@@ -296,15 +177,30 @@ mod tests {
// different type // different type
let mut srv = init_service( let mut srv = init_service(
App::new().service( App::new().service(
web::resource("/").route( web::resource("/")
web::get()
.data(10u32) .data(10u32)
.to(|_: web::RouteData<usize>| HttpResponse::Ok()), .route(web::get().to(|_: web::Data<usize>| HttpResponse::Ok())),
),
), ),
); );
let req = TestRequest::default().to_request(); let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap(); let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} }
#[test]
fn test_override_data() {
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);
let _ = data.clone();
HttpResponse::Ok()
},
)),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
} }

View File

@@ -283,7 +283,7 @@ mod tests {
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/x-www-form-urlencoded", "application/x-www-form-urlencoded",
) )
.route_data(FormConfig::default().limit(4096)) .data(FormConfig::default().limit(4096))
.to_http_parts(); .to_http_parts();
let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap(); let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap();

View File

@@ -1,8 +1,6 @@
use std::cell::RefCell;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::rc::Rc;
use actix_http::{Error, Extensions, Payload, Response}; use actix_http::{Error, Payload, Response};
use actix_service::{NewService, Service, Void}; use actix_service::{NewService, Service, Void};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{try_ready, Async, Future, IntoFuture, Poll}; use futures::{try_ready, Async, Future, IntoFuture, Poll};
@@ -267,15 +265,13 @@ where
/// Extract arguments from request /// Extract arguments from request
pub struct Extract<T: FromRequest, S> { pub struct Extract<T: FromRequest, S> {
config: Rc<RefCell<Option<Rc<Extensions>>>>,
service: S, service: S,
_t: PhantomData<T>, _t: PhantomData<T>,
} }
impl<T: FromRequest, S> Extract<T, S> { impl<T: FromRequest, S> Extract<T, S> {
pub fn new(config: Rc<RefCell<Option<Rc<Extensions>>>>, service: S) -> Self { pub fn new(service: S) -> Self {
Extract { Extract {
config,
service, service,
_t: PhantomData, _t: PhantomData,
} }
@@ -297,14 +293,12 @@ where
fn new_service(&self, _: &()) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
ok(ExtractService { ok(ExtractService {
_t: PhantomData, _t: PhantomData,
config: self.config.borrow().clone(),
service: self.service.clone(), service: self.service.clone(),
}) })
} }
} }
pub struct ExtractService<T: FromRequest, S> { pub struct ExtractService<T: FromRequest, S> {
config: Option<Rc<Extensions>>,
service: S, service: S,
_t: PhantomData<T>, _t: PhantomData<T>,
} }
@@ -324,8 +318,7 @@ where
} }
fn call(&mut self, req: ServiceRequest) -> Self::Future { fn call(&mut self, req: ServiceRequest) -> Self::Future {
let (mut req, mut payload) = req.into_parts(); let (req, mut payload) = req.into_parts();
req.set_route_data(self.config.clone());
let fut = T::from_request(&req, &mut payload).into_future(); let fut = T::from_request(&req, &mut payload).into_future();
ExtractResponse { ExtractResponse {

View File

@@ -81,13 +81,6 @@ pub enum CorsError {
fmt = "The request header `Access-Control-Request-Headers` has an invalid value" fmt = "The request header `Access-Control-Request-Headers` has an invalid value"
)] )]
BadRequestHeaders, BadRequestHeaders,
/// The request header `Access-Control-Request-Headers` is required but is
/// missing.
#[display(
fmt = "The request header `Access-Control-Request-Headers` is required but is
missing"
)]
MissingRequestHeaders,
/// Origin is not allowed to make this request /// Origin is not allowed to make this request
#[display(fmt = "Origin is not allowed to make this request")] #[display(fmt = "Origin is not allowed to make this request")]
OriginNotAllowed, OriginNotAllowed,
@@ -661,15 +654,18 @@ impl Inner {
Err(_) => return Err(CorsError::BadRequestHeaders), Err(_) => return Err(CorsError::BadRequestHeaders),
}; };
} }
// `Access-Control-Request-Headers` must contain 1 or more
if !hdrs.is_empty() && !hdrs.is_subset(allowed_headers) { // `field-name`.
if !hdrs.is_empty() {
if !hdrs.is_subset(allowed_headers) {
return Err(CorsError::HeadersNotAllowed); return Err(CorsError::HeadersNotAllowed);
} }
return Ok(()); return Ok(());
} }
}
Err(CorsError::BadRequestHeaders) Err(CorsError::BadRequestHeaders)
} else { } else {
Err(CorsError::MissingRequestHeaders) return Ok(());
} }
} }
} }
@@ -874,6 +870,7 @@ mod tests {
let req = TestRequest::with_header("Origin", "https://www.example.com") let req = TestRequest::with_header("Origin", "https://www.example.com")
.method(Method::OPTIONS) .method(Method::OPTIONS)
.header(header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed")
.to_srv_request(); .to_srv_request();
assert!(cors.inner.validate_allowed_method(req.head()).is_err()); assert!(cors.inner.validate_allowed_method(req.head()).is_err());
@@ -887,7 +884,7 @@ mod tests {
.to_srv_request(); .to_srv_request();
assert!(cors.inner.validate_allowed_method(req.head()).is_err()); assert!(cors.inner.validate_allowed_method(req.head()).is_err());
assert!(cors.inner.validate_allowed_headers(req.head()).is_err()); assert!(cors.inner.validate_allowed_headers(req.head()).is_ok());
let req = TestRequest::with_header("Origin", "https://www.example.com") let req = TestRequest::with_header("Origin", "https://www.example.com")
.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST") .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")

View File

@@ -1,6 +1,8 @@
//! `Middleware` to normalize request's URI //! `Middleware` to normalize request's URI
use actix_http::http::{HttpTryFrom, PathAndQuery, Uri};
use actix_service::{Service, Transform}; use actix_service::{Service, Transform};
use bytes::Bytes;
use futures::future::{self, FutureResult}; use futures::future::{self, FutureResult};
use regex::Regex; use regex::Regex;
@@ -13,14 +15,30 @@ use crate::Error;
/// Performs following: /// Performs following:
/// ///
/// - Merges multiple slashes into one. /// - Merges multiple slashes into one.
///
/// ```rust
/// use actix_web::{web, http, middleware, App, HttpResponse};
///
/// fn main() {
/// let app = App::new()
/// .wrap(middleware::NormalizePath)
/// .service(
/// web::resource("/test")
/// .route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::method(http::Method::HEAD).to(|| HttpResponse::MethodNotAllowed()))
/// );
/// }
/// ```
pub struct NormalizePath; pub struct NormalizePath;
impl<S> Transform<S> for NormalizePath impl<S, B> Transform<S> for NormalizePath
where where
S: Service<Request = ServiceRequest, Response = ServiceResponse, Error = Error>, S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
{ {
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse; type Response = ServiceResponse<B>;
type Error = Error; type Error = Error;
type InitError = (); type InitError = ();
type Transform = NormalizePathNormalization<S>; type Transform = NormalizePathNormalization<S>;
@@ -39,12 +57,13 @@ pub struct NormalizePathNormalization<S> {
merge_slash: Regex, merge_slash: Regex,
} }
impl<S> Service for NormalizePathNormalization<S> impl<S, B> Service for NormalizePathNormalization<S>
where where
S: Service<Request = ServiceRequest, Response = ServiceResponse, Error = Error>, S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
{ {
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse; type Response = ServiceResponse<B>;
type Error = Error; type Error = Error;
type Future = S::Future; type Future = S::Future;
@@ -60,7 +79,19 @@ where
let path = self.merge_slash.replace_all(path, "/"); let path = self.merge_slash.replace_all(path, "/");
if original_len != path.len() { if original_len != path.len() {
head.uri = path.parse().unwrap(); let mut parts = head.uri.clone().into_parts();
let pq = parts.path_and_query.as_ref().unwrap();
let path = if let Some(q) = pq.query() {
Bytes::from(format!("{}?{}", path, q))
} else {
Bytes::from(path.as_ref())
};
parts.path_and_query = Some(PathAndQuery::try_from(path).unwrap());
let uri = Uri::from_parts(parts).unwrap();
req.match_info_mut().get_mut().update(&uri);
req.head_mut().uri = uri;
} }
self.service.call(req) self.service.call(req)
@@ -73,8 +104,21 @@ mod tests {
use super::*; use super::*;
use crate::dev::ServiceRequest; use crate::dev::ServiceRequest;
use crate::test::{block_on, TestRequest}; use crate::test::{block_on, call_service, init_service, TestRequest};
use crate::HttpResponse; use crate::{web, App, HttpResponse};
#[test]
fn test_wrap() {
let mut app = init_service(
App::new()
.wrap(NormalizePath::default())
.service(web::resource("/v1/something/").to(|| HttpResponse::Ok())),
);
let req = TestRequest::with_uri("/v1//something////").to_request();
let res = call_service(&mut app, req);
assert!(res.status().is_success());
}
#[test] #[test]
fn test_in_place_normalization() { fn test_in_place_normalization() {

View File

@@ -7,7 +7,7 @@ use actix_http::{Error, Extensions, HttpMessage, Message, Payload, RequestHead};
use actix_router::{Path, Url}; use actix_router::{Path, Url};
use crate::config::AppConfig; use crate::config::AppConfig;
use crate::data::{Data, RouteData}; use crate::data::Data;
use crate::error::UrlGenerationError; use crate::error::UrlGenerationError;
use crate::extract::FromRequest; use crate::extract::FromRequest;
use crate::info::ConnectionInfo; use crate::info::ConnectionInfo;
@@ -20,9 +20,9 @@ pub struct HttpRequest(pub(crate) Rc<HttpRequestInner>);
pub(crate) struct HttpRequestInner { pub(crate) struct HttpRequestInner {
pub(crate) head: Message<RequestHead>, pub(crate) head: Message<RequestHead>,
pub(crate) path: Path<Url>, pub(crate) path: Path<Url>,
pub(crate) app_data: Rc<Extensions>,
rmap: Rc<ResourceMap>, rmap: Rc<ResourceMap>,
config: AppConfig, config: AppConfig,
route_data: Option<Rc<Extensions>>,
pool: &'static HttpRequestPool, pool: &'static HttpRequestPool,
} }
@@ -33,6 +33,7 @@ impl HttpRequest {
head: Message<RequestHead>, head: Message<RequestHead>,
rmap: Rc<ResourceMap>, rmap: Rc<ResourceMap>,
config: AppConfig, config: AppConfig,
app_data: Rc<Extensions>,
pool: &'static HttpRequestPool, pool: &'static HttpRequestPool,
) -> HttpRequest { ) -> HttpRequest {
HttpRequest(Rc::new(HttpRequestInner { HttpRequest(Rc::new(HttpRequestInner {
@@ -40,8 +41,8 @@ impl HttpRequest {
path, path,
rmap, rmap,
config, config,
app_data,
pool, pool,
route_data: None,
})) }))
} }
} }
@@ -195,27 +196,23 @@ impl HttpRequest {
/// Get an application data stored with `App::data()` method during /// Get an application data stored with `App::data()` method during
/// application configuration. /// application configuration.
pub fn app_data<T: 'static>(&self) -> Option<Data<T>> { pub fn app_data<T: 'static>(&self) -> Option<&T> {
if let Some(st) = self.0.config.extensions().get::<Data<T>>() { if let Some(st) = self.0.app_data.get::<Data<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()) Some(st.clone())
} else { } else {
None None
} }
} }
/// Load route data. Route data could be set during
/// route configuration with `Route::data()` method.
pub fn route_data<T: 'static>(&self) -> Option<&RouteData<T>> {
if let Some(ref ext) = self.0.route_data {
ext.get::<RouteData<T>>()
} else {
None
}
}
pub(crate) fn set_route_data(&mut self, data: Option<Rc<Extensions>>) {
Rc::get_mut(&mut self.0).unwrap().route_data = data;
}
} }
impl HttpMessage for HttpRequest { impl HttpMessage for HttpRequest {

View File

@@ -2,7 +2,7 @@ use std::cell::RefCell;
use std::fmt; use std::fmt;
use std::rc::Rc; use std::rc::Rc;
use actix_http::{Error, Response}; use actix_http::{Error, Extensions, Response};
use actix_service::boxed::{self, BoxedNewService, BoxedService}; use actix_service::boxed::{self, BoxedNewService, BoxedService};
use actix_service::{ use actix_service::{
apply_transform, IntoNewService, IntoTransform, NewService, Service, Transform, apply_transform, IntoNewService, IntoTransform, NewService, Service, Transform,
@@ -10,6 +10,7 @@ use actix_service::{
use futures::future::{ok, Either, FutureResult}; use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, IntoFuture, Poll}; use futures::{Async, Future, IntoFuture, Poll};
use crate::data::Data;
use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef}; use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef};
use crate::extract::FromRequest; use crate::extract::FromRequest;
use crate::guard::Guard; use crate::guard::Guard;
@@ -48,6 +49,7 @@ pub struct Resource<T = ResourceEndpoint> {
rdef: String, rdef: String,
name: Option<String>, name: Option<String>,
routes: Vec<Route>, routes: Vec<Route>,
data: Option<Extensions>,
guards: Vec<Box<Guard>>, guards: Vec<Box<Guard>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>, default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
factory_ref: Rc<RefCell<Option<ResourceFactory>>>, factory_ref: Rc<RefCell<Option<ResourceFactory>>>,
@@ -64,6 +66,7 @@ impl Resource {
endpoint: ResourceEndpoint::new(fref.clone()), endpoint: ResourceEndpoint::new(fref.clone()),
factory_ref: fref, factory_ref: fref,
guards: Vec::new(), guards: Vec::new(),
data: None,
default: Rc::new(RefCell::new(None)), default: Rc::new(RefCell::new(None)),
} }
} }
@@ -154,7 +157,42 @@ where
/// # fn delete_handler() {} /// # fn delete_handler() {}
/// ``` /// ```
pub fn route(mut self, route: Route) -> Self { pub fn route(mut self, route: Route) -> Self {
self.routes.push(route.finish()); self.routes.push(route);
self
}
/// Provide resource specific data. This method allows to add extractor
/// configuration or specific state available via `Data<T>` extractor.
/// Provided data is available for all routes registered for the current resource.
/// Resource data overrides data registered by `App::data()` method.
///
/// ```rust
/// use actix_web::{web, App, FromRequest};
///
/// /// extract text data from request
/// fn index(body: String) -> String {
/// format!("Body {}!", body)
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html")
/// // limit size of the payload
/// .data(String::configure(|cfg| {
/// cfg.limit(4096)
/// }))
/// .route(
/// web::get()
/// // register handler
/// .to(index)
/// ));
/// }
/// ```
pub fn data<U: 'static>(mut self, data: U) -> Self {
if self.data.is_none() {
self.data = Some(Extensions::new());
}
self.data.as_mut().unwrap().insert(Data::new(data));
self self
} }
@@ -260,6 +298,7 @@ where
guards: self.guards, guards: self.guards,
routes: self.routes, routes: self.routes,
default: self.default, default: self.default,
data: self.data,
factory_ref: self.factory_ref, factory_ref: self.factory_ref,
} }
} }
@@ -361,6 +400,10 @@ where
if let Some(ref name) = self.name { if let Some(ref name) = self.name {
*rdef.name_mut() = name.clone(); *rdef.name_mut() = name.clone();
} }
// custom app data storage
if let Some(ref mut ext) = self.data {
config.set_route_data(ext);
}
config.register_service(rdef, guards, self, None) config.register_service(rdef, guards, self, None)
} }
} }
@@ -377,6 +420,7 @@ where
fn into_new_service(self) -> T { fn into_new_service(self) -> T {
*self.factory_ref.borrow_mut() = Some(ResourceFactory { *self.factory_ref.borrow_mut() = Some(ResourceFactory {
routes: self.routes, routes: self.routes,
data: self.data.map(|data| Rc::new(data)),
default: self.default, default: self.default,
}); });
@@ -386,6 +430,7 @@ where
pub struct ResourceFactory { pub struct ResourceFactory {
routes: Vec<Route>, routes: Vec<Route>,
data: Option<Rc<Extensions>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>, default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
} }
@@ -410,6 +455,7 @@ impl NewService for ResourceFactory {
.iter() .iter()
.map(|route| CreateRouteServiceItem::Future(route.new_service(&()))) .map(|route| CreateRouteServiceItem::Future(route.new_service(&())))
.collect(), .collect(),
data: self.data.clone(),
default: None, default: None,
default_fut, default_fut,
} }
@@ -423,6 +469,7 @@ enum CreateRouteServiceItem {
pub struct CreateResourceService { pub struct CreateResourceService {
fut: Vec<CreateRouteServiceItem>, fut: Vec<CreateRouteServiceItem>,
data: Option<Rc<Extensions>>,
default: Option<HttpService>, default: Option<HttpService>,
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>, default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
} }
@@ -467,6 +514,7 @@ impl Future for CreateResourceService {
.collect(); .collect();
Ok(Async::Ready(ResourceService { Ok(Async::Ready(ResourceService {
routes, routes,
data: self.data.clone(),
default: self.default.take(), default: self.default.take(),
})) }))
} else { } else {
@@ -477,6 +525,7 @@ impl Future for CreateResourceService {
pub struct ResourceService { pub struct ResourceService {
routes: Vec<RouteService>, routes: Vec<RouteService>,
data: Option<Rc<Extensions>>,
default: Option<HttpService>, default: Option<HttpService>,
} }
@@ -496,6 +545,9 @@ impl Service for ResourceService {
fn call(&mut self, mut req: ServiceRequest) -> Self::Future { fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
for route in self.routes.iter_mut() { for route in self.routes.iter_mut() {
if route.check(&mut req) { if route.check(&mut req) {
if let Some(ref data) = self.data {
req.set_data_container(data.clone());
}
return route.call(req); return route.call(req);
} }
} }

View File

@@ -1,12 +1,10 @@
use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use actix_http::{http::Method, Error, Extensions}; use actix_http::{http::Method, Error};
use actix_service::{NewService, Service}; use actix_service::{NewService, Service};
use futures::future::{ok, Either, FutureResult}; use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, IntoFuture, Poll}; use futures::{Async, Future, IntoFuture, Poll};
use crate::data::RouteData;
use crate::extract::FromRequest; use crate::extract::FromRequest;
use crate::guard::{self, Guard}; use crate::guard::{self, Guard};
use crate::handler::{AsyncFactory, AsyncHandler, Extract, Factory, Handler}; use crate::handler::{AsyncFactory, AsyncHandler, Extract, Factory, Handler};
@@ -44,30 +42,19 @@ type BoxedRouteNewService<Req, Res> = Box<
pub struct Route { pub struct Route {
service: BoxedRouteNewService<ServiceRequest, ServiceResponse>, service: BoxedRouteNewService<ServiceRequest, ServiceResponse>,
guards: Rc<Vec<Box<Guard>>>, guards: Rc<Vec<Box<Guard>>>,
data: Option<Extensions>,
data_ref: Rc<RefCell<Option<Rc<Extensions>>>>,
} }
impl Route { impl Route {
/// Create new route which matches any request. /// Create new route which matches any request.
pub fn new() -> Route { pub fn new() -> Route {
let data_ref = Rc::new(RefCell::new(None));
Route { Route {
service: Box::new(RouteNewService::new(Extract::new( service: Box::new(RouteNewService::new(Extract::new(Handler::new(|| {
data_ref.clone(), HttpResponse::NotFound()
Handler::new(|| HttpResponse::NotFound()), })))),
))),
guards: Rc::new(Vec::new()), guards: Rc::new(Vec::new()),
data: None,
data_ref,
} }
} }
pub(crate) fn finish(mut self) -> Self {
*self.data_ref.borrow_mut() = self.data.take().map(Rc::new);
self
}
pub(crate) fn take_guards(&mut self) -> Vec<Box<Guard>> { pub(crate) fn take_guards(&mut self) -> Vec<Box<Guard>> {
std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new()) std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new())
} }
@@ -239,10 +226,8 @@ impl Route {
T: FromRequest + 'static, T: FromRequest + 'static,
R: Responder + 'static, R: Responder + 'static,
{ {
self.service = Box::new(RouteNewService::new(Extract::new( self.service =
self.data_ref.clone(), Box::new(RouteNewService::new(Extract::new(Handler::new(handler))));
Handler::new(handler),
)));
self self
} }
@@ -281,42 +266,9 @@ impl Route {
R::Item: Responder, R::Item: Responder,
R::Error: Into<Error>, R::Error: Into<Error>,
{ {
self.service = Box::new(RouteNewService::new(Extract::new( self.service = Box::new(RouteNewService::new(Extract::new(AsyncHandler::new(
self.data_ref.clone(), handler,
AsyncHandler::new(handler), ))));
)));
self
}
/// Provide route specific data. This method allows to add extractor
/// configuration or specific state available via `RouteData<T>` extractor.
///
/// ```rust
/// use actix_web::{web, App, FromRequest};
///
/// /// extract text data from request
/// fn index(body: String) -> String {
/// format!("Body {}!", body)
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html").route(
/// web::get()
/// // limit size of the payload
/// .data(String::configure(|cfg| {
/// cfg.limit(4096)
/// }))
/// // register handler
/// .to(index)
/// ));
/// }
/// ```
pub fn data<T: 'static>(mut self, data: T) -> Self {
if self.data.is_none() {
self.data = Some(Extensions::new());
}
self.data.as_mut().unwrap().insert(RouteData::new(data));
self self
} }
} }

View File

@@ -322,6 +322,7 @@ where
default: self.default.clone(), default: self.default.clone(),
services: Rc::new( services: Rc::new(
cfg.into_services() cfg.into_services()
.1
.into_iter() .into_iter()
.map(|(mut rdef, srv, guards, nested)| { .map(|(mut rdef, srv, guards, nested)| {
rmap.add(&mut rdef, nested); rmap.add(&mut rdef, nested);

View File

@@ -1,4 +1,5 @@
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
use std::rc::Rc;
use std::{fmt, net}; use std::{fmt, net};
use actix_http::body::{Body, MessageBody, ResponseBody}; use actix_http::body::{Body, MessageBody, ResponseBody};
@@ -180,12 +181,18 @@ impl ServiceRequest {
/// Get an application data stored with `App::data()` method during /// Get an application data stored with `App::data()` method during
/// application configuration. /// application configuration.
pub fn app_data<T: 'static>(&self) -> Option<Data<T>> { pub fn app_data<T: 'static>(&self) -> Option<Data<T>> {
if let Some(st) = self.req.app_config().extensions().get::<Data<T>>() { if let Some(st) = self.req.0.app_data.get::<Data<T>>() {
Some(st.clone()) Some(st.clone())
} else { } else {
None None
} }
} }
#[doc(hidden)]
/// Set new app data container
pub fn set_data_container(&mut self, extensions: Rc<Extensions>) {
Rc::get_mut(&mut self.req.0).unwrap().app_data = extensions;
}
} }
impl Resource<Url> for ServiceRequest { impl Resource<Url> for ServiceRequest {

View File

@@ -2,27 +2,24 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use actix_http::cookie::Cookie;
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue}; use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version}; use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
use actix_http::test::TestRequest as HttpTestRequest; use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{Extensions, Request}; use actix_http::{cookie::Cookie, Extensions, Request};
use actix_router::{Path, ResourceDef, Url}; use actix_router::{Path, ResourceDef, Url};
use actix_rt::Runtime; use actix_rt::Runtime;
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::{FnService, IntoNewService, NewService, Service}; use actix_service::{FnService, IntoNewService, NewService, Service};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::{ use futures::future::{lazy, ok, Future, IntoFuture};
future::{lazy, ok, Future}, use futures::Stream;
stream::Stream,
};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde_json; use serde_json;
pub use actix_http::test::TestBuffer; pub use actix_http::test::TestBuffer;
use crate::config::{AppConfig, AppConfigInner}; use crate::config::{AppConfig, AppConfigInner};
use crate::data::{Data, RouteData}; use crate::data::Data;
use crate::dev::{Body, MessageBody, Payload}; use crate::dev::{Body, MessageBody, Payload};
use crate::request::HttpRequestPool; use crate::request::HttpRequestPool;
use crate::rmap::ResourceMap; use crate::rmap::ResourceMap;
@@ -30,11 +27,25 @@ use crate::service::{ServiceRequest, ServiceResponse};
use crate::{Error, HttpRequest, HttpResponse}; use crate::{Error, HttpRequest, HttpResponse};
thread_local! { thread_local! {
static RT: RefCell<Runtime> = { static RT: RefCell<Inner> = {
RefCell::new(Runtime::new().unwrap()) RefCell::new(Inner(Some(Runtime::new().unwrap())))
}; };
} }
struct Inner(Option<Runtime>);
impl Inner {
fn get_mut(&mut self) -> &mut Runtime {
self.0.as_mut().unwrap()
}
}
impl Drop for Inner {
fn drop(&mut self) {
std::mem::forget(self.0.take().unwrap())
}
}
/// Runs the provided future, blocking the current thread until the future /// Runs the provided future, blocking the current thread until the future
/// completes. /// completes.
/// ///
@@ -47,11 +58,30 @@ thread_local! {
/// This function panics on nested call. /// This function panics on nested call.
pub fn block_on<F>(f: F) -> Result<F::Item, F::Error> pub fn block_on<F>(f: F) -> Result<F::Item, F::Error>
where where
F: Future, F: IntoFuture,
{ {
RT.with(move |rt| rt.borrow_mut().block_on(f)) RT.with(move |rt| rt.borrow_mut().get_mut().block_on(f.into_future()))
} }
/// Runs the provided function, blocking the current thread until the resul
/// future completes.
///
/// This function can be used to synchronously block the current thread
/// until the provided `future` has resolved either successfully or with an
/// error. The result of the future is then returned from this function
/// call.
///
/// Note that this function is intended to be used only for testing purpose.
/// This function panics on nested call.
pub fn block_fn<F, R>(f: F) -> Result<R::Item, R::Error>
where
F: FnOnce() -> R,
R: IntoFuture,
{
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f())))
}
#[doc(hidden)]
/// Runs the provided function, with runtime enabled. /// Runs the provided function, with runtime enabled.
/// ///
/// Note that this function is intended to be used only for testing purpose. /// Note that this function is intended to be used only for testing purpose.
@@ -60,7 +90,11 @@ pub fn run_on<F, R>(f: F) -> R
where where
F: FnOnce() -> R, F: FnOnce() -> R,
{ {
RT.with(move |rt| rt.borrow_mut().block_on(lazy(|| Ok::<_, ()>(f())))) RT.with(move |rt| {
rt.borrow_mut()
.get_mut()
.block_on(lazy(|| Ok::<_, ()>(f())))
})
.unwrap() .unwrap()
} }
@@ -295,12 +329,11 @@ where
/// For unit testing, actix provides a request builder type and a simple handler runner. TestRequest implements a builder-like pattern. /// For unit testing, actix provides a request builder type and a simple handler runner. TestRequest implements a builder-like pattern.
/// You can generate various types of request via TestRequest's methods: /// You can generate various types of request via TestRequest's methods:
/// * `TestRequest::to_request` creates `actix_http::Request` instance. /// * `TestRequest::to_request` creates `actix_http::Request` instance.
/// * `TestRequest::to_service` creates `ServiceRequest` instance, which is used for testing middlewares and chain adapters. /// * `TestRequest::to_srv_request` creates `ServiceRequest` instance, which is used for testing middlewares and chain adapters.
/// * `TestRequest::to_from` creates `ServiceFromRequest` instance, which is used for testing extractors. /// * `TestRequest::to_srv_response` creates `ServiceResponse` instance.
/// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers. /// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
/// ///
/// ```rust /// ```rust
/// # use futures::IntoFuture;
/// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage}; /// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage};
/// use actix_web::http::{header, StatusCode}; /// use actix_web::http::{header, StatusCode};
/// ///
@@ -317,11 +350,11 @@ where
/// let req = test::TestRequest::with_header("content-type", "text/plain") /// let req = test::TestRequest::with_header("content-type", "text/plain")
/// .to_http_request(); /// .to_http_request();
/// ///
/// let resp = test::block_on(index(req).into_future()).unwrap(); /// let resp = test::block_on(index(req)).unwrap();
/// assert_eq!(resp.status(), StatusCode::OK); /// assert_eq!(resp.status(), StatusCode::OK);
/// ///
/// let req = test::TestRequest::default().to_http_request(); /// let req = test::TestRequest::default().to_http_request();
/// let resp = test::block_on(index(req).into_future()).unwrap(); /// let resp = test::block_on(index(req)).unwrap();
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST); /// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// } /// }
/// ``` /// ```
@@ -329,8 +362,8 @@ pub struct TestRequest {
req: HttpTestRequest, req: HttpTestRequest,
rmap: ResourceMap, rmap: ResourceMap,
config: AppConfigInner, config: AppConfigInner,
route_data: Extensions,
path: Path<Url>, path: Path<Url>,
app_data: Extensions,
} }
impl Default for TestRequest { impl Default for TestRequest {
@@ -339,8 +372,8 @@ impl Default for TestRequest {
req: HttpTestRequest::default(), req: HttpTestRequest::default(),
rmap: ResourceMap::new(ResourceDef::new("")), rmap: ResourceMap::new(ResourceDef::new("")),
config: AppConfigInner::default(), config: AppConfigInner::default(),
route_data: Extensions::new(),
path: Path::new(Url::new(Uri::default())), path: Path::new(Url::new(Uri::default())),
app_data: Extensions::new(),
} }
} }
} }
@@ -386,6 +419,11 @@ impl TestRequest {
TestRequest::default().method(Method::PATCH) TestRequest::default().method(Method::PATCH)
} }
/// Create TestRequest and set method to `Method::DELETE`
pub fn delete() -> TestRequest {
TestRequest::default().method(Method::DELETE)
}
/// Set HTTP version of this request /// Set HTTP version of this request
pub fn version(mut self, ver: Version) -> Self { pub fn version(mut self, ver: Version) -> Self {
self.req.version(ver); self.req.version(ver);
@@ -440,15 +478,8 @@ impl TestRequest {
/// Set application data. This is equivalent of `App::data()` method /// Set application data. This is equivalent of `App::data()` method
/// for testing purpose. /// for testing purpose.
pub fn app_data<T: 'static>(self, data: T) -> Self { pub fn data<T: 'static>(mut self, data: T) -> Self {
self.config.extensions.borrow_mut().insert(Data::new(data)); self.app_data.insert(Data::new(data));
self
}
/// Set route data. This is equivalent of `Route::data()` method
/// for testing purpose.
pub fn route_data<T: 'static>(mut self, data: T) -> Self {
self.route_data.insert(RouteData::new(data));
self self
} }
@@ -474,6 +505,7 @@ impl TestRequest {
head, head,
Rc::new(self.rmap), Rc::new(self.rmap),
AppConfig::new(self.config), AppConfig::new(self.config),
Rc::new(self.app_data),
HttpRequestPool::create(), HttpRequestPool::create(),
); );
@@ -490,15 +522,14 @@ impl TestRequest {
let (head, _) = self.req.finish().into_parts(); let (head, _) = self.req.finish().into_parts();
self.path.get_mut().update(&head.uri); self.path.get_mut().update(&head.uri);
let mut req = HttpRequest::new( HttpRequest::new(
self.path, self.path,
head, head,
Rc::new(self.rmap), Rc::new(self.rmap),
AppConfig::new(self.config), AppConfig::new(self.config),
Rc::new(self.app_data),
HttpRequestPool::create(), HttpRequestPool::create(),
); )
req.set_route_data(Some(Rc::new(self.route_data)));
req
} }
/// Complete request creation and generate `HttpRequest` and `Payload` instances /// Complete request creation and generate `HttpRequest` and `Payload` instances
@@ -506,14 +537,15 @@ impl TestRequest {
let (head, payload) = self.req.finish().into_parts(); let (head, payload) = self.req.finish().into_parts();
self.path.get_mut().update(&head.uri); self.path.get_mut().update(&head.uri);
let mut req = HttpRequest::new( let req = HttpRequest::new(
self.path, self.path,
head, head,
Rc::new(self.rmap), Rc::new(self.rmap),
AppConfig::new(self.config), AppConfig::new(self.config),
Rc::new(self.app_data),
HttpRequestPool::create(), HttpRequestPool::create(),
); );
req.set_route_data(Some(Rc::new(self.route_data)));
(req, payload) (req, payload)
} }
} }
@@ -532,15 +564,20 @@ mod tests {
.version(Version::HTTP_2) .version(Version::HTTP_2)
.set(header::Date(SystemTime::now().into())) .set(header::Date(SystemTime::now().into()))
.param("test", "123") .param("test", "123")
.app_data(10u32) .data(10u32)
.to_http_request(); .to_http_request();
assert!(req.headers().contains_key(header::CONTENT_TYPE)); assert!(req.headers().contains_key(header::CONTENT_TYPE));
assert!(req.headers().contains_key(header::DATE)); assert!(req.headers().contains_key(header::DATE));
assert_eq!(&req.match_info()["test"], "123"); assert_eq!(&req.match_info()["test"], "123");
assert_eq!(req.version(), Version::HTTP_2); assert_eq!(req.version(), Version::HTTP_2);
let data = req.app_data::<u32>().unwrap(); let data = req.get_app_data::<u32>().unwrap();
assert!(req.get_app_data::<u64>().is_none());
assert_eq!(*data, 10); assert_eq!(*data, 10);
assert_eq!(*data.get_ref(), 10); assert_eq!(*data.get_ref(), 10);
assert!(req.app_data::<u64>().is_none());
let data = req.app_data::<u32>().unwrap();
assert_eq!(*data, 10);
} }
#[test] #[test]
@@ -549,7 +586,8 @@ mod tests {
App::new().service( App::new().service(
web::resource("/index.html") web::resource("/index.html")
.route(web::put().to(|| HttpResponse::Ok().body("put!"))) .route(web::put().to(|| HttpResponse::Ok().body("put!")))
.route(web::patch().to(|| HttpResponse::Ok().body("patch!"))), .route(web::patch().to(|| HttpResponse::Ok().body("patch!")))
.route(web::delete().to(|| HttpResponse::Ok().body("delete!"))),
), ),
); );
@@ -568,6 +606,10 @@ mod tests {
let result = read_response(&mut app, patch_req); let result = read_response(&mut app, patch_req);
assert_eq!(result, Bytes::from_static(b"patch!")); assert_eq!(result, Bytes::from_static(b"patch!"));
let delete_req = TestRequest::delete().uri("/index.html").to_request();
let result = read_response(&mut app, delete_req);
assert_eq!(result, Bytes::from_static(b"delete!"));
} }
#[test] #[test]
@@ -613,4 +655,24 @@ mod tests {
let result: Person = read_response_json(&mut app, req); let result: Person = read_response_json(&mut app, req);
assert_eq!(&result.id, "12345"); assert_eq!(&result.id, "12345");
} }
#[test]
fn test_async_with_block() {
fn async_with_block() -> impl Future<Item = HttpResponse, Error = Error> {
web::block(move || Some(4).ok_or("wrong")).then(|res| match res {
Ok(value) => HttpResponse::Ok()
.content_type("text/plain")
.body(format!("Async with block value: {}", value)),
Err(_) => panic!("Unexpected"),
})
}
let mut app = init_service(
App::new().service(web::resource("/index.html").to_async(async_with_block)),
);
let req = TestRequest::post().uri("/index.html").to_request();
let res = block_fn(|| app.call(req)).unwrap();
assert!(res.status().is_success());
}
} }

View File

@@ -81,7 +81,7 @@ where
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let req2 = req.clone(); let req2 = req.clone();
let (limit, err) = req let (limit, err) = req
.route_data::<FormConfig>() .app_data::<FormConfig>()
.map(|c| (c.limit, c.ehandler.clone())) .map(|c| (c.limit, c.ehandler.clone()))
.unwrap_or((16384, None)); .unwrap_or((16384, None));
@@ -132,12 +132,11 @@ impl<T: fmt::Display> fmt::Display for Form<T> {
/// fn main() { /// fn main() {
/// let app = App::new().service( /// let app = App::new().service(
/// web::resource("/index.html") /// web::resource("/index.html")
/// .route(web::get()
/// // change `Form` extractor configuration /// // change `Form` extractor configuration
/// .data( /// .data(
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097)) /// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
/// ) /// )
/// .to(index)) /// .route(web::get().to(index))
/// ); /// );
/// } /// }
/// ``` /// ```

View File

@@ -176,7 +176,7 @@ where
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let req2 = req.clone(); let req2 = req.clone();
let (limit, err) = req let (limit, err) = req
.route_data::<JsonConfig>() .app_data::<JsonConfig>()
.map(|c| (c.limit, c.ehandler.clone())) .map(|c| (c.limit, c.ehandler.clone()))
.unwrap_or((32768, None)); .unwrap_or((32768, None));
@@ -220,8 +220,7 @@ where
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().service( /// let app = App::new().service(
/// web::resource("/index.html").route( /// web::resource("/index.html").data(
/// web::post().data(
/// // change json extractor configuration /// // change json extractor configuration
/// web::Json::<Info>::configure(|cfg| { /// web::Json::<Info>::configure(|cfg| {
/// cfg.limit(4096) /// cfg.limit(4096)
@@ -230,7 +229,7 @@ where
/// err, HttpResponse::Conflict().finish()).into() /// err, HttpResponse::Conflict().finish()).into()
/// }) /// })
/// })) /// }))
/// .to(index)) /// .route(web::post().to(index))
/// ); /// );
/// } /// }
/// ``` /// ```
@@ -431,7 +430,7 @@ mod tests {
header::HeaderValue::from_static("16"), header::HeaderValue::from_static("16"),
) )
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.route_data(JsonConfig::default().limit(10).error_handler(|err, _| { .data(JsonConfig::default().limit(10).error_handler(|err, _| {
let msg = MyObject { let msg = MyObject {
name: "invalid request".to_string(), name: "invalid request".to_string(),
}; };
@@ -483,7 +482,7 @@ mod tests {
header::HeaderValue::from_static("16"), header::HeaderValue::from_static("16"),
) )
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.route_data(JsonConfig::default().limit(10)) .data(JsonConfig::default().limit(10))
.to_http_parts(); .to_http_parts();
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl)); let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
@@ -500,7 +499,7 @@ mod tests {
header::HeaderValue::from_static("16"), header::HeaderValue::from_static("16"),
) )
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.route_data( .data(
JsonConfig::default() JsonConfig::default()
.limit(10) .limit(10)
.error_handler(|_, _| JsonPayloadError::ContentType.into()), .error_handler(|_, _| JsonPayloadError::ContentType.into()),

View File

@@ -130,7 +130,7 @@ impl FromRequest for Bytes {
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
let mut tmp; let mut tmp;
let cfg = if let Some(cfg) = req.route_data::<PayloadConfig>() { let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() {
cfg cfg
} else { } else {
tmp = PayloadConfig::default(); tmp = PayloadConfig::default();
@@ -167,12 +167,11 @@ impl FromRequest for Bytes {
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().service( /// let app = App::new().service(
/// web::resource("/index.html").route( /// web::resource("/index.html")
/// web::get()
/// .data(String::configure(|cfg| { // <- limit size of the payload /// .data(String::configure(|cfg| { // <- limit size of the payload
/// cfg.limit(4096) /// cfg.limit(4096)
/// })) /// }))
/// .to(index)) // <- register handler with extractor params /// .route(web::get().to(index)) // <- register handler with extractor params
/// ); /// );
/// } /// }
/// ``` /// ```
@@ -185,7 +184,7 @@ impl FromRequest for String {
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
let mut tmp; let mut tmp;
let cfg = if let Some(cfg) = req.route_data::<PayloadConfig>() { let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() {
cfg cfg
} else { } else {
tmp = PayloadConfig::default(); tmp = PayloadConfig::default();

View File

@@ -15,7 +15,7 @@ use crate::scope::Scope;
use crate::service::WebService; use crate::service::WebService;
pub use crate::config::ServiceConfig; pub use crate::config::ServiceConfig;
pub use crate::data::{Data, RouteData}; pub use crate::data::Data;
pub use crate::request::HttpRequest; pub use crate::request::HttpRequest;
pub use crate::types::*; pub use crate::types::*;

View File

@@ -1 +1,9 @@
# Actix http test server [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-http-test)](https://crates.io/crates/actix-http-test) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Actix http test server [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-http-test)](https://crates.io/crates/actix-http-test) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [User Guide](https://actix.rs/docs/)
* [API Documentation](https://docs.rs/actix-http-test/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-http-test](https://crates.io/crates/actix-http-test)
* Minimum supported Rust version: 1.33 or later