mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-06 19:00:18 +02:00
Compare commits
47 Commits
http-v0.1.
...
web-v1.0.0
Author | SHA1 | Date | |
---|---|---|---|
1ca58e876b | |||
e9cbcbaf03 | |||
07c9eec803 | |||
beae9ca0f7 | |||
07b9707ca1 | |||
45c05978b0 | |||
df08baf67f | |||
4066375737 | |||
a77b0b054a | |||
a17ff492a1 | |||
33b4c05557 | |||
005c055a7f | |||
3d1af19080 | |||
fa78da8156 | |||
01cfcf3b75 | |||
7ef4f5ac0b | |||
fc19ce41c4 | |||
6e00eef63a | |||
337c2febe3 | |||
f27beab016 | |||
4f1c6d1bb7 | |||
6b34909537 | |||
87284f0951 | |||
24bd5b1344 | |||
94a0d1a6bc | |||
f4e1205cbb | |||
d2c1791067 | |||
f4b4875cb1 | |||
29a841529f | |||
b51b5b763c | |||
8db6b48a76 | |||
ffd2c04cd3 | |||
70a4c36496 | |||
cba78e06ae | |||
3b3dbb4f40 | |||
7300002226 | |||
5426413cb6 | |||
2bc937f6c3 | |||
60fa0d5427 | |||
f429d3319f | |||
2e19f572ee | |||
64f603b076 | |||
679d1cd513 | |||
42644dac3f | |||
898ef57080 | |||
9702b2d88e | |||
d2b0afd859 |
53
CHANGES.md
53
CHANGES.md
@ -1,16 +1,67 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.0-beta.4] - 2019-05-12
|
||||||
|
|
||||||
|
### Add
|
||||||
|
|
||||||
|
* Allow to set/override app data on scope level
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
* `App::configure` take an `FnOnce` instead of `Fn`
|
||||||
|
|
||||||
|
* Upgrade actix-net crates
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-beta.3] - 2019-05-04
|
||||||
|
|
||||||
### Added
|
### 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
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add raw services support via `web::service()`
|
||||||
|
|
||||||
* Add helper functions for reading response body `test::read_body()`
|
* Add helper functions for reading response body `test::read_body()`
|
||||||
|
|
||||||
* Added support for `remainder match` (i.e "/path/{tail}*")
|
* Add support for `remainder match` (i.e "/path/{tail}*")
|
||||||
|
|
||||||
|
* Extend `Responder` trait, allow to override status code and headers.
|
||||||
|
|
||||||
|
* Store visit and login timestamp in the identity cookie #502
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
* `.to_async()` handler can return `Responder` type #792
|
* `.to_async()` handler can return `Responder` type #792
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix async web::Data factory handling
|
||||||
|
|
||||||
|
|
||||||
## [1.0.0-beta.1] - 2019-04-20
|
## [1.0.0-beta.1] - 2019-04-20
|
||||||
|
|
||||||
|
24
Cargo.toml
24
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web"
|
name = "actix-web"
|
||||||
version = "1.0.0-beta.1"
|
version = "1.0.0-beta.4"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -66,26 +66,27 @@ rust-tls = ["rustls", "actix-server/rust-tls"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.0"
|
||||||
actix-utils = "0.3.4"
|
actix-utils = "0.4.0"
|
||||||
actix-router = "0.1.3"
|
actix-router = "0.1.3"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-web-codegen = "0.1.0-beta.1"
|
actix-web-codegen = "0.1.0-beta.1"
|
||||||
actix-http = { version = "0.1.1", features=["fail"] }
|
actix-http = { version = "0.2.0", features=["fail"] }
|
||||||
actix-server = "0.4.3"
|
actix-server = "0.5.0"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.1"
|
||||||
actix-threadpool = "0.1.0"
|
actix-threadpool = "0.1.0"
|
||||||
awc = { version = "0.1.1", optional = true }
|
actix = { version = "0.8.1", features=["http"], optional = true }
|
||||||
|
awc = { version = "0.2.0", optional = true }
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
encoding = "0.2"
|
encoding = "0.2"
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
hashbrown = "0.2.2"
|
hashbrown = "0.3.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
net2 = "0.2.33"
|
net2 = "0.2.33"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.8"
|
||||||
regex = "1.0"
|
regex = "1.0"
|
||||||
serde = { version = "1.0", features=["derive"] }
|
serde = { version = "1.0", features=["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
@ -98,9 +99,9 @@ openssl = { version="0.10", optional = true }
|
|||||||
rustls = { version = "^0.15", optional = true }
|
rustls = { version = "^0.15", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-http = { version = "0.1.1", features=["ssl", "brotli", "flate2-zlib"] }
|
actix-http = { version = "0.2.0", features=["ssl", "brotli", "flate2-zlib"] }
|
||||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-files = { version = "0.1.0-beta.1" }
|
actix-files = { version = "0.1.0-betsa.1" }
|
||||||
rand = "0.6"
|
rand = "0.6"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
@ -121,4 +122,5 @@ actix-web-codegen = { path = "actix-web-codegen" }
|
|||||||
actix-web-actors = { path = "actix-web-actors" }
|
actix-web-actors = { path = "actix-web-actors" }
|
||||||
actix-session = { path = "actix-session" }
|
actix-session = { path = "actix-session" }
|
||||||
actix-files = { path = "actix-files" }
|
actix-files = { path = "actix-files" }
|
||||||
|
actix-multipart = { path = "actix-multipart" }
|
||||||
awc = { path = "awc" }
|
awc = { path = "awc" }
|
||||||
|
33
MIGRATION.md
33
MIGRATION.md
@ -92,6 +92,36 @@
|
|||||||
App.new().service(web::resource("/welcome").to(welcome))
|
App.new().service(web::resource("/welcome").to(welcome))
|
||||||
```
|
```
|
||||||
|
|
||||||
|
* `HttpRequest` does not provide access to request's payload stream.
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn index(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||||
|
req
|
||||||
|
.payload()
|
||||||
|
.from_err()
|
||||||
|
.fold((), |_, chunk| {
|
||||||
|
...
|
||||||
|
})
|
||||||
|
.map(|_| HttpResponse::Ok().finish())
|
||||||
|
.responder()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
use `Payload` extractor
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn index(stream: web::Payload) -> impl Future<Item=HttpResponse, Error=Error> {
|
||||||
|
stream
|
||||||
|
.from_err()
|
||||||
|
.fold((), |_, chunk| {
|
||||||
|
...
|
||||||
|
})
|
||||||
|
.map(|_| HttpResponse::Ok().finish())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
* `State` is now `Data`. You register Data during the App initialization process
|
* `State` is now `Data`. You register Data during the App initialization process
|
||||||
and then access it from handlers either using a Data extractor or using
|
and then access it from handlers either using a Data extractor or using
|
||||||
HttpRequest's api.
|
HttpRequest's api.
|
||||||
@ -164,7 +194,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 +203,7 @@
|
|||||||
...
|
...
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
use
|
use
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-files"
|
name = "actix-files"
|
||||||
version = "0.1.0-beta.1"
|
version = "0.1.0-betsa.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Static files support for actix web."
|
description = "Static files support for actix web."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -19,7 +19,7 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-beta.1"
|
actix-web = "1.0.0-beta.1"
|
||||||
actix-service = "0.3.4"
|
actix-service = "0.4.0"
|
||||||
bitflags = "1"
|
bitflags = "1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
|
@ -1 +1,9 @@
|
|||||||
# Static files support for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-files) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Static files support for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-files) [](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
|
||||||
|
@ -334,6 +334,7 @@ impl Files {
|
|||||||
where
|
where
|
||||||
F: IntoNewService<U>,
|
F: IntoNewService<U>,
|
||||||
U: NewService<
|
U: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -363,6 +364,7 @@ impl HttpServiceFactory for Files {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for Files {
|
impl NewService for Files {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
@ -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(())
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-framed"
|
name = "actix-framed"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix framed app server"
|
description = "Actix framed app server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -21,17 +21,18 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.0"
|
||||||
actix-utils = "0.3.4"
|
actix-utils = "0.4.0"
|
||||||
actix-router = "0.1.2"
|
actix-router = "0.1.2"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-http = "0.1.0"
|
actix-http = "0.2.0"
|
||||||
|
actix-server-config = "0.1.1"
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
|
@ -1 +1,8 @@
|
|||||||
# Framed app for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-framed) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Framed app for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-framed) [](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
|
||||||
|
@ -1,5 +1,10 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
|
* Update dependencies
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0] - 2019-04-16
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
* Update tests
|
* Update tests
|
||||||
|
@ -4,6 +4,7 @@ use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
|||||||
use actix_http::h1::{Codec, SendResponse};
|
use actix_http::h1::{Codec, SendResponse};
|
||||||
use actix_http::{Error, Request, Response};
|
use actix_http::{Error, Request, Response};
|
||||||
use actix_router::{Path, Router, Url};
|
use actix_router::{Path, Router, Url};
|
||||||
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
use actix_utils::cloneable::CloneableService;
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
@ -49,6 +50,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
|||||||
where
|
where
|
||||||
U: HttpServiceFactory,
|
U: HttpServiceFactory,
|
||||||
U::Factory: NewService<
|
U::Factory: NewService<
|
||||||
|
Config = (),
|
||||||
Request = FramedRequest<T, S>,
|
Request = FramedRequest<T, S>,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -88,11 +90,12 @@ pub struct FramedAppFactory<T, S> {
|
|||||||
services: Rc<Vec<(String, BoxedHttpNewService<FramedRequest<T, S>>)>>,
|
services: Rc<Vec<(String, BoxedHttpNewService<FramedRequest<T, S>>)>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, C> NewService<C> for FramedAppFactory<T, S>
|
impl<T, S> NewService for FramedAppFactory<T, S>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
S: 'static,
|
S: 'static,
|
||||||
{
|
{
|
||||||
|
type Config = ServerConfig;
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -100,7 +103,7 @@ where
|
|||||||
type Service = CloneableService<FramedAppService<T, S>>;
|
type Service = CloneableService<FramedAppService<T, S>>;
|
||||||
type Future = CreateService<T, S>;
|
type Future = CreateService<T, S>;
|
||||||
|
|
||||||
fn new_service(&self, _: &C) -> Self::Future {
|
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||||
CreateService {
|
CreateService {
|
||||||
fut: self
|
fut: self
|
||||||
.services
|
.services
|
||||||
|
@ -13,6 +13,7 @@ pub(crate) type BoxedHttpService<Req> = Box<
|
|||||||
|
|
||||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||||
NewService<
|
NewService<
|
||||||
|
Config = (),
|
||||||
Request = Req,
|
Request = Req,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -39,12 +40,13 @@ where
|
|||||||
|
|
||||||
impl<T> NewService for HttpNewService<T>
|
impl<T> NewService for HttpNewService<T>
|
||||||
where
|
where
|
||||||
T: NewService<Response = (), Error = Error>,
|
T: NewService<Config = (), Response = (), Error = Error>,
|
||||||
T::Request: 'static,
|
T::Request: 'static,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
|
type Config = ();
|
||||||
type Request = T::Request;
|
type Request = T::Request;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
@ -106,6 +106,7 @@ where
|
|||||||
R::Future: 'static,
|
R::Future: 'static,
|
||||||
R::Error: fmt::Display,
|
R::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
type Config = ();
|
||||||
type Request = FramedRequest<Io, S>;
|
type Request = FramedRequest<Io, S>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
@ -12,22 +12,23 @@ use futures::{Async, Future, IntoFuture, Poll, Sink};
|
|||||||
|
|
||||||
/// Service that verifies incoming request if it is valid websocket
|
/// Service that verifies incoming request if it is valid websocket
|
||||||
/// upgrade request. In case of error returns `HandshakeError`
|
/// upgrade request. In case of error returns `HandshakeError`
|
||||||
pub struct VerifyWebSockets<T> {
|
pub struct VerifyWebSockets<T, C> {
|
||||||
_t: PhantomData<T>,
|
_t: PhantomData<(T, C)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Default for VerifyWebSockets<T> {
|
impl<T, C> Default for VerifyWebSockets<T, C> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
VerifyWebSockets { _t: PhantomData }
|
VerifyWebSockets { _t: PhantomData }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
impl<T, C> NewService for VerifyWebSockets<T, C> {
|
||||||
|
type Config = C;
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = (Request, Framed<T, Codec>);
|
type Response = (Request, Framed<T, Codec>);
|
||||||
type Error = (HandshakeError, Framed<T, Codec>);
|
type Error = (HandshakeError, Framed<T, Codec>);
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Service = VerifyWebSockets<T>;
|
type Service = VerifyWebSockets<T, C>;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &C) -> Self::Future {
|
fn new_service(&self, _: &C) -> Self::Future {
|
||||||
@ -35,7 +36,7 @@ impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Service for VerifyWebSockets<T> {
|
impl<T, C> Service for VerifyWebSockets<T, C> {
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = (Request, Framed<T, Codec>);
|
type Response = (Request, Framed<T, Codec>);
|
||||||
type Error = (HandshakeError, Framed<T, Codec>);
|
type Error = (HandshakeError, Framed<T, Codec>);
|
||||||
@ -54,9 +55,9 @@ impl<T> Service for VerifyWebSockets<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Send http/1 error response
|
/// Send http/1 error response
|
||||||
pub struct SendError<T, R, E>(PhantomData<(T, R, E)>);
|
pub struct SendError<T, R, E, C>(PhantomData<(T, R, E, C)>);
|
||||||
|
|
||||||
impl<T, R, E> Default for SendError<T, R, E>
|
impl<T, R, E, C> Default for SendError<T, R, E, C>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
E: ResponseError,
|
E: ResponseError,
|
||||||
@ -66,17 +67,18 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, R, E, C> NewService<C> for SendError<T, R, E>
|
impl<T, R, E, C> NewService for SendError<T, R, E, C>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
R: 'static,
|
R: 'static,
|
||||||
E: ResponseError + 'static,
|
E: ResponseError + 'static,
|
||||||
{
|
{
|
||||||
|
type Config = C;
|
||||||
type Request = Result<R, (E, Framed<T, Codec>)>;
|
type Request = Result<R, (E, Framed<T, Codec>)>;
|
||||||
type Response = R;
|
type Response = R;
|
||||||
type Error = (E, Framed<T, Codec>);
|
type Error = (E, Framed<T, Codec>);
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Service = SendError<T, R, E>;
|
type Service = SendError<T, R, E, C>;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &C) -> Self::Future {
|
fn new_service(&self, _: &C) -> Self::Future {
|
||||||
@ -84,7 +86,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, R, E> Service for SendError<T, R, E>
|
impl<T, R, E, C> Service for SendError<T, R, E, C>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
R: 'static,
|
R: 'static,
|
||||||
|
@ -1,5 +1,45 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Update actix-service to 0.4
|
||||||
|
|
||||||
|
* Expect and upgrade services accept `ServerConfig` config.
|
||||||
|
|
||||||
|
### Deleted
|
||||||
|
|
||||||
|
* `OneRequest` service
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.5] - 2019-05-04
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Clean up response extensions in response pool #817
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.4] - 2019-04-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to render h1 request headers in `Camel-Case`
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Read until eof for http/1.0 responses #771
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.3] - 2019-04-23
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix http client pool management
|
||||||
|
|
||||||
|
* Fix http client wait queue management #794
|
||||||
|
|
||||||
|
|
||||||
## [0.1.2] - 2019-04-23
|
## [0.1.2] - 2019-04-23
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http"
|
name = "actix-http"
|
||||||
version = "0.1.2"
|
version = "0.2.0"
|
||||||
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"
|
||||||
@ -44,10 +44,10 @@ fail = ["failure"]
|
|||||||
secure-cookies = ["ring"]
|
secure-cookies = ["ring"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.0"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-connect = "0.1.5"
|
actix-connect = "0.2.0"
|
||||||
actix-utils = "0.3.5"
|
actix-utils = "0.4.0"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.1"
|
||||||
actix-threadpool = "0.1.0"
|
actix-threadpool = "0.1.0"
|
||||||
|
|
||||||
@ -59,8 +59,8 @@ copyless = "0.1.2"
|
|||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
either = "1.5.2"
|
either = "1.5.2"
|
||||||
encoding = "0.2"
|
encoding = "0.2"
|
||||||
futures = "0.1"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.2.2"
|
hashbrown = "0.3.0"
|
||||||
h2 = "0.1.16"
|
h2 = "0.1.16"
|
||||||
http = "0.1.17"
|
http = "0.1.17"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
@ -97,9 +97,9 @@ chrono = "0.4.6"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
openssl = { version="0.10" }
|
openssl = { version="0.10" }
|
||||||
|
@ -29,7 +29,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
|
|||||||
|
|
||||||
impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>>
|
impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -48,13 +48,17 @@ where
|
|||||||
|
|
||||||
impl<T, S, X, U> HttpServiceBuilder<T, S, X, U>
|
impl<T, S, X, U> HttpServiceBuilder<T, S, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
U: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -101,7 +105,7 @@ where
|
|||||||
pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U>
|
pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U>
|
||||||
where
|
where
|
||||||
F: IntoNewService<X1>,
|
F: IntoNewService<X1>,
|
||||||
X1: NewService<Request = Request, Response = Request>,
|
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X1::Error: Into<Error>,
|
X1::Error: Into<Error>,
|
||||||
X1::InitError: fmt::Debug,
|
X1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -122,7 +126,11 @@ where
|
|||||||
pub fn upgrade<F, U1>(self, upgrade: F) -> HttpServiceBuilder<T, S, X, U1>
|
pub fn upgrade<F, U1>(self, upgrade: F) -> HttpServiceBuilder<T, S, X, U1>
|
||||||
where
|
where
|
||||||
F: IntoNewService<U1>,
|
F: IntoNewService<U1>,
|
||||||
U1: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
U1: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U1::Error: fmt::Display,
|
U1::Error: fmt::Display,
|
||||||
U1::InitError: fmt::Debug,
|
U1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -140,7 +148,7 @@ where
|
|||||||
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
F: IntoNewService<S, SrvConfig>,
|
F: IntoNewService<S>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -159,7 +167,7 @@ where
|
|||||||
pub fn h2<F, P, B>(self, service: F) -> H2Service<T, P, S, B>
|
pub fn h2<F, P, B>(self, service: F) -> H2Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
F: IntoNewService<S, SrvConfig>,
|
F: IntoNewService<S>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -177,7 +185,7 @@ where
|
|||||||
pub fn finish<F, P, B>(self, service: F) -> HttpService<T, P, S, B, X, U>
|
pub fn finish<F, P, B>(self, service: F) -> HttpService<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
F: IntoNewService<S, SrvConfig>,
|
F: IntoNewService<S>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
@ -114,7 +114,8 @@ where
|
|||||||
Request = TcpConnect<Uri>,
|
Request = TcpConnect<Uri>,
|
||||||
Response = TcpConnection<Uri, U>,
|
Response = TcpConnection<Uri, U>,
|
||||||
Error = actix_connect::ConnectError,
|
Error = actix_connect::ConnectError,
|
||||||
> + Clone,
|
> + Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
/// Connection timeout, i.e. max time to connect to remote host including dns name resolution.
|
/// Connection timeout, i.e. max time to connect to remote host including dns name resolution.
|
||||||
/// Set to 1 second by default.
|
/// Set to 1 second by default.
|
||||||
@ -284,7 +285,9 @@ mod connect_impl {
|
|||||||
pub(crate) struct InnerConnector<T, Io>
|
pub(crate) struct InnerConnector<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
||||||
}
|
}
|
||||||
@ -293,7 +296,8 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
InnerConnector {
|
InnerConnector {
|
||||||
@ -305,7 +309,9 @@ mod connect_impl {
|
|||||||
impl<T, Io> Service for InnerConnector<T, Io>
|
impl<T, Io> Service for InnerConnector<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
type Request = Connect;
|
type Request = Connect;
|
||||||
type Response = IoConnection<Io>;
|
type Response = IoConnection<Io>;
|
||||||
@ -356,9 +362,11 @@ mod connect_impl {
|
|||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
InnerConnector {
|
InnerConnector {
|
||||||
@ -372,8 +380,12 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
|
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
type Request = Connect;
|
type Request = Connect;
|
||||||
type Response = EitherConnection<Io1, Io2>;
|
type Response = EitherConnection<Io1, Io2>;
|
||||||
@ -409,7 +421,9 @@ mod connect_impl {
|
|||||||
pub(crate) struct InnerConnectorResponseA<T, Io1, Io2>
|
pub(crate) struct InnerConnectorResponseA<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
||||||
_t: PhantomData<Io2>,
|
_t: PhantomData<Io2>,
|
||||||
@ -417,7 +431,9 @@ mod connect_impl {
|
|||||||
|
|
||||||
impl<T, Io1, Io2> Future for InnerConnectorResponseA<T, Io1, Io2>
|
impl<T, Io1, Io2> Future for InnerConnectorResponseA<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
@ -435,7 +451,9 @@ mod connect_impl {
|
|||||||
pub(crate) struct InnerConnectorResponseB<T, Io1, Io2>
|
pub(crate) struct InnerConnectorResponseB<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
||||||
_t: PhantomData<Io1>,
|
_t: PhantomData<Io1>,
|
||||||
@ -443,7 +461,9 @@ mod connect_impl {
|
|||||||
|
|
||||||
impl<T, Io1, Io2> Future for InnerConnectorResponseB<T, Io1, Io2>
|
impl<T, Io1, Io2> Future for InnerConnectorResponseB<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
|
@ -274,7 +274,7 @@ impl<Io: ConnectionLifetime> Stream for PlStream<Io> {
|
|||||||
Ok(Async::Ready(Some(chunk)))
|
Ok(Async::Ready(Some(chunk)))
|
||||||
} else {
|
} else {
|
||||||
let framed = self.framed.take().unwrap();
|
let framed = self.framed.take().unwrap();
|
||||||
let force_close = framed.get_codec().keepalive();
|
let force_close = !framed.get_codec().keepalive();
|
||||||
release_connection(framed, force_close);
|
release_connection(framed, force_close);
|
||||||
Ok(Async::Ready(None))
|
Ok(Async::Ready(None))
|
||||||
}
|
}
|
||||||
|
@ -49,7 +49,9 @@ pub(crate) struct ConnectionPool<T, Io: AsyncRead + AsyncWrite + 'static>(
|
|||||||
impl<T, Io> ConnectionPool<T, Io>
|
impl<T, Io> ConnectionPool<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
connector: T,
|
connector: T,
|
||||||
@ -69,7 +71,7 @@ where
|
|||||||
waiters: Slab::new(),
|
waiters: Slab::new(),
|
||||||
waiters_queue: IndexSet::new(),
|
waiters_queue: IndexSet::new(),
|
||||||
available: HashMap::new(),
|
available: HashMap::new(),
|
||||||
task: AtomicTask::new(),
|
task: None,
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -88,7 +90,9 @@ where
|
|||||||
impl<T, Io> Service for ConnectionPool<T, Io>
|
impl<T, Io> Service for ConnectionPool<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
type Request = Connect;
|
type Request = Connect;
|
||||||
type Response = IoConnection<Io>;
|
type Response = IoConnection<Io>;
|
||||||
@ -131,7 +135,17 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
// connection is not available, wait
|
// connection is not available, wait
|
||||||
let (rx, token) = self.1.as_ref().borrow_mut().wait_for(req);
|
let (rx, token, support) = self.1.as_ref().borrow_mut().wait_for(req);
|
||||||
|
|
||||||
|
// start support future
|
||||||
|
if !support {
|
||||||
|
self.1.as_ref().borrow_mut().task = Some(AtomicTask::new());
|
||||||
|
tokio_current_thread::spawn(ConnectorPoolSupport {
|
||||||
|
connector: self.0.clone(),
|
||||||
|
inner: self.1.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
Either::B(Either::A(WaitForConnection {
|
Either::B(Either::A(WaitForConnection {
|
||||||
rx,
|
rx,
|
||||||
key,
|
key,
|
||||||
@ -245,7 +259,7 @@ where
|
|||||||
Ok(Async::Ready(IoConnection::new(
|
Ok(Async::Ready(IoConnection::new(
|
||||||
ConnectionType::H2(snd),
|
ConnectionType::H2(snd),
|
||||||
Instant::now(),
|
Instant::now(),
|
||||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
@ -256,12 +270,11 @@ where
|
|||||||
match self.fut.poll() {
|
match self.fut.poll() {
|
||||||
Err(err) => Err(err),
|
Err(err) => Err(err),
|
||||||
Ok(Async::Ready((io, proto))) => {
|
Ok(Async::Ready((io, proto))) => {
|
||||||
let _ = self.inner.take();
|
|
||||||
if proto == Protocol::Http1 {
|
if proto == Protocol::Http1 {
|
||||||
Ok(Async::Ready(IoConnection::new(
|
Ok(Async::Ready(IoConnection::new(
|
||||||
ConnectionType::H1(io),
|
ConnectionType::H1(io),
|
||||||
Instant::now(),
|
Instant::now(),
|
||||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||||
)))
|
)))
|
||||||
} else {
|
} else {
|
||||||
self.h2 = Some(handshake(io));
|
self.h2 = Some(handshake(io));
|
||||||
@ -279,7 +292,6 @@ enum Acquire<T> {
|
|||||||
NotAvailable,
|
NotAvailable,
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[derive(Debug)]
|
|
||||||
struct AvailableConnection<Io> {
|
struct AvailableConnection<Io> {
|
||||||
io: ConnectionType<Io>,
|
io: ConnectionType<Io>,
|
||||||
used: Instant,
|
used: Instant,
|
||||||
@ -298,7 +310,7 @@ pub(crate) struct Inner<Io> {
|
|||||||
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||||
)>,
|
)>,
|
||||||
waiters_queue: IndexSet<(Key, usize)>,
|
waiters_queue: IndexSet<(Key, usize)>,
|
||||||
task: AtomicTask,
|
task: Option<AtomicTask>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io> Inner<Io> {
|
impl<Io> Inner<Io> {
|
||||||
@ -314,18 +326,6 @@ impl<Io> Inner<Io> {
|
|||||||
self.waiters.remove(token);
|
self.waiters.remove(token);
|
||||||
self.waiters_queue.remove(&(key.clone(), token));
|
self.waiters_queue.remove(&(key.clone(), token));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
|
||||||
self.acquired -= 1;
|
|
||||||
self.available
|
|
||||||
.entry(key.clone())
|
|
||||||
.or_insert_with(VecDeque::new)
|
|
||||||
.push_back(AvailableConnection {
|
|
||||||
io,
|
|
||||||
created,
|
|
||||||
used: Instant::now(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io> Inner<Io>
|
impl<Io> Inner<Io>
|
||||||
@ -339,6 +339,7 @@ where
|
|||||||
) -> (
|
) -> (
|
||||||
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
||||||
usize,
|
usize,
|
||||||
|
bool,
|
||||||
) {
|
) {
|
||||||
let (tx, rx) = oneshot::channel();
|
let (tx, rx) = oneshot::channel();
|
||||||
|
|
||||||
@ -346,8 +347,9 @@ where
|
|||||||
let entry = self.waiters.vacant_entry();
|
let entry = self.waiters.vacant_entry();
|
||||||
let token = entry.key();
|
let token = entry.key();
|
||||||
entry.insert((connect, tx));
|
entry.insert((connect, tx));
|
||||||
assert!(!self.waiters_queue.insert((key, token)));
|
assert!(self.waiters_queue.insert((key, token)));
|
||||||
(rx, token)
|
|
||||||
|
(rx, token, self.task.is_some())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn acquire(&mut self, key: &Key) -> Acquire<Io> {
|
fn acquire(&mut self, key: &Key) -> Acquire<Io> {
|
||||||
@ -400,6 +402,19 @@ where
|
|||||||
Acquire::Available
|
Acquire::Available
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
||||||
|
self.acquired -= 1;
|
||||||
|
self.available
|
||||||
|
.entry(key.clone())
|
||||||
|
.or_insert_with(VecDeque::new)
|
||||||
|
.push_back(AvailableConnection {
|
||||||
|
io,
|
||||||
|
created,
|
||||||
|
used: Instant::now(),
|
||||||
|
});
|
||||||
|
self.check_availibility();
|
||||||
|
}
|
||||||
|
|
||||||
fn release_close(&mut self, io: ConnectionType<Io>) {
|
fn release_close(&mut self, io: ConnectionType<Io>) {
|
||||||
self.acquired -= 1;
|
self.acquired -= 1;
|
||||||
if let Some(timeout) = self.disconnect_timeout {
|
if let Some(timeout) = self.disconnect_timeout {
|
||||||
@ -407,11 +422,12 @@ where
|
|||||||
tokio_current_thread::spawn(CloseConnection::new(io, timeout))
|
tokio_current_thread::spawn(CloseConnection::new(io, timeout))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.check_availibility();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_availibility(&self) {
|
fn check_availibility(&self) {
|
||||||
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
||||||
self.task.notify()
|
self.task.as_ref().map(|t| t.notify());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -451,6 +467,147 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ConnectorPoolSupport<T, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
connector: T,
|
||||||
|
inner: Rc<RefCell<Inner<Io>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, Io> Future for ConnectorPoolSupport<T, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||||
|
T::Future: 'static,
|
||||||
|
{
|
||||||
|
type Item = ();
|
||||||
|
type Error = ();
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
let mut inner = self.inner.as_ref().borrow_mut();
|
||||||
|
inner.task.as_ref().unwrap().register();
|
||||||
|
|
||||||
|
// check waiters
|
||||||
|
loop {
|
||||||
|
let (key, token) = {
|
||||||
|
if let Some((key, token)) = inner.waiters_queue.get_index(0) {
|
||||||
|
(key.clone(), *token)
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match inner.acquire(&key) {
|
||||||
|
Acquire::NotAvailable => break,
|
||||||
|
Acquire::Acquired(io, created) => {
|
||||||
|
let (_, tx) = inner.waiters.remove(token);
|
||||||
|
if let Err(conn) = tx.send(Ok(IoConnection::new(
|
||||||
|
io,
|
||||||
|
created,
|
||||||
|
Some(Acquired(key.clone(), Some(self.inner.clone()))),
|
||||||
|
))) {
|
||||||
|
let (io, created) = conn.unwrap().into_inner();
|
||||||
|
inner.release_conn(&key, io, created);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Acquire::Available => {
|
||||||
|
let (connect, tx) = inner.waiters.remove(token);
|
||||||
|
OpenWaitingConnection::spawn(
|
||||||
|
key.clone(),
|
||||||
|
tx,
|
||||||
|
self.inner.clone(),
|
||||||
|
self.connector.call(connect),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = inner.waiters_queue.swap_remove_index(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Async::NotReady)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
fut: F,
|
||||||
|
key: Key,
|
||||||
|
h2: Option<Handshake<Io, Bytes>>,
|
||||||
|
rx: Option<oneshot::Sender<Result<IoConnection<Io>, ConnectError>>>,
|
||||||
|
inner: Option<Rc<RefCell<Inner<Io>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, Io> OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
F: Future<Item = (Io, Protocol), Error = ConnectError> + 'static,
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
fn spawn(
|
||||||
|
key: Key,
|
||||||
|
rx: oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||||
|
inner: Rc<RefCell<Inner<Io>>>,
|
||||||
|
fut: F,
|
||||||
|
) {
|
||||||
|
tokio_current_thread::spawn(OpenWaitingConnection {
|
||||||
|
key,
|
||||||
|
fut,
|
||||||
|
h2: None,
|
||||||
|
rx: Some(rx),
|
||||||
|
inner: Some(inner),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, Io> Drop for OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(inner) = self.inner.take() {
|
||||||
|
let mut inner = inner.as_ref().borrow_mut();
|
||||||
|
inner.release();
|
||||||
|
inner.check_availibility();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, Io> Future for OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
F: Future<Item = (Io, Protocol), Error = ConnectError>,
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
{
|
||||||
|
type Item = ();
|
||||||
|
type Error = ();
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
match self.fut.poll() {
|
||||||
|
Err(err) => {
|
||||||
|
let _ = self.inner.take();
|
||||||
|
if let Some(rx) = self.rx.take() {
|
||||||
|
let _ = rx.send(Err(err));
|
||||||
|
}
|
||||||
|
Err(())
|
||||||
|
}
|
||||||
|
Ok(Async::Ready((io, proto))) => {
|
||||||
|
if proto == Protocol::Http1 {
|
||||||
|
let rx = self.rx.take().unwrap();
|
||||||
|
let _ = rx.send(Ok(IoConnection::new(
|
||||||
|
ConnectionType::H1(io),
|
||||||
|
Instant::now(),
|
||||||
|
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||||
|
)));
|
||||||
|
Ok(Async::Ready(()))
|
||||||
|
} else {
|
||||||
|
self.h2 = Some(handshake(io));
|
||||||
|
self.poll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) struct Acquired<T>(Key, Option<Rc<RefCell<Inner<T>>>>);
|
pub(crate) struct Acquired<T>(Key, Option<Rc<RefCell<Inner<T>>>>);
|
||||||
|
|
||||||
impl<T> Acquired<T>
|
impl<T> Acquired<T>
|
||||||
|
@ -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`
|
||||||
|
@ -299,8 +299,14 @@ impl MessageType for ResponseHead {
|
|||||||
} else if src.len() >= MAX_BUFFER_SIZE {
|
} else if src.len() >= MAX_BUFFER_SIZE {
|
||||||
error!("MAX_BUFFER_SIZE unprocessed data reached, closing");
|
error!("MAX_BUFFER_SIZE unprocessed data reached, closing");
|
||||||
return Err(ParseError::TooLarge);
|
return Err(ParseError::TooLarge);
|
||||||
|
} else {
|
||||||
|
// for HTTP/1.0 read to eof and close connection
|
||||||
|
if msg.version == Version::HTTP_10 {
|
||||||
|
msg.set_connection_type(ConnectionType::Close);
|
||||||
|
PayloadType::Payload(PayloadDecoder::eof())
|
||||||
} else {
|
} else {
|
||||||
PayloadType::None
|
PayloadType::None
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Some((msg, decoder)))
|
Ok(Some((msg, decoder)))
|
||||||
@ -331,7 +337,7 @@ impl HeaderIndex {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
/// Http payload item
|
/// Http payload item
|
||||||
pub enum PayloadItem {
|
pub enum PayloadItem {
|
||||||
Chunk(Bytes),
|
Chunk(Bytes),
|
||||||
@ -1191,4 +1197,16 @@ mod tests {
|
|||||||
let msg = pl.decode(&mut buf).unwrap().unwrap();
|
let msg = pl.decode(&mut buf).unwrap().unwrap();
|
||||||
assert!(msg.eof());
|
assert!(msg.eof());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_response_http10_read_until_eof() {
|
||||||
|
let mut buf = BytesMut::from(&"HTTP/1.0 200 Ok\r\n\r\ntest data"[..]);
|
||||||
|
|
||||||
|
let mut reader = MessageDecoder::<ResponseHead>::default();
|
||||||
|
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
|
||||||
|
let mut pl = pl.unwrap();
|
||||||
|
|
||||||
|
let chunk = pl.decode(&mut buf).unwrap().unwrap();
|
||||||
|
assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"test data")));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -43,6 +43,10 @@ pub(crate) trait MessageType: Sized {
|
|||||||
|
|
||||||
fn headers(&self) -> &HeaderMap;
|
fn headers(&self) -> &HeaderMap;
|
||||||
|
|
||||||
|
fn camel_case(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
fn chunked(&self) -> bool;
|
fn chunked(&self) -> bool;
|
||||||
|
|
||||||
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()>;
|
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()>;
|
||||||
@ -57,6 +61,7 @@ pub(crate) trait MessageType: Sized {
|
|||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
let chunked = self.chunked();
|
let chunked = self.chunked();
|
||||||
let mut skip_len = length != BodySize::Stream;
|
let mut skip_len = length != BodySize::Stream;
|
||||||
|
let camel_case = self.camel_case();
|
||||||
|
|
||||||
// Content length
|
// Content length
|
||||||
if let Some(status) = self.status() {
|
if let Some(status) = self.status() {
|
||||||
@ -74,18 +79,30 @@ pub(crate) trait MessageType: Sized {
|
|||||||
match length {
|
match length {
|
||||||
BodySize::Stream => {
|
BodySize::Stream => {
|
||||||
if chunked {
|
if chunked {
|
||||||
|
if camel_case {
|
||||||
|
dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n")
|
||||||
|
} 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;
|
||||||
dst.put_slice(b"\r\n");
|
dst.put_slice(b"\r\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
BodySize::Empty => {
|
BodySize::Empty => {
|
||||||
|
if camel_case {
|
||||||
|
dst.put_slice(b"\r\nContent-Length: 0\r\n");
|
||||||
|
} else {
|
||||||
dst.put_slice(b"\r\ncontent-length: 0\r\n");
|
dst.put_slice(b"\r\ncontent-length: 0\r\n");
|
||||||
}
|
}
|
||||||
|
}
|
||||||
BodySize::Sized(len) => helpers::write_content_length(len, dst),
|
BodySize::Sized(len) => helpers::write_content_length(len, dst),
|
||||||
BodySize::Sized64(len) => {
|
BodySize::Sized64(len) => {
|
||||||
|
if camel_case {
|
||||||
|
dst.put_slice(b"\r\nContent-Length: ");
|
||||||
|
} else {
|
||||||
dst.put_slice(b"\r\ncontent-length: ");
|
dst.put_slice(b"\r\ncontent-length: ");
|
||||||
|
}
|
||||||
write!(dst.writer(), "{}\r\n", len)?;
|
write!(dst.writer(), "{}\r\n", len)?;
|
||||||
}
|
}
|
||||||
BodySize::None => dst.put_slice(b"\r\n"),
|
BodySize::None => dst.put_slice(b"\r\n"),
|
||||||
@ -95,11 +112,19 @@ pub(crate) trait MessageType: Sized {
|
|||||||
match ctype {
|
match ctype {
|
||||||
ConnectionType::Upgrade => dst.put_slice(b"connection: upgrade\r\n"),
|
ConnectionType::Upgrade => dst.put_slice(b"connection: upgrade\r\n"),
|
||||||
ConnectionType::KeepAlive if version < Version::HTTP_11 => {
|
ConnectionType::KeepAlive if version < Version::HTTP_11 => {
|
||||||
|
if camel_case {
|
||||||
|
dst.put_slice(b"Connection: keep-alive\r\n")
|
||||||
|
} else {
|
||||||
dst.put_slice(b"connection: keep-alive\r\n")
|
dst.put_slice(b"connection: keep-alive\r\n")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
ConnectionType::Close if version >= Version::HTTP_11 => {
|
ConnectionType::Close if version >= Version::HTTP_11 => {
|
||||||
|
if camel_case {
|
||||||
|
dst.put_slice(b"Connection: close\r\n")
|
||||||
|
} else {
|
||||||
dst.put_slice(b"connection: close\r\n")
|
dst.put_slice(b"connection: close\r\n")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,7 +158,12 @@ pub(crate) trait MessageType: Sized {
|
|||||||
buf = &mut *(dst.bytes_mut() as *mut _);
|
buf = &mut *(dst.bytes_mut() as *mut _);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// use upper Camel-Case
|
||||||
|
if camel_case {
|
||||||
|
write_camel_case(k, &mut buf[pos..pos + k.len()]);
|
||||||
|
} else {
|
||||||
buf[pos..pos + k.len()].copy_from_slice(k);
|
buf[pos..pos + k.len()].copy_from_slice(k);
|
||||||
|
}
|
||||||
pos += k.len();
|
pos += k.len();
|
||||||
buf[pos..pos + 2].copy_from_slice(b": ");
|
buf[pos..pos + 2].copy_from_slice(b": ");
|
||||||
pos += 2;
|
pos += 2;
|
||||||
@ -158,7 +188,12 @@ pub(crate) trait MessageType: Sized {
|
|||||||
buf = &mut *(dst.bytes_mut() as *mut _);
|
buf = &mut *(dst.bytes_mut() as *mut _);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// use upper Camel-Case
|
||||||
|
if camel_case {
|
||||||
|
write_camel_case(k, &mut buf[pos..pos + k.len()]);
|
||||||
|
} else {
|
||||||
buf[pos..pos + k.len()].copy_from_slice(k);
|
buf[pos..pos + k.len()].copy_from_slice(k);
|
||||||
|
}
|
||||||
pos += k.len();
|
pos += k.len();
|
||||||
buf[pos..pos + 2].copy_from_slice(b": ");
|
buf[pos..pos + 2].copy_from_slice(b": ");
|
||||||
pos += 2;
|
pos += 2;
|
||||||
@ -221,6 +256,10 @@ impl MessageType for RequestHead {
|
|||||||
self.chunked()
|
self.chunked()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn camel_case(&self) -> bool {
|
||||||
|
RequestHead::camel_case_headers(self)
|
||||||
|
}
|
||||||
|
|
||||||
fn headers(&self) -> &HeaderMap {
|
fn headers(&self) -> &HeaderMap {
|
||||||
&self.headers
|
&self.headers
|
||||||
}
|
}
|
||||||
@ -418,11 +457,41 @@ impl<'a> io::Write for Writer<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn write_camel_case(value: &[u8], buffer: &mut [u8]) {
|
||||||
|
let mut index = 0;
|
||||||
|
let key = value;
|
||||||
|
let mut key_iter = key.iter();
|
||||||
|
|
||||||
|
if let Some(c) = key_iter.next() {
|
||||||
|
if *c >= b'a' && *c <= b'z' {
|
||||||
|
buffer[index] = *c ^ b' ';
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while let Some(c) = key_iter.next() {
|
||||||
|
buffer[index] = *c;
|
||||||
|
index += 1;
|
||||||
|
if *c == b'-' {
|
||||||
|
if let Some(c) = key_iter.next() {
|
||||||
|
if *c >= b'a' && *c <= b'z' {
|
||||||
|
buffer[index] = *c ^ b' ';
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::http::header::{HeaderValue, CONTENT_TYPE};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_chunked_te() {
|
fn test_chunked_te() {
|
||||||
let mut bytes = BytesMut::new();
|
let mut bytes = BytesMut::new();
|
||||||
@ -436,4 +505,77 @@ mod tests {
|
|||||||
Bytes::from_static(b"4\r\ntest\r\n0\r\n\r\n")
|
Bytes::from_static(b"4\r\ntest\r\n0\r\n\r\n")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_camel_case() {
|
||||||
|
let mut bytes = BytesMut::with_capacity(2048);
|
||||||
|
let mut head = RequestHead::default();
|
||||||
|
head.set_camel_case_headers(true);
|
||||||
|
head.headers.insert(DATE, HeaderValue::from_static("date"));
|
||||||
|
head.headers
|
||||||
|
.insert(CONTENT_TYPE, HeaderValue::from_static("plain/text"));
|
||||||
|
|
||||||
|
let _ = head.encode_headers(
|
||||||
|
&mut bytes,
|
||||||
|
Version::HTTP_11,
|
||||||
|
BodySize::Empty,
|
||||||
|
ConnectionType::Close,
|
||||||
|
&ServiceConfig::default(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bytes.take().freeze(),
|
||||||
|
Bytes::from_static(b"\r\nContent-Length: 0\r\nConnection: close\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
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: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
let _ = head.encode_headers(
|
||||||
|
&mut bytes,
|
||||||
|
Version::HTTP_11,
|
||||||
|
BodySize::Sized64(100),
|
||||||
|
ConnectionType::KeepAlive,
|
||||||
|
&ServiceConfig::default(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bytes.take().freeze(),
|
||||||
|
Bytes::from_static(b"\r\nContent-Length: 100\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
head.headers
|
||||||
|
.append(CONTENT_TYPE, HeaderValue::from_static("xml"));
|
||||||
|
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")
|
||||||
|
);
|
||||||
|
|
||||||
|
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")
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{NewService, Service};
|
use actix_service::{NewService, Service};
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{Async, Poll};
|
use futures::{Async, Poll};
|
||||||
@ -8,6 +9,7 @@ use crate::request::Request;
|
|||||||
pub struct ExpectHandler;
|
pub struct ExpectHandler;
|
||||||
|
|
||||||
impl NewService for ExpectHandler {
|
impl NewService for ExpectHandler {
|
||||||
|
type Config = ServerConfig;
|
||||||
type Request = Request;
|
type Request = Request;
|
||||||
type Response = Request;
|
type Response = Request;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -15,7 +17,7 @@ impl NewService for ExpectHandler {
|
|||||||
type InitError = Error;
|
type InitError = Error;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &()) -> Self::Future {
|
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||||
ok(ExpectHandler)
|
ok(ExpectHandler)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -29,14 +29,14 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
|
|||||||
|
|
||||||
impl<T, P, S, B> H1Service<T, P, S, B>
|
impl<T, P, S, B> H1Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance with default config.
|
/// Create new `HttpService` instance with default config.
|
||||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||||
|
|
||||||
H1Service {
|
H1Service {
|
||||||
@ -49,10 +49,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create new `HttpService` instance with config.
|
/// Create new `HttpService` instance with config.
|
||||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||||
cfg: ServiceConfig,
|
|
||||||
service: F,
|
|
||||||
) -> Self {
|
|
||||||
H1Service {
|
H1Service {
|
||||||
cfg,
|
cfg,
|
||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
@ -65,7 +62,7 @@ where
|
|||||||
|
|
||||||
impl<T, P, S, B, X, U> H1Service<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> H1Service<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
@ -102,21 +99,26 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for H1Service<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> NewService for H1Service<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
U: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = Io<T, P>;
|
type Request = Io<T, P>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -127,8 +129,8 @@ where
|
|||||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||||
H1ServiceResponse {
|
H1ServiceResponse {
|
||||||
fut: self.srv.new_service(cfg).into_future(),
|
fut: self.srv.new_service(cfg).into_future(),
|
||||||
fut_ex: Some(self.expect.new_service(&())),
|
fut_ex: Some(self.expect.new_service(cfg)),
|
||||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||||
expect: None,
|
expect: None,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
@ -140,7 +142,7 @@ where
|
|||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct H1ServiceResponse<T, P, S, B, X, U>
|
pub struct H1ServiceResponse<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Request = Request, Response = Request>,
|
||||||
@ -162,7 +164,7 @@ where
|
|||||||
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
@ -320,10 +322,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P> NewService<SrvConfig> for OneRequest<T, P>
|
impl<T, P> NewService for OneRequest<T, P>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = Io<T, P>;
|
type Request = Io<T, P>;
|
||||||
type Response = (Request, Framed<T, Codec>);
|
type Response = (Request, Framed<T, Codec>);
|
||||||
type Error = ParseError;
|
type Error = ParseError;
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{NewService, Service};
|
use actix_service::{NewService, Service};
|
||||||
use futures::future::FutureResult;
|
use futures::future::FutureResult;
|
||||||
use futures::{Async, Poll};
|
use futures::{Async, Poll};
|
||||||
@ -12,6 +13,7 @@ use crate::request::Request;
|
|||||||
pub struct UpgradeHandler<T>(PhantomData<T>);
|
pub struct UpgradeHandler<T>(PhantomData<T>);
|
||||||
|
|
||||||
impl<T> NewService for UpgradeHandler<T> {
|
impl<T> NewService for UpgradeHandler<T> {
|
||||||
|
type Config = ServerConfig;
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -19,7 +21,7 @@ impl<T> NewService for UpgradeHandler<T> {
|
|||||||
type InitError = Error;
|
type InitError = Error;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &()) -> Self::Future {
|
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||||
unimplemented!()
|
unimplemented!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -31,14 +31,14 @@ pub struct H2Service<T, P, S, B> {
|
|||||||
|
|
||||||
impl<T, P, S, B> H2Service<T, P, S, B>
|
impl<T, P, S, B> H2Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance.
|
/// Create new `HttpService` instance.
|
||||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||||
|
|
||||||
H2Service {
|
H2Service {
|
||||||
@ -49,10 +49,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create new `HttpService` instance with config.
|
/// Create new `HttpService` instance with config.
|
||||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||||
cfg: ServiceConfig,
|
|
||||||
service: F,
|
|
||||||
) -> Self {
|
|
||||||
H2Service {
|
H2Service {
|
||||||
cfg,
|
cfg,
|
||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
@ -61,15 +58,16 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B> NewService<SrvConfig> for H2Service<T, P, S, B>
|
impl<T, P, S, B> NewService for H2Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = Io<T, P>;
|
type Request = Io<T, P>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -87,7 +85,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>, B> {
|
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
||||||
fut: <S::Future as IntoFuture>::Future,
|
fut: <S::Future as IntoFuture>::Future,
|
||||||
cfg: Option<ServiceConfig>,
|
cfg: Option<ServiceConfig>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
@ -96,7 +94,7 @@ pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>,
|
|||||||
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B>
|
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
|
@ -27,6 +27,7 @@ bitflags! {
|
|||||||
const UPGRADE = 0b0000_0100;
|
const UPGRADE = 0b0000_0100;
|
||||||
const EXPECT = 0b0000_1000;
|
const EXPECT = 0b0000_1000;
|
||||||
const NO_CHUNKING = 0b0001_0000;
|
const NO_CHUNKING = 0b0001_0000;
|
||||||
|
const CAMEL_CASE = 0b0010_0000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,6 +98,23 @@ impl RequestHead {
|
|||||||
&mut self.headers
|
&mut self.headers
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Is to uppercase headers with Camel-Case.
|
||||||
|
/// Befault is `false`
|
||||||
|
#[inline]
|
||||||
|
pub fn camel_case_headers(&self) -> bool {
|
||||||
|
self.flags.contains(Flags::CAMEL_CASE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set `true` to send headers which are uppercased with Camel-Case.
|
||||||
|
#[inline]
|
||||||
|
pub fn set_camel_case_headers(&mut self, val: bool) {
|
||||||
|
if val {
|
||||||
|
self.flags.insert(Flags::CAMEL_CASE);
|
||||||
|
} else {
|
||||||
|
self.flags.remove(Flags::CAMEL_CASE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
/// Set connection type of the message
|
/// Set connection type of the message
|
||||||
pub fn set_connection_type(&mut self, ctype: ConnectionType) {
|
pub fn set_connection_type(&mut self, ctype: ConnectionType) {
|
||||||
@ -431,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -30,7 +30,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
|
|||||||
|
|
||||||
impl<T, S, B> HttpService<T, (), S, B>
|
impl<T, S, B> HttpService<T, (), S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -45,7 +45,7 @@ where
|
|||||||
|
|
||||||
impl<T, P, S, B> HttpService<T, P, S, B>
|
impl<T, P, S, B> HttpService<T, P, S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -53,7 +53,7 @@ where
|
|||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance.
|
/// Create new `HttpService` instance.
|
||||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||||
|
|
||||||
HttpService {
|
HttpService {
|
||||||
@ -66,7 +66,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create new `HttpService` instance with config.
|
/// Create new `HttpService` instance with config.
|
||||||
pub(crate) fn with_config<F: IntoNewService<S, SrvConfig>>(
|
pub(crate) fn with_config<F: IntoNewService<S>>(
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
service: F,
|
service: F,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
@ -82,7 +82,7 @@ where
|
|||||||
|
|
||||||
impl<T, P, S, B, X, U> HttpService<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> HttpService<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -95,7 +95,7 @@ where
|
|||||||
/// request will be forwarded to main service.
|
/// request will be forwarded to main service.
|
||||||
pub fn expect<X1>(self, expect: X1) -> HttpService<T, P, S, B, X1, U>
|
pub fn expect<X1>(self, expect: X1) -> HttpService<T, P, S, B, X1, U>
|
||||||
where
|
where
|
||||||
X1: NewService<Request = Request, Response = Request>,
|
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X1::Error: Into<Error>,
|
X1::Error: Into<Error>,
|
||||||
X1::InitError: fmt::Debug,
|
X1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -114,7 +114,11 @@ where
|
|||||||
/// and this service get called with original request and framed object.
|
/// and this service get called with original request and framed object.
|
||||||
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, P, S, B, X, U1>
|
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, P, S, B, X, U1>
|
||||||
where
|
where
|
||||||
U1: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
U1: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, h1::Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U1::Error: fmt::Display,
|
U1::Error: fmt::Display,
|
||||||
U1::InitError: fmt::Debug,
|
U1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -128,22 +132,27 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for HttpService<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> NewService for HttpService<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
U: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
U: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, h1::Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = ServerIo<T, P>;
|
type Request = ServerIo<T, P>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -154,8 +163,8 @@ where
|
|||||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||||
HttpServiceResponse {
|
HttpServiceResponse {
|
||||||
fut: self.srv.new_service(cfg).into_future(),
|
fut: self.srv.new_service(cfg).into_future(),
|
||||||
fut_ex: Some(self.expect.new_service(&())),
|
fut_ex: Some(self.expect.new_service(cfg)),
|
||||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||||
expect: None,
|
expect: None,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
@ -165,14 +174,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct HttpServiceResponse<
|
pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewService> {
|
||||||
T,
|
|
||||||
P,
|
|
||||||
S: NewService<SrvConfig>,
|
|
||||||
B,
|
|
||||||
X: NewService,
|
|
||||||
U: NewService,
|
|
||||||
> {
|
|
||||||
fut: S::Future,
|
fut: S::Future,
|
||||||
fut_ex: Option<X::Future>,
|
fut_ex: Option<X::Future>,
|
||||||
fut_upg: Option<U::Future>,
|
fut_upg: Option<U::Future>,
|
||||||
@ -185,7 +187,7 @@ pub struct HttpServiceResponse<
|
|||||||
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
@ -59,9 +59,7 @@ fn test_connection_close() {
|
|||||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
});
|
});
|
||||||
println!("REQ: {:?}", srv.get("/").force_close());
|
|
||||||
let response = srv.block_on(srv.get("/").force_close().send()).unwrap();
|
let response = srv.block_on(srv.get("/").force_close().send()).unwrap();
|
||||||
println!("RES: {:?}", response);
|
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,7 +5,7 @@ use std::{net, thread};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_server_config::ServerConfig;
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{fn_cfg_factory, fn_service, NewService};
|
use actix_service::{new_service_cfg, service_fn, NewService};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::future::{self, ok, Future};
|
use futures::future::{self, ok, Future};
|
||||||
use futures::stream::{once, Stream};
|
use futures::stream::{once, Stream};
|
||||||
@ -163,7 +163,7 @@ fn test_h2_body() -> std::io::Result<()> {
|
|||||||
fn test_expect_continue() {
|
fn test_expect_continue() {
|
||||||
let srv = TestServer::new(|| {
|
let srv = TestServer::new(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.expect(fn_service(|req: Request| {
|
.expect(service_fn(|req: Request| {
|
||||||
if req.head().uri.query() == Some("yes=") {
|
if req.head().uri.query() == Some("yes=") {
|
||||||
Ok(req)
|
Ok(req)
|
||||||
} else {
|
} else {
|
||||||
@ -190,7 +190,7 @@ fn test_expect_continue() {
|
|||||||
fn test_expect_continue_h1() {
|
fn test_expect_continue_h1() {
|
||||||
let srv = TestServer::new(|| {
|
let srv = TestServer::new(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.expect(fn_service(|req: Request| {
|
.expect(service_fn(|req: Request| {
|
||||||
sleep(Duration::from_millis(20)).then(move |_| {
|
sleep(Duration::from_millis(20)).then(move |_| {
|
||||||
if req.head().uri.query() == Some("yes=") {
|
if req.head().uri.query() == Some("yes=") {
|
||||||
Ok(req)
|
Ok(req)
|
||||||
@ -912,7 +912,7 @@ fn test_h1_body_chunked_implicit() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_h1_response_http_error_handling() {
|
fn test_h1_response_http_error_handling() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
HttpService::build().h1(fn_cfg_factory(|_: &ServerConfig| {
|
HttpService::build().h1(new_service_cfg(|_: &ServerConfig| {
|
||||||
Ok::<_, ()>(|_| {
|
Ok::<_, ()>(|_| {
|
||||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
@ -943,7 +943,7 @@ fn test_h2_response_http_error_handling() {
|
|||||||
.map_err(|e| println!("Openssl error: {}", e))
|
.map_err(|e| println!("Openssl error: {}", e))
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(fn_cfg_factory(|_: &ServerConfig| {
|
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||||
Ok::<_, ()>(|_| {
|
Ok::<_, ()>(|_| {
|
||||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
|
@ -19,7 +19,7 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-beta.1"
|
actix-web = "1.0.0-beta.1"
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.0"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
@ -31,4 +31,4 @@ twoway = "0.2"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-http = "0.1.1"
|
actix-http = "0.2.0"
|
@ -1 +1,8 @@
|
|||||||
# Multipart support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-multipart) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Multipart support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-multipart) [](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
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.0-beta.2] - 2019-04-28
|
||||||
|
|
||||||
|
* Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest
|
||||||
|
|
||||||
## [0.1.0-beta.1] - 2019-04-20
|
## [0.1.0-beta.1] - 2019-04-20
|
||||||
|
|
||||||
* Update actix-web to beta.1
|
* Update actix-web to beta.1
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-session"
|
name = "actix-session"
|
||||||
version = "0.1.0-beta.1"
|
version = "0.1.0-beta.2"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Session for actix web framework."
|
description = "Session for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -24,12 +24,12 @@ default = ["cookie-session"]
|
|||||||
cookie-session = ["actix-web/secure-cookies"]
|
cookie-session = ["actix-web/secure-cookies"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-beta.1"
|
actix-web = "1.0.0-beta.2"
|
||||||
actix-service = "0.3.4"
|
actix-service = "0.4.0"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.2.2"
|
hashbrown = "0.3.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
time = "0.1.42"
|
time = "0.1.42"
|
||||||
|
@ -1 +1,9 @@
|
|||||||
# Session for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-session) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Session for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-session) [](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
|
||||||
|
@ -79,6 +79,23 @@ pub use crate::cookie::CookieSession;
|
|||||||
/// ```
|
/// ```
|
||||||
pub struct Session(Rc<RefCell<SessionInner>>);
|
pub struct Session(Rc<RefCell<SessionInner>>);
|
||||||
|
|
||||||
|
/// Helper trait that allows to get session
|
||||||
|
pub trait UserSession {
|
||||||
|
fn get_session(&mut self) -> Session;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserSession for HttpRequest {
|
||||||
|
fn get_session(&mut self) -> Session {
|
||||||
|
Session::get_session(&mut *self.extensions_mut())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserSession for ServiceRequest {
|
||||||
|
fn get_session(&mut self) -> Session {
|
||||||
|
Session::get_session(&mut *self.extensions_mut())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct SessionInner {
|
struct SessionInner {
|
||||||
state: HashMap<String, String>,
|
state: HashMap<String, String>,
|
||||||
@ -208,4 +225,18 @@ mod tests {
|
|||||||
let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
|
let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
|
||||||
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_session() {
|
||||||
|
let mut req = test::TestRequest::default().to_srv_request();
|
||||||
|
|
||||||
|
Session::set_session(
|
||||||
|
vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
|
||||||
|
&mut req,
|
||||||
|
);
|
||||||
|
|
||||||
|
let session = req.get_session();
|
||||||
|
let res = session.get::<String>("key").unwrap();
|
||||||
|
assert_eq!(res, Some("value".to_string()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,11 +20,11 @@ path = "src/lib.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.8.0"
|
actix = "0.8.0"
|
||||||
actix-web = "1.0.0-beta.1"
|
actix-web = "1.0.0-beta.1"
|
||||||
actix-http = "0.1.1"
|
actix-http = "0.2.0"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
|
@ -1 +1,8 @@
|
|||||||
Actix actors support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-web-actors) [](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 [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-web-actors) [](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
|
||||||
|
@ -17,6 +17,6 @@ syn = { version = "0.15", features = ["full", "parsing"] }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "1.0.0-alpha.6" }
|
actix-web = { version = "1.0.0-alpha.6" }
|
||||||
actix-http = { version = "0.1.1", features=["ssl"] }
|
actix-http = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
futures = { version = "0.1" }
|
futures = { version = "0.1" }
|
||||||
|
@ -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();
|
||||||
|
@ -1,5 +1,16 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to send headers in `Camel-Case` form.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Upgrade actix-http dependency.
|
||||||
|
|
||||||
|
|
||||||
## [0.1.1] - 2019-04-19
|
## [0.1.1] - 2019-04-19
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "awc"
|
name = "awc"
|
||||||
version = "0.1.1"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix http client."
|
description = "Actix http client."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -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"
|
||||||
@ -37,8 +40,8 @@ flate2-rust = ["actix-http/flate2-rust"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.0"
|
||||||
actix-http = "0.1.1"
|
actix-http = "0.2.0"
|
||||||
base64 = "0.10.1"
|
base64 = "0.10.1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
@ -55,11 +58,11 @@ openssl = { version="0.10", optional = true }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-web = { version = "1.0.0-alpha.6", features=["ssl"] }
|
actix-web = { version = "1.0.0-beta.1", features=["ssl"] }
|
||||||
actix-http = { version = "0.1.1", features=["ssl"] }
|
actix-http = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-utils = "0.3.4"
|
actix-utils = "0.4.0"
|
||||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||||
brotli2 = { version="0.3.2" }
|
brotli2 = { version="0.3.2" }
|
||||||
flate2 = { version="1.0.2" }
|
flate2 = { version="1.0.2" }
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
|
@ -140,11 +140,9 @@ impl ClientBuilder {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::test;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn client_basic_auth() {
|
fn client_basic_auth() {
|
||||||
test::run_on(|| {
|
|
||||||
let client = ClientBuilder::new().basic_auth("username", Some("password"));
|
let client = ClientBuilder::new().basic_auth("username", Some("password"));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
client
|
client
|
||||||
@ -168,12 +166,10 @@ mod tests {
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
"Basic dXNlcm5hbWU="
|
"Basic dXNlcm5hbWU="
|
||||||
);
|
);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn client_bearer_auth() {
|
fn client_bearer_auth() {
|
||||||
test::run_on(|| {
|
|
||||||
let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n");
|
let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
client
|
client
|
||||||
@ -185,6 +181,5 @@ mod tests {
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
"Bearer someS3cr3tAutht0k3n"
|
"Bearer someS3cr3tAutht0k3n"
|
||||||
);
|
);
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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)
|
||||||
|
@ -235,6 +235,13 @@ impl ClientRequest {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Send headers in `Camel-Case` form.
|
||||||
|
#[inline]
|
||||||
|
pub fn camel_case(mut self) -> Self {
|
||||||
|
self.head.set_camel_case_headers(true);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Force close connection instead of returning it back to connections pool.
|
/// Force close connection instead of returning it back to connections pool.
|
||||||
/// This setting affect only http/1 connections.
|
/// This setting affect only http/1 connections.
|
||||||
#[inline]
|
#[inline]
|
||||||
|
@ -347,10 +347,11 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use actix_http_test::block_on;
|
||||||
use futures::Async;
|
use futures::Async;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::{http::header, test::block_on, test::TestResponse};
|
use crate::{http::header, test::TestResponse};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_body() {
|
fn test_body() {
|
||||||
|
@ -6,39 +6,10 @@ use actix_http::http::header::{self, Header, HeaderValue, IntoHeaderValue};
|
|||||||
use actix_http::http::{HeaderName, HttpTryFrom, StatusCode, Version};
|
use actix_http::http::{HeaderName, HttpTryFrom, StatusCode, Version};
|
||||||
use actix_http::{h1, Payload, ResponseHead};
|
use actix_http::{h1, Payload, ResponseHead};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
#[cfg(test)]
|
|
||||||
use futures::Future;
|
|
||||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||||
|
|
||||||
use crate::ClientResponse;
|
use crate::ClientResponse;
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
thread_local! {
|
|
||||||
static RT: std::cell::RefCell<actix_rt::Runtime> = {
|
|
||||||
std::cell::RefCell::new(actix_rt::Runtime::new().unwrap())
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) fn run_on<F, R>(f: F) -> R
|
|
||||||
where
|
|
||||||
F: Fn() -> R,
|
|
||||||
{
|
|
||||||
RT.with(move |rt| {
|
|
||||||
rt.borrow_mut()
|
|
||||||
.block_on(futures::future::lazy(|| Ok::<_, ()>(f())))
|
|
||||||
})
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) fn block_on<F>(f: F) -> Result<F::Item, F::Error>
|
|
||||||
where
|
|
||||||
F: Future,
|
|
||||||
{
|
|
||||||
RT.with(move |rt| rt.borrow_mut().block_on(f))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test `ClientResponse` builder
|
/// Test `ClientResponse` builder
|
||||||
pub struct TestResponse {
|
pub struct TestResponse {
|
||||||
head: ResponseHead,
|
head: ResponseHead,
|
||||||
|
@ -318,7 +318,9 @@ impl WebsocketsRequest {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log::trace!("Invalid connection header: {:?}", conn);
|
log::trace!("Invalid connection header: {:?}", conn);
|
||||||
return Err(WsClientError::InvalidConnectionHeader(conn.clone()));
|
return Err(WsClientError::InvalidConnectionHeader(
|
||||||
|
conn.clone(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log::trace!("Missing connection header");
|
log::trace!("Missing connection header");
|
||||||
@ -462,7 +464,6 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn basics() {
|
fn basics() {
|
||||||
actix_http_test::run_on(|| {
|
|
||||||
let req = Client::new()
|
let req = Client::new()
|
||||||
.ws("http://localhost/")
|
.ws("http://localhost/")
|
||||||
.origin("test-origin")
|
.origin("test-origin")
|
||||||
@ -483,8 +484,8 @@ mod tests {
|
|||||||
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
|
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
|
||||||
header::HeaderValue::from_static("json")
|
header::HeaderValue::from_static("json")
|
||||||
);
|
);
|
||||||
let _ = req.connect();
|
|
||||||
});
|
let _ = actix_http_test::block_fn(move || req.connect());
|
||||||
|
|
||||||
assert!(Client::new().ws("/").connect().poll().is_err());
|
assert!(Client::new().ws("/").connect().poll().is_err());
|
||||||
assert!(Client::new().ws("http:///test").connect().poll().is_err());
|
assert!(Client::new().ws("http:///test").connect().poll().is_err());
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use brotli2::write::BrotliEncoder;
|
use brotli2::write::BrotliEncoder;
|
||||||
@ -7,12 +9,14 @@ use bytes::Bytes;
|
|||||||
use flate2::read::GzDecoder;
|
use flate2::read::GzDecoder;
|
||||||
use flate2::write::GzEncoder;
|
use flate2::write::GzEncoder;
|
||||||
use flate2::Compression;
|
use flate2::Compression;
|
||||||
use futures::future::Future;
|
use futures::Future;
|
||||||
use rand::Rng;
|
use rand::Rng;
|
||||||
|
|
||||||
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_web::http::Cookie;
|
use actix_service::{service_fn, NewService};
|
||||||
|
use actix_web::http::{Cookie, Version};
|
||||||
use actix_web::middleware::{BodyEncoding, Compress};
|
use actix_web::middleware::{BodyEncoding, Compress};
|
||||||
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
|
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
|
||||||
use awc::error::SendRequestError;
|
use awc::error::SendRequestError;
|
||||||
@ -39,6 +43,30 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
|||||||
Hello World Hello World Hello World Hello World Hello World \
|
Hello World Hello World Hello World Hello World Hello World \
|
||||||
Hello World Hello World Hello World Hello World Hello World";
|
Hello World Hello World Hello World Hello World Hello World";
|
||||||
|
|
||||||
|
#[cfg(feature = "ssl")]
|
||||||
|
fn ssl_acceptor<T: AsyncRead + AsyncWrite>(
|
||||||
|
) -> std::io::Result<actix_server::ssl::OpensslAcceptor<T, ()>> {
|
||||||
|
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
||||||
|
// load ssl keys
|
||||||
|
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||||
|
builder
|
||||||
|
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
|
||||||
|
.unwrap();
|
||||||
|
builder
|
||||||
|
.set_certificate_chain_file("../tests/cert.pem")
|
||||||
|
.unwrap();
|
||||||
|
builder.set_alpn_select_callback(|_, protos| {
|
||||||
|
const H2: &[u8] = b"\x02h2";
|
||||||
|
if protos.windows(3).any(|window| window == H2) {
|
||||||
|
Ok(b"h2")
|
||||||
|
} else {
|
||||||
|
Err(openssl::ssl::AlpnError::NOACK)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
builder.set_alpn_protos(b"\x02h2")?;
|
||||||
|
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_simple() {
|
fn test_simple() {
|
||||||
let mut srv =
|
let mut srv =
|
||||||
@ -62,6 +90,10 @@ fn test_simple() {
|
|||||||
// read response
|
// read response
|
||||||
let bytes = srv.block_on(response.body()).unwrap();
|
let bytes = srv.block_on(response.body()).unwrap();
|
||||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
|
|
||||||
|
// camel case
|
||||||
|
let response = srv.block_on(srv.post("/").camel_case().send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -144,17 +176,249 @@ fn test_timeout_override() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_connection_close() {
|
fn test_connection_reuse() {
|
||||||
let mut srv = TestServer::new(|| {
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
HttpService::new(
|
let num2 = num.clone();
|
||||||
App::new().service(web::resource("/").to(|| HttpResponse::Ok())),
|
|
||||||
|
let mut srv = TestServer::new(move || {
|
||||||
|
let num2 = num2.clone();
|
||||||
|
service_fn(move |io| {
|
||||||
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Ok(io)
|
||||||
|
})
|
||||||
|
.and_then(HttpService::new(
|
||||||
|
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = awc::Client::default();
|
||||||
|
|
||||||
|
// req 1
|
||||||
|
let request = client.get(srv.url("/")).send();
|
||||||
|
let response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let req = client.post(srv.url("/"));
|
||||||
|
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// one connection
|
||||||
|
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "ssl")]
|
||||||
|
#[test]
|
||||||
|
fn test_connection_reuse_h2() {
|
||||||
|
let openssl = ssl_acceptor().unwrap();
|
||||||
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
|
let num2 = num.clone();
|
||||||
|
|
||||||
|
let mut srv = TestServer::new(move || {
|
||||||
|
let num2 = num2.clone();
|
||||||
|
service_fn(move |io| {
|
||||||
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Ok(io)
|
||||||
|
})
|
||||||
|
.and_then(
|
||||||
|
openssl
|
||||||
|
.clone()
|
||||||
|
.map_err(|e| println!("Openssl error: {}", e)),
|
||||||
|
)
|
||||||
|
.and_then(
|
||||||
|
HttpService::build()
|
||||||
|
.h2(App::new()
|
||||||
|
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||||
|
.map_err(|_| ()),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
let res = srv
|
// disable ssl verification
|
||||||
.block_on(awc::Client::new().get(srv.url("/")).force_close().send())
|
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
|
||||||
.unwrap();
|
|
||||||
assert!(res.status().is_success());
|
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||||
|
builder.set_verify(SslVerifyMode::NONE);
|
||||||
|
let _ = builder
|
||||||
|
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||||
|
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
|
||||||
|
|
||||||
|
let client = awc::Client::build()
|
||||||
|
.connector(awc::Connector::new().ssl(builder.build()).finish())
|
||||||
|
.finish();
|
||||||
|
|
||||||
|
// req 1
|
||||||
|
let request = client.get(srv.surl("/")).send();
|
||||||
|
let response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let req = client.post(srv.surl("/"));
|
||||||
|
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
assert_eq!(response.version(), Version::HTTP_2);
|
||||||
|
|
||||||
|
// one connection
|
||||||
|
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_connection_force_close() {
|
||||||
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
|
let num2 = num.clone();
|
||||||
|
|
||||||
|
let mut srv = TestServer::new(move || {
|
||||||
|
let num2 = num2.clone();
|
||||||
|
service_fn(move |io| {
|
||||||
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Ok(io)
|
||||||
|
})
|
||||||
|
.and_then(HttpService::new(
|
||||||
|
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = awc::Client::default();
|
||||||
|
|
||||||
|
// req 1
|
||||||
|
let request = client.get(srv.url("/")).force_close().send();
|
||||||
|
let response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let req = client.post(srv.url("/")).force_close();
|
||||||
|
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// two connection
|
||||||
|
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_connection_server_close() {
|
||||||
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
|
let num2 = num.clone();
|
||||||
|
|
||||||
|
let mut srv = TestServer::new(move || {
|
||||||
|
let num2 = num2.clone();
|
||||||
|
service_fn(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())),
|
||||||
|
),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = awc::Client::default();
|
||||||
|
|
||||||
|
// req 1
|
||||||
|
let request = client.get(srv.url("/")).send();
|
||||||
|
let response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let req = client.post(srv.url("/"));
|
||||||
|
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// two connection
|
||||||
|
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_connection_wait_queue() {
|
||||||
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
|
let num2 = num.clone();
|
||||||
|
|
||||||
|
let mut srv = TestServer::new(move || {
|
||||||
|
let num2 = num2.clone();
|
||||||
|
service_fn(move |io| {
|
||||||
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Ok(io)
|
||||||
|
})
|
||||||
|
.and_then(HttpService::new(App::new().service(
|
||||||
|
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||||
|
)))
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = awc::Client::build()
|
||||||
|
.connector(awc::Connector::new().limit(1).finish())
|
||||||
|
.finish();
|
||||||
|
|
||||||
|
// req 1
|
||||||
|
let request = client.get(srv.url("/")).send();
|
||||||
|
let mut response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let req2 = client.post(srv.url("/"));
|
||||||
|
let req2_fut = srv.execute(move || {
|
||||||
|
let mut fut = req2.send();
|
||||||
|
assert!(fut.poll().unwrap().is_not_ready());
|
||||||
|
fut
|
||||||
|
});
|
||||||
|
|
||||||
|
// read response 1
|
||||||
|
let bytes = srv.block_on(response.body()).unwrap();
|
||||||
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let response = srv.block_on(req2_fut).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// two connection
|
||||||
|
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_connection_wait_queue_force_close() {
|
||||||
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
|
let num2 = num.clone();
|
||||||
|
|
||||||
|
let mut srv = TestServer::new(move || {
|
||||||
|
let num2 = num2.clone();
|
||||||
|
service_fn(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))),
|
||||||
|
),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = awc::Client::build()
|
||||||
|
.connector(awc::Connector::new().limit(1).finish())
|
||||||
|
.finish();
|
||||||
|
|
||||||
|
// req 1
|
||||||
|
let request = client.get(srv.url("/")).send();
|
||||||
|
let mut response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let req2 = client.post(srv.url("/"));
|
||||||
|
let req2_fut = srv.execute(move || {
|
||||||
|
let mut fut = req2.send();
|
||||||
|
assert!(fut.poll().unwrap().is_not_ready());
|
||||||
|
fut
|
||||||
|
});
|
||||||
|
|
||||||
|
// read response 1
|
||||||
|
let bytes = srv.block_on(response.body()).unwrap();
|
||||||
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
|
|
||||||
|
// req 2
|
||||||
|
let response = srv.block_on(req2_fut).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// two connection
|
||||||
|
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -1,17 +1,11 @@
|
|||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
|
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_server::Io;
|
|
||||||
use actix_service::{fn_service, NewService};
|
|
||||||
use actix_utils::framed::IntoFramed;
|
|
||||||
use actix_utils::stream::TakeItem;
|
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::future::{ok, Either};
|
use futures::future::ok;
|
||||||
use futures::{Future, Sink, Stream};
|
use futures::{Future, Sink, Stream};
|
||||||
use tokio_tcp::TcpStream;
|
|
||||||
|
|
||||||
use actix_http::{body::BodySize, h1, ws, Request, ResponseError, ServiceConfig};
|
|
||||||
|
|
||||||
fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Error> {
|
fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Error> {
|
||||||
match req {
|
match req {
|
||||||
@ -37,52 +31,20 @@ fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Err
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_simple() {
|
fn test_simple() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
fn_service(|io: Io<TcpStream>| Ok(io.into_parts().0))
|
HttpService::build()
|
||||||
.and_then(IntoFramed::new(|| h1::Codec::new(ServiceConfig::default())))
|
.upgrade(|(req, framed): (Request, Framed<_, _>)| {
|
||||||
.and_then(TakeItem::new().map_err(|_| ()))
|
|
||||||
.and_then(
|
|
||||||
|(req, framed): (Option<h1::Message<Request>>, Framed<_, _>)| {
|
|
||||||
// validate request
|
|
||||||
if let Some(h1::Message::Item(req)) = req {
|
|
||||||
match ws::verify_handshake(req.head()) {
|
|
||||||
Err(e) => {
|
|
||||||
// validation failed
|
|
||||||
let res = e.error_response();
|
|
||||||
Either::A(
|
|
||||||
framed
|
|
||||||
.send(h1::Message::Item((
|
|
||||||
res.drop_body(),
|
|
||||||
BodySize::Empty,
|
|
||||||
)))
|
|
||||||
.map_err(|_| ())
|
|
||||||
.map(|_| ()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Ok(_) => {
|
|
||||||
let res = ws::handshake_response(req.head()).finish();
|
let res = ws::handshake_response(req.head()).finish();
|
||||||
Either::B(
|
|
||||||
// send handshake response
|
// send handshake response
|
||||||
framed
|
framed
|
||||||
.send(h1::Message::Item((
|
.send(h1::Message::Item((res.drop_body(), BodySize::None)))
|
||||||
res.drop_body(),
|
.map_err(|e: io::Error| e.into())
|
||||||
BodySize::None,
|
|
||||||
)))
|
|
||||||
.map_err(|_| ())
|
|
||||||
.and_then(|framed| {
|
.and_then(|framed| {
|
||||||
// start websocket service
|
// start websocket service
|
||||||
let framed =
|
let framed = framed.into_framed(ws::Codec::new());
|
||||||
framed.into_framed(ws::Codec::new());
|
|
||||||
ws::Transport::with(framed, ws_service)
|
ws::Transport::with(framed, ws_service)
|
||||||
.map_err(|_| ())
|
})
|
||||||
}),
|
})
|
||||||
)
|
.finish(|_| ok::<_, Error>(Response::NotFound()))
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
|
104
src/app.rs
104
src/app.rs
@ -4,7 +4,6 @@ use std::marker::PhantomData;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::body::{Body, MessageBody};
|
use actix_http::body::{Body, MessageBody};
|
||||||
use actix_server_config::ServerConfig;
|
|
||||||
use actix_service::boxed::{self, BoxedNewService};
|
use actix_service::boxed::{self, BoxedNewService};
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
apply_transform, IntoNewService, IntoTransform, NewService, Transform,
|
apply_transform, IntoNewService, IntoTransform, NewService, Transform,
|
||||||
@ -59,6 +58,7 @@ impl<T, B> App<T, B>
|
|||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse<B>,
|
Response = ServiceResponse<B>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -95,24 +95,11 @@ where
|
|||||||
/// web::get().to(index)));
|
/// web::get().to(index)));
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn data<S: 'static>(mut self, data: S) -> Self {
|
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||||
self.data.push(Box::new(Data::new(data)));
|
self.data.push(Box::new(Data::new(data)));
|
||||||
self
|
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
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run external configuration as part of the application building
|
/// Run external configuration as part of the application building
|
||||||
/// process
|
/// process
|
||||||
///
|
///
|
||||||
@ -141,7 +128,7 @@ where
|
|||||||
/// ```
|
/// ```
|
||||||
pub fn configure<F>(mut self, f: F) -> Self
|
pub fn configure<F>(mut self, f: F) -> Self
|
||||||
where
|
where
|
||||||
F: Fn(&mut ServiceConfig),
|
F: FnOnce(&mut ServiceConfig),
|
||||||
{
|
{
|
||||||
let mut cfg = ServiceConfig::new();
|
let mut cfg = ServiceConfig::new();
|
||||||
f(&mut cfg);
|
f(&mut cfg);
|
||||||
@ -247,6 +234,7 @@ where
|
|||||||
where
|
where
|
||||||
F: IntoNewService<U>,
|
F: IntoNewService<U>,
|
||||||
U: NewService<
|
U: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -301,7 +289,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;
|
||||||
@ -324,6 +320,7 @@ where
|
|||||||
mw: F,
|
mw: F,
|
||||||
) -> App<
|
) -> App<
|
||||||
impl NewService<
|
impl NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse<B1>,
|
Response = ServiceResponse<B1>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -389,6 +386,7 @@ where
|
|||||||
mw: F,
|
mw: F,
|
||||||
) -> App<
|
) -> App<
|
||||||
impl NewService<
|
impl NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse<B1>,
|
Response = ServiceResponse<B1>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -405,10 +403,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, B> IntoNewService<AppInit<T, B>, ServerConfig> for App<T, B>
|
impl<T, B> IntoNewService<AppInit<T, B>> for App<T, B>
|
||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse<B>,
|
Response = ServiceResponse<B>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -417,9 +416,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,
|
||||||
@ -431,13 +430,16 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
|
use bytes::Bytes;
|
||||||
use futures::{Future, IntoFuture};
|
use futures::{Future, IntoFuture};
|
||||||
|
|
||||||
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, TestRequest};
|
use crate::test::{
|
||||||
use crate::{web, Error, HttpResponse};
|
block_fn, block_on, call_service, init_service, read_body, TestRequest,
|
||||||
|
};
|
||||||
|
use crate::{web, Error, HttpRequest, HttpResponse};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_default_resource() {
|
fn test_default_resource() {
|
||||||
@ -445,7 +447,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();
|
||||||
@ -482,24 +484,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,
|
||||||
@ -598,4 +600,26 @@ mod tests {
|
|||||||
HeaderValue::from_static("0001")
|
HeaderValue::from_static("0001")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_external_resource() {
|
||||||
|
let mut srv = init_service(
|
||||||
|
App::new()
|
||||||
|
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
|
||||||
|
.route(
|
||||||
|
"/test",
|
||||||
|
web::get().to(|req: HttpRequest| {
|
||||||
|
HttpResponse::Ok().body(format!(
|
||||||
|
"{}",
|
||||||
|
req.url_for("youtube", &["12345"]).unwrap()
|
||||||
|
))
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let req = TestRequest::with_uri("/test").to_request();
|
||||||
|
let resp = call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
let body = read_body(resp);
|
||||||
|
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,16 +2,16 @@ 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};
|
||||||
use actix_service::{fn_service, NewService, Service};
|
use actix_service::{service_fn, NewService, Service};
|
||||||
use futures::future::{ok, Either, FutureResult};
|
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};
|
||||||
@ -31,6 +31,7 @@ type BoxedResponse = Either<
|
|||||||
pub struct AppInit<T, B>
|
pub struct AppInit<T, B>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse<B>,
|
Response = ServiceResponse<B>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -38,23 +39,25 @@ 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>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, B> NewService<ServerConfig> for AppInit<T, B>
|
impl<T, B> NewService for AppInit<T, B>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse<B>,
|
Response = ServiceResponse<B>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
>,
|
>,
|
||||||
{
|
{
|
||||||
|
type Config = ServerConfig;
|
||||||
type Request = Request;
|
type Request = Request;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
@ -65,11 +68,12 @@ where
|
|||||||
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
||||||
// update resource default service
|
// update resource default service
|
||||||
let default = self.default.clone().unwrap_or_else(|| {
|
let default = self.default.clone().unwrap_or_else(|| {
|
||||||
Rc::new(boxed::new_service(fn_service(|req: ServiceRequest| {
|
Rc::new(boxed::new_service(service_fn(|req: ServiceRequest| {
|
||||||
Ok(req.into_response(Response::NotFound().finish()))
|
Ok(req.into_response(Response::NotFound().finish()))
|
||||||
})))
|
})))
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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 +81,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 +94,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 +119,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,14 +143,15 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, B> Future for AppInitResult<T, B>
|
impl<T, B> Future for AppInitResult<T, B>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse<B>,
|
Response = ServiceResponse<B>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -146,16 +162,6 @@ 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);
|
||||||
@ -167,6 +173,7 @@ where
|
|||||||
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 +190,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 +215,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 +223,7 @@ where
|
|||||||
head,
|
head,
|
||||||
self.rmap.clone(),
|
self.rmap.clone(),
|
||||||
self.config.clone(),
|
self.config.clone(),
|
||||||
|
self.data.clone(),
|
||||||
self.pool,
|
self.pool,
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
@ -227,6 +237,7 @@ pub struct AppRoutingFactory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for AppRoutingFactory {
|
impl NewService for AppRoutingFactory {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -385,6 +396,7 @@ impl AppEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for AppEntry {
|
impl NewService for AppEntry {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
138
src/config.rs
138
src/config.rs
@ -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>>,
|
||||||
)>,
|
)>,
|
||||||
|
service_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>,
|
||||||
|
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
AppService {
|
AppService {
|
||||||
config,
|
config,
|
||||||
default,
|
default,
|
||||||
|
service_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,
|
||||||
|
service_data: self.service_data.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,6 +89,15 @@ impl AppService {
|
|||||||
self.default.clone()
|
self.default.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set global route data
|
||||||
|
pub fn set_service_data(&self, extensions: &mut Extensions) -> bool {
|
||||||
|
for f in self.service_data.iter() {
|
||||||
|
f.create(extensions);
|
||||||
|
}
|
||||||
|
!self.service_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,
|
||||||
@ -90,6 +107,7 @@ impl AppService {
|
|||||||
) where
|
) where
|
||||||
F: IntoNewService<S>,
|
F: IntoNewService<S>,
|
||||||
S: NewService<
|
S: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -133,24 +151,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 +165,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()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -193,21 +197,6 @@ impl ServiceConfig {
|
|||||||
self
|
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
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Configure route for a specific path.
|
/// Configure route for a specific path.
|
||||||
///
|
///
|
||||||
/// This is same as `App::route()` method.
|
/// This is same as `App::route()` method.
|
||||||
@ -253,11 +242,12 @@ impl ServiceConfig {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
|
use bytes::Bytes;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::http::{Method, StatusCode};
|
use crate::http::{Method, StatusCode};
|
||||||
use crate::test::{block_on, call_service, init_service, TestRequest};
|
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
|
||||||
use crate::{web, App, HttpResponse};
|
use crate::{web, App, HttpRequest, HttpResponse};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_data() {
|
fn test_data() {
|
||||||
@ -274,31 +264,63 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #[test]
|
||||||
|
// fn test_data_factory() {
|
||||||
|
// let cfg = |cfg: &mut ServiceConfig| {
|
||||||
|
// cfg.data_factory(|| {
|
||||||
|
// sleep(std::time::Duration::from_millis(50)).then(|_| {
|
||||||
|
// println!("READY");
|
||||||
|
// Ok::<_, ()>(10usize)
|
||||||
|
// })
|
||||||
|
// });
|
||||||
|
// };
|
||||||
|
|
||||||
|
// let mut srv =
|
||||||
|
// init_service(App::new().configure(cfg).service(
|
||||||
|
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||||
|
// ));
|
||||||
|
// let req = TestRequest::default().to_request();
|
||||||
|
// let resp = block_on(srv.call(req)).unwrap();
|
||||||
|
// assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
|
// let cfg2 = |cfg: &mut ServiceConfig| {
|
||||||
|
// cfg.data_factory(|| Ok::<_, ()>(10u32));
|
||||||
|
// };
|
||||||
|
// let mut srv = init_service(
|
||||||
|
// App::new()
|
||||||
|
// .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()))
|
||||||
|
// .configure(cfg2),
|
||||||
|
// );
|
||||||
|
// let req = TestRequest::default().to_request();
|
||||||
|
// let resp = block_on(srv.call(req)).unwrap();
|
||||||
|
// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
// }
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_data_factory() {
|
fn test_external_resource() {
|
||||||
let cfg = |cfg: &mut ServiceConfig| {
|
|
||||||
cfg.data_factory(|| Ok::<_, ()>(10usize));
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut srv =
|
|
||||||
init_service(App::new().configure(cfg).service(
|
|
||||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
|
||||||
));
|
|
||||||
let req = TestRequest::default().to_request();
|
|
||||||
let resp = block_on(srv.call(req)).unwrap();
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
|
|
||||||
let cfg2 = |cfg: &mut ServiceConfig| {
|
|
||||||
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()))
|
.configure(|cfg| {
|
||||||
.configure(cfg2),
|
cfg.external_resource(
|
||||||
|
"youtube",
|
||||||
|
"https://youtube.com/watch/{video_id}",
|
||||||
);
|
);
|
||||||
let req = TestRequest::default().to_request();
|
})
|
||||||
let resp = block_on(srv.call(req)).unwrap();
|
.route(
|
||||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
"/test",
|
||||||
|
web::get().to(|req: HttpRequest| {
|
||||||
|
HttpResponse::Ok().body(format!(
|
||||||
|
"{}",
|
||||||
|
req.url_for("youtube", &["12345"]).unwrap()
|
||||||
|
))
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let req = TestRequest::with_uri("/test").to_request();
|
||||||
|
let resp = call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
let body = read_body(resp);
|
||||||
|
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
204
src/data.rs
204
src/data.rs
@ -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))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -96,8 +100,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 +116,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 +156,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 +171,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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -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();
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
use std::cell::RefCell;
|
use std::convert::Infallible;
|
||||||
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};
|
||||||
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};
|
||||||
|
|
||||||
@ -73,7 +72,7 @@ where
|
|||||||
{
|
{
|
||||||
type Request = (T, HttpRequest);
|
type Request = (T, HttpRequest);
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Void;
|
type Error = Infallible;
|
||||||
type Future = HandlerServiceResponse<<R::Future as IntoFuture>::Future>;
|
type Future = HandlerServiceResponse<<R::Future as IntoFuture>::Future>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -100,7 +99,7 @@ where
|
|||||||
T::Error: Into<Error>,
|
T::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Item = ServiceResponse;
|
type Item = ServiceResponse;
|
||||||
type Error = Void;
|
type Error = Infallible;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
match self.fut.poll() {
|
match self.fut.poll() {
|
||||||
@ -193,7 +192,7 @@ where
|
|||||||
{
|
{
|
||||||
type Request = (T, HttpRequest);
|
type Request = (T, HttpRequest);
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Void;
|
type Error = Infallible;
|
||||||
type Future = AsyncHandlerServiceResponse<R::Future>;
|
type Future = AsyncHandlerServiceResponse<R::Future>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -227,7 +226,7 @@ where
|
|||||||
T::Error: Into<Error>,
|
T::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Item = ServiceResponse;
|
type Item = ServiceResponse;
|
||||||
type Error = Void;
|
type Error = Infallible;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
if let Some(ref mut fut) = self.fut2 {
|
if let Some(ref mut fut) = self.fut2 {
|
||||||
@ -267,15 +266,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,
|
||||||
}
|
}
|
||||||
@ -284,9 +281,13 @@ impl<T: FromRequest, S> Extract<T, S> {
|
|||||||
|
|
||||||
impl<T: FromRequest, S> NewService for Extract<T, S>
|
impl<T: FromRequest, S> NewService for Extract<T, S>
|
||||||
where
|
where
|
||||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>
|
S: Service<
|
||||||
+ Clone,
|
Request = (T, HttpRequest),
|
||||||
|
Response = ServiceResponse,
|
||||||
|
Error = Infallible,
|
||||||
|
> + Clone,
|
||||||
{
|
{
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = (Error, ServiceRequest);
|
type Error = (Error, ServiceRequest);
|
||||||
@ -297,22 +298,23 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: FromRequest, S> Service for ExtractService<T, S>
|
impl<T: FromRequest, S> Service for ExtractService<T, S>
|
||||||
where
|
where
|
||||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>
|
S: Service<
|
||||||
+ Clone,
|
Request = (T, HttpRequest),
|
||||||
|
Response = ServiceResponse,
|
||||||
|
Error = Infallible,
|
||||||
|
> + Clone,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
@ -324,8 +326,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 {
|
||||||
@ -346,7 +347,11 @@ pub struct ExtractResponse<T: FromRequest, S: Service> {
|
|||||||
|
|
||||||
impl<T: FromRequest, S> Future for ExtractResponse<T, S>
|
impl<T: FromRequest, S> Future for ExtractResponse<T, S>
|
||||||
where
|
where
|
||||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>,
|
S: Service<
|
||||||
|
Request = (T, HttpRequest),
|
||||||
|
Response = ServiceResponse,
|
||||||
|
Error = Infallible,
|
||||||
|
>,
|
||||||
{
|
{
|
||||||
type Item = ServiceResponse;
|
type Item = ServiceResponse;
|
||||||
type Error = (Error, ServiceRequest);
|
type Error = (Error, ServiceRequest);
|
||||||
|
@ -136,7 +136,9 @@ pub mod dev {
|
|||||||
pub use crate::config::{AppConfig, AppService};
|
pub use crate::config::{AppConfig, AppService};
|
||||||
pub use crate::info::ConnectionInfo;
|
pub use crate::info::ConnectionInfo;
|
||||||
pub use crate::rmap::ResourceMap;
|
pub use crate::rmap::ResourceMap;
|
||||||
pub use crate::service::{HttpServiceFactory, ServiceRequest, ServiceResponse};
|
pub use crate::service::{
|
||||||
|
HttpServiceFactory, ServiceRequest, ServiceResponse, WebService,
|
||||||
|
};
|
||||||
pub use crate::types::form::UrlEncoded;
|
pub use crate::types::form::UrlEncoded;
|
||||||
pub use crate::types::json::JsonBody;
|
pub use crate::types::json::JsonBody;
|
||||||
pub use crate::types::readlines::Readlines;
|
pub use crate::types::readlines::Readlines;
|
||||||
|
@ -6,7 +6,7 @@ use std::str::FromStr;
|
|||||||
use actix_http::body::MessageBody;
|
use actix_http::body::MessageBody;
|
||||||
use actix_http::encoding::Encoder;
|
use actix_http::encoding::Encoder;
|
||||||
use actix_http::http::header::{ContentEncoding, ACCEPT_ENCODING};
|
use actix_http::http::header::{ContentEncoding, ACCEPT_ENCODING};
|
||||||
use actix_http::{Response, ResponseBuilder};
|
use actix_http::{Error, Response, ResponseBuilder};
|
||||||
use actix_service::{Service, Transform};
|
use actix_service::{Service, Transform};
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
@ -71,11 +71,11 @@ impl Default for Compress {
|
|||||||
impl<S, B> Transform<S> for Compress
|
impl<S, B> Transform<S> for Compress
|
||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<Encoder<B>>;
|
type Response = ServiceResponse<Encoder<B>>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = CompressMiddleware<S>;
|
type Transform = CompressMiddleware<S>;
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
@ -96,11 +96,11 @@ pub struct CompressMiddleware<S> {
|
|||||||
impl<S, B> Service for CompressMiddleware<S>
|
impl<S, B> Service for CompressMiddleware<S>
|
||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<Encoder<B>>;
|
type Response = ServiceResponse<Encoder<B>>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type Future = CompressResponse<S, B>;
|
type Future = CompressResponse<S, B>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -141,10 +141,10 @@ where
|
|||||||
impl<S, B> Future for CompressResponse<S, B>
|
impl<S, B> Future for CompressResponse<S, B>
|
||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
{
|
{
|
||||||
type Item = ServiceResponse<Encoder<B>>;
|
type Item = ServiceResponse<Encoder<B>>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
let resp = futures::try_ready!(self.fut.poll());
|
let resp = futures::try_ready!(self.fut.poll());
|
||||||
|
@ -47,7 +47,7 @@ use futures::future::{ok, Either, Future, FutureResult};
|
|||||||
use futures::Poll;
|
use futures::Poll;
|
||||||
|
|
||||||
use crate::dev::RequestHead;
|
use crate::dev::RequestHead;
|
||||||
use crate::error::{ResponseError, Result};
|
use crate::error::{Error, ResponseError, Result};
|
||||||
use crate::http::header::{self, HeaderName, HeaderValue};
|
use crate::http::header::{self, HeaderName, HeaderValue};
|
||||||
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
use crate::service::{ServiceRequest, ServiceResponse};
|
||||||
@ -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,
|
||||||
@ -477,9 +470,8 @@ fn cors<'a>(
|
|||||||
|
|
||||||
impl<S, B> IntoTransform<CorsFactory, S> for Cors
|
impl<S, B> IntoTransform<CorsFactory, S> for Cors
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
fn into_transform(self) -> CorsFactory {
|
fn into_transform(self) -> CorsFactory {
|
||||||
@ -539,14 +531,13 @@ pub struct CorsFactory {
|
|||||||
|
|
||||||
impl<S, B> Transform<S> for CorsFactory
|
impl<S, B> Transform<S> for CorsFactory
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = CorsMiddleware<S>;
|
type Transform = CorsMiddleware<S>;
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
@ -663,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(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -680,17 +674,16 @@ impl Inner {
|
|||||||
|
|
||||||
impl<S, B> Service for CorsMiddleware<S>
|
impl<S, B> Service for CorsMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
FutureResult<Self::Response, Self::Error>,
|
FutureResult<Self::Response, Error>,
|
||||||
Either<S::Future, Box<Future<Item = Self::Response, Error = Self::Error>>>,
|
Either<S::Future, Box<Future<Item = Self::Response, Error = Error>>>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -812,22 +805,26 @@ where
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::{FnService, Transform};
|
use actix_service::{IntoService, Transform};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::test::{self, block_on, TestRequest};
|
use crate::test::{self, block_on, TestRequest};
|
||||||
|
|
||||||
impl Cors {
|
impl Cors {
|
||||||
fn finish<S, B>(self, srv: S) -> CorsMiddleware<S>
|
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>
|
F: IntoService<S>,
|
||||||
+ 'static,
|
S: Service<
|
||||||
|
Request = ServiceRequest,
|
||||||
|
Response = ServiceResponse<B>,
|
||||||
|
Error = Error,
|
||||||
|
> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
block_on(
|
block_on(
|
||||||
IntoTransform::<CorsFactory, S>::into_transform(self).new_transform(srv),
|
IntoTransform::<CorsFactory, S>::into_transform(self)
|
||||||
|
.new_transform(srv.into_service()),
|
||||||
)
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
@ -875,6 +872,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());
|
||||||
@ -888,7 +886,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")
|
||||||
@ -1067,11 +1065,11 @@ mod tests {
|
|||||||
.allowed_headers(exposed_headers.clone())
|
.allowed_headers(exposed_headers.clone())
|
||||||
.expose_headers(exposed_headers.clone())
|
.expose_headers(exposed_headers.clone())
|
||||||
.allowed_header(header::CONTENT_TYPE)
|
.allowed_header(header::CONTENT_TYPE)
|
||||||
.finish(FnService::new(move |req: ServiceRequest| {
|
.finish(|req: ServiceRequest| {
|
||||||
req.into_response(
|
req.into_response(
|
||||||
HttpResponse::Ok().header(header::VARY, "Accept").finish(),
|
HttpResponse::Ok().header(header::VARY, "Accept").finish(),
|
||||||
)
|
)
|
||||||
}));
|
});
|
||||||
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)
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
|
@ -8,6 +8,7 @@ use futures::{Future, Poll};
|
|||||||
use crate::http::header::{HeaderName, HeaderValue, CONTENT_TYPE};
|
use crate::http::header::{HeaderName, HeaderValue, CONTENT_TYPE};
|
||||||
use crate::http::{HeaderMap, HttpTryFrom};
|
use crate::http::{HeaderMap, HttpTryFrom};
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
use crate::service::{ServiceRequest, ServiceResponse};
|
||||||
|
use crate::Error;
|
||||||
|
|
||||||
/// `Middleware` for setting default response headers.
|
/// `Middleware` for setting default response headers.
|
||||||
///
|
///
|
||||||
@ -87,12 +88,12 @@ impl DefaultHeaders {
|
|||||||
|
|
||||||
impl<S, B> Transform<S> for DefaultHeaders
|
impl<S, B> Transform<S> for DefaultHeaders
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = DefaultHeadersMiddleware<S>;
|
type Transform = DefaultHeadersMiddleware<S>;
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
@ -112,12 +113,12 @@ pub struct DefaultHeadersMiddleware<S> {
|
|||||||
|
|
||||||
impl<S, B> Service for DefaultHeadersMiddleware<S>
|
impl<S, B> Service for DefaultHeadersMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -149,7 +150,7 @@ where
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::FnService;
|
use actix_service::IntoService;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::dev::ServiceRequest;
|
use crate::dev::ServiceRequest;
|
||||||
@ -171,13 +172,13 @@ mod tests {
|
|||||||
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
|
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
|
||||||
|
|
||||||
let req = TestRequest::default().to_srv_request();
|
let req = TestRequest::default().to_srv_request();
|
||||||
let srv = FnService::new(|req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
req.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish())
|
req.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish())
|
||||||
});
|
};
|
||||||
let mut mw = block_on(
|
let mut mw = block_on(
|
||||||
DefaultHeaders::new()
|
DefaultHeaders::new()
|
||||||
.header(CONTENT_TYPE, "0001")
|
.header(CONTENT_TYPE, "0001")
|
||||||
.new_transform(srv),
|
.new_transform(srv.into_service()),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let resp = block_on(mw.call(req)).unwrap();
|
let resp = block_on(mw.call(req)).unwrap();
|
||||||
@ -186,11 +187,13 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_content_type() {
|
fn test_content_type() {
|
||||||
let srv = FnService::new(|req: ServiceRequest| {
|
let srv = |req: ServiceRequest| req.into_response(HttpResponse::Ok().finish());
|
||||||
req.into_response(HttpResponse::Ok().finish())
|
let mut mw = block_on(
|
||||||
});
|
DefaultHeaders::new()
|
||||||
let mut mw =
|
.content_type()
|
||||||
block_on(DefaultHeaders::new().content_type().new_transform(srv)).unwrap();
|
.new_transform(srv.into_service()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let req = TestRequest::default().to_srv_request();
|
let req = TestRequest::default().to_srv_request();
|
||||||
let resp = block_on(mw.call(req)).unwrap();
|
let resp = block_on(mw.call(req)).unwrap();
|
||||||
|
@ -85,7 +85,6 @@ impl<S, B> Transform<S> for ErrorHandlers<B>
|
|||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
@ -113,7 +112,6 @@ impl<S, B> Service for ErrorHandlersMiddleware<S, B>
|
|||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
@ -144,7 +142,7 @@ where
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::FnService;
|
use actix_service::IntoService;
|
||||||
use futures::future::ok;
|
use futures::future::ok;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -161,14 +159,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_handler() {
|
fn test_handler() {
|
||||||
let srv = FnService::new(|req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
req.into_response(HttpResponse::InternalServerError().finish())
|
req.into_response(HttpResponse::InternalServerError().finish())
|
||||||
});
|
};
|
||||||
|
|
||||||
let mut mw = test::block_on(
|
let mut mw = test::block_on(
|
||||||
ErrorHandlers::new()
|
ErrorHandlers::new()
|
||||||
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500)
|
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500)
|
||||||
.new_transform(srv),
|
.new_transform(srv.into_service()),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@ -187,14 +185,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_handler_async() {
|
fn test_handler_async() {
|
||||||
let srv = FnService::new(|req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
req.into_response(HttpResponse::InternalServerError().finish())
|
req.into_response(HttpResponse::InternalServerError().finish())
|
||||||
});
|
};
|
||||||
|
|
||||||
let mut mw = test::block_on(
|
let mut mw = test::block_on(
|
||||||
ErrorHandlers::new()
|
ErrorHandlers::new()
|
||||||
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500_async)
|
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500_async)
|
||||||
.new_transform(srv),
|
.new_transform(srv.into_service()),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
@ -49,10 +49,12 @@
|
|||||||
//! ```
|
//! ```
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
use std::time::SystemTime;
|
||||||
|
|
||||||
use actix_service::{Service, Transform};
|
use actix_service::{Service, Transform};
|
||||||
use futures::future::{ok, Either, FutureResult};
|
use futures::future::{ok, Either, FutureResult};
|
||||||
use futures::{Future, IntoFuture, Poll};
|
use futures::{Future, IntoFuture, Poll};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
use time::Duration;
|
use time::Duration;
|
||||||
|
|
||||||
use crate::cookie::{Cookie, CookieJar, Key, SameSite};
|
use crate::cookie::{Cookie, CookieJar, Key, SameSite};
|
||||||
@ -201,15 +203,15 @@ impl<T> IdentityService<T> {
|
|||||||
|
|
||||||
impl<S, T, B> Transform<S> for IdentityService<T>
|
impl<S, T, B> Transform<S> for IdentityService<T>
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>> + 'static,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
|
||||||
|
+ 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
T: IdentityPolicy,
|
T: IdentityPolicy,
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = IdentityServiceMiddleware<S, T>;
|
type Transform = IdentityServiceMiddleware<S, T>;
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
@ -231,14 +233,14 @@ pub struct IdentityServiceMiddleware<S, T> {
|
|||||||
impl<S, T, B> Service for IdentityServiceMiddleware<S, T>
|
impl<S, T, B> Service for IdentityServiceMiddleware<S, T>
|
||||||
where
|
where
|
||||||
B: 'static,
|
B: 'static,
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>> + 'static,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>
|
||||||
|
+ 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
T: IdentityPolicy,
|
T: IdentityPolicy,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -284,36 +286,64 @@ where
|
|||||||
|
|
||||||
struct CookieIdentityInner {
|
struct CookieIdentityInner {
|
||||||
key: Key,
|
key: Key,
|
||||||
|
key_v2: Key,
|
||||||
name: String,
|
name: String,
|
||||||
path: String,
|
path: String,
|
||||||
domain: Option<String>,
|
domain: Option<String>,
|
||||||
secure: bool,
|
secure: bool,
|
||||||
max_age: Option<Duration>,
|
max_age: Option<Duration>,
|
||||||
same_site: Option<SameSite>,
|
same_site: Option<SameSite>,
|
||||||
|
visit_deadline: Option<Duration>,
|
||||||
|
login_deadline: Option<Duration>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize, Debug)]
|
||||||
|
struct CookieValue {
|
||||||
|
identity: String,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
login_timestamp: Option<SystemTime>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
visit_timestamp: Option<SystemTime>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct CookieIdentityExtention {
|
||||||
|
login_timestamp: Option<SystemTime>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CookieIdentityInner {
|
impl CookieIdentityInner {
|
||||||
fn new(key: &[u8]) -> CookieIdentityInner {
|
fn new(key: &[u8]) -> CookieIdentityInner {
|
||||||
|
let key_v2: Vec<u8> =
|
||||||
|
key.iter().chain([1, 0, 0, 0].iter()).map(|e| *e).collect();
|
||||||
CookieIdentityInner {
|
CookieIdentityInner {
|
||||||
key: Key::from_master(key),
|
key: Key::from_master(key),
|
||||||
|
key_v2: Key::from_master(&key_v2),
|
||||||
name: "actix-identity".to_owned(),
|
name: "actix-identity".to_owned(),
|
||||||
path: "/".to_owned(),
|
path: "/".to_owned(),
|
||||||
domain: None,
|
domain: None,
|
||||||
secure: true,
|
secure: true,
|
||||||
max_age: None,
|
max_age: None,
|
||||||
same_site: None,
|
same_site: None,
|
||||||
|
visit_deadline: None,
|
||||||
|
login_deadline: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_cookie<B>(
|
fn set_cookie<B>(
|
||||||
&self,
|
&self,
|
||||||
resp: &mut ServiceResponse<B>,
|
resp: &mut ServiceResponse<B>,
|
||||||
id: Option<String>,
|
value: Option<CookieValue>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let some = id.is_some();
|
let add_cookie = value.is_some();
|
||||||
{
|
let val = value.map(|val| {
|
||||||
let id = id.unwrap_or_else(String::new);
|
if !self.legacy_supported() {
|
||||||
let mut cookie = Cookie::new(self.name.clone(), id);
|
serde_json::to_string(&val)
|
||||||
|
} else {
|
||||||
|
Ok(val.identity)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let mut cookie =
|
||||||
|
Cookie::new(self.name.clone(), val.unwrap_or_else(|| Ok(String::new()))?);
|
||||||
cookie.set_path(self.path.clone());
|
cookie.set_path(self.path.clone());
|
||||||
cookie.set_secure(self.secure);
|
cookie.set_secure(self.secure);
|
||||||
cookie.set_http_only(true);
|
cookie.set_http_only(true);
|
||||||
@ -331,37 +361,74 @@ impl CookieIdentityInner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut jar = CookieJar::new();
|
let mut jar = CookieJar::new();
|
||||||
if some {
|
let key = if self.legacy_supported() {
|
||||||
jar.private(&self.key).add(cookie);
|
&self.key
|
||||||
|
} else {
|
||||||
|
&self.key_v2
|
||||||
|
};
|
||||||
|
if add_cookie {
|
||||||
|
jar.private(&key).add(cookie);
|
||||||
} else {
|
} else {
|
||||||
jar.add_original(cookie.clone());
|
jar.add_original(cookie.clone());
|
||||||
jar.private(&self.key).remove(cookie);
|
jar.private(&key).remove(cookie);
|
||||||
}
|
}
|
||||||
|
|
||||||
for cookie in jar.delta() {
|
for cookie in jar.delta() {
|
||||||
let val = HeaderValue::from_str(&cookie.to_string())?;
|
let val = HeaderValue::from_str(&cookie.to_string())?;
|
||||||
resp.headers_mut().append(header::SET_COOKIE, val);
|
resp.headers_mut().append(header::SET_COOKIE, val);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load(&self, req: &ServiceRequest) -> Option<String> {
|
fn load(&self, req: &ServiceRequest) -> Option<CookieValue> {
|
||||||
if let Ok(cookies) = req.cookies() {
|
let cookie = req.cookie(&self.name)?;
|
||||||
for cookie in cookies.iter() {
|
|
||||||
if cookie.name() == self.name {
|
|
||||||
let mut jar = CookieJar::new();
|
let mut jar = CookieJar::new();
|
||||||
jar.add_original(cookie.clone());
|
jar.add_original(cookie.clone());
|
||||||
|
let res = if self.legacy_supported() {
|
||||||
let cookie_opt = jar.private(&self.key).get(&self.name);
|
jar.private(&self.key).get(&self.name).map(|n| CookieValue {
|
||||||
if let Some(cookie) = cookie_opt {
|
identity: n.value().to_string(),
|
||||||
return Some(cookie.value().into());
|
login_timestamp: None,
|
||||||
}
|
visit_timestamp: None,
|
||||||
}
|
})
|
||||||
}
|
} else {
|
||||||
}
|
|
||||||
None
|
None
|
||||||
|
};
|
||||||
|
res.or_else(|| {
|
||||||
|
jar.private(&self.key_v2)
|
||||||
|
.get(&self.name)
|
||||||
|
.and_then(|c| self.parse(c))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(&self, cookie: Cookie) -> Option<CookieValue> {
|
||||||
|
let value: CookieValue = serde_json::from_str(cookie.value()).ok()?;
|
||||||
|
let now = SystemTime::now();
|
||||||
|
if let Some(visit_deadline) = self.visit_deadline {
|
||||||
|
if now.duration_since(value.visit_timestamp?).ok()?
|
||||||
|
> visit_deadline.to_std().ok()?
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(login_deadline) = self.login_deadline {
|
||||||
|
if now.duration_since(value.login_timestamp?).ok()?
|
||||||
|
> login_deadline.to_std().ok()?
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_supported(&self) -> bool {
|
||||||
|
self.visit_deadline.is_none() && self.login_deadline.is_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn always_update_cookie(&self) -> bool {
|
||||||
|
self.visit_deadline.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn requires_oob_data(&self) -> bool {
|
||||||
|
self.login_deadline.is_some()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -443,6 +510,22 @@ impl CookieIdentityPolicy {
|
|||||||
Rc::get_mut(&mut self.0).unwrap().same_site = Some(same_site);
|
Rc::get_mut(&mut self.0).unwrap().same_site = Some(same_site);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Accepts only users whose cookie has been seen before the given deadline
|
||||||
|
///
|
||||||
|
/// By default visit deadline is disabled.
|
||||||
|
pub fn visit_deadline(mut self, value: Duration) -> CookieIdentityPolicy {
|
||||||
|
Rc::get_mut(&mut self.0).unwrap().visit_deadline = Some(value);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accepts only users which has been authenticated before the given deadline
|
||||||
|
///
|
||||||
|
/// By default login deadline is disabled.
|
||||||
|
pub fn login_deadline(mut self, value: Duration) -> CookieIdentityPolicy {
|
||||||
|
Rc::get_mut(&mut self.0).unwrap().login_deadline = Some(value);
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IdentityPolicy for CookieIdentityPolicy {
|
impl IdentityPolicy for CookieIdentityPolicy {
|
||||||
@ -450,7 +533,19 @@ impl IdentityPolicy for CookieIdentityPolicy {
|
|||||||
type ResponseFuture = Result<(), Error>;
|
type ResponseFuture = Result<(), Error>;
|
||||||
|
|
||||||
fn from_request(&self, req: &mut ServiceRequest) -> Self::Future {
|
fn from_request(&self, req: &mut ServiceRequest) -> Self::Future {
|
||||||
Ok(self.0.load(req))
|
Ok(self.0.load(req).map(
|
||||||
|
|CookieValue {
|
||||||
|
identity,
|
||||||
|
login_timestamp,
|
||||||
|
..
|
||||||
|
}| {
|
||||||
|
if self.0.requires_oob_data() {
|
||||||
|
req.extensions_mut()
|
||||||
|
.insert(CookieIdentityExtention { login_timestamp });
|
||||||
|
}
|
||||||
|
identity
|
||||||
|
},
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn to_response<B>(
|
fn to_response<B>(
|
||||||
@ -459,9 +554,36 @@ impl IdentityPolicy for CookieIdentityPolicy {
|
|||||||
changed: bool,
|
changed: bool,
|
||||||
res: &mut ServiceResponse<B>,
|
res: &mut ServiceResponse<B>,
|
||||||
) -> Self::ResponseFuture {
|
) -> Self::ResponseFuture {
|
||||||
if changed {
|
let _ = if changed {
|
||||||
let _ = self.0.set_cookie(res, id);
|
let login_timestamp = SystemTime::now();
|
||||||
|
self.0.set_cookie(
|
||||||
|
res,
|
||||||
|
id.map(|identity| CookieValue {
|
||||||
|
identity,
|
||||||
|
login_timestamp: self.0.login_deadline.map(|_| login_timestamp),
|
||||||
|
visit_timestamp: self.0.visit_deadline.map(|_| login_timestamp),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
} else if self.0.always_update_cookie() && id.is_some() {
|
||||||
|
let visit_timestamp = SystemTime::now();
|
||||||
|
let mut login_timestamp = None;
|
||||||
|
if self.0.requires_oob_data() {
|
||||||
|
let CookieIdentityExtention {
|
||||||
|
login_timestamp: lt,
|
||||||
|
} = res.request().extensions_mut().remove().unwrap();
|
||||||
|
login_timestamp = lt;
|
||||||
}
|
}
|
||||||
|
self.0.set_cookie(
|
||||||
|
res,
|
||||||
|
Some(CookieValue {
|
||||||
|
identity: id.unwrap(),
|
||||||
|
login_timestamp,
|
||||||
|
visit_timestamp: self.0.visit_deadline.map(|_| visit_timestamp),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -473,14 +595,20 @@ mod tests {
|
|||||||
use crate::test::{self, TestRequest};
|
use crate::test::{self, TestRequest};
|
||||||
use crate::{web, App, HttpResponse};
|
use crate::{web, App, HttpResponse};
|
||||||
|
|
||||||
|
use std::borrow::Borrow;
|
||||||
|
|
||||||
|
const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
|
||||||
|
const COOKIE_NAME: &'static str = "actix_auth";
|
||||||
|
const COOKIE_LOGIN: &'static str = "test";
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_identity() {
|
fn test_identity() {
|
||||||
let mut srv = test::init_service(
|
let mut srv = test::init_service(
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(IdentityService::new(
|
.wrap(IdentityService::new(
|
||||||
CookieIdentityPolicy::new(&[0; 32])
|
CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
|
||||||
.domain("www.rust-lang.org")
|
.domain("www.rust-lang.org")
|
||||||
.name("actix_auth")
|
.name(COOKIE_NAME)
|
||||||
.path("/")
|
.path("/")
|
||||||
.secure(true),
|
.secure(true),
|
||||||
))
|
))
|
||||||
@ -492,7 +620,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
.service(web::resource("/login").to(|id: Identity| {
|
.service(web::resource("/login").to(|id: Identity| {
|
||||||
id.remember("test".to_string());
|
id.remember(COOKIE_LOGIN.to_string());
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
}))
|
}))
|
||||||
.service(web::resource("/logout").to(|id: Identity| {
|
.service(web::resource("/logout").to(|id: Identity| {
|
||||||
@ -537,9 +665,9 @@ mod tests {
|
|||||||
let mut srv = test::init_service(
|
let mut srv = test::init_service(
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(IdentityService::new(
|
.wrap(IdentityService::new(
|
||||||
CookieIdentityPolicy::new(&[0; 32])
|
CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
|
||||||
.domain("www.rust-lang.org")
|
.domain("www.rust-lang.org")
|
||||||
.name("actix_auth")
|
.name(COOKIE_NAME)
|
||||||
.path("/")
|
.path("/")
|
||||||
.max_age_time(duration)
|
.max_age_time(duration)
|
||||||
.secure(true),
|
.secure(true),
|
||||||
@ -563,9 +691,9 @@ mod tests {
|
|||||||
let mut srv = test::init_service(
|
let mut srv = test::init_service(
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(IdentityService::new(
|
.wrap(IdentityService::new(
|
||||||
CookieIdentityPolicy::new(&[0; 32])
|
CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
|
||||||
.domain("www.rust-lang.org")
|
.domain("www.rust-lang.org")
|
||||||
.name("actix_auth")
|
.name(COOKIE_NAME)
|
||||||
.path("/")
|
.path("/")
|
||||||
.max_age(seconds)
|
.max_age(seconds)
|
||||||
.secure(true),
|
.secure(true),
|
||||||
@ -582,4 +710,328 @@ mod tests {
|
|||||||
let c = resp.response().cookies().next().unwrap().to_owned();
|
let c = resp.response().cookies().next().unwrap().to_owned();
|
||||||
assert_eq!(Duration::seconds(seconds as i64), c.max_age().unwrap());
|
assert_eq!(Duration::seconds(seconds as i64), c.max_age().unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn create_identity_server<
|
||||||
|
F: Fn(CookieIdentityPolicy) -> CookieIdentityPolicy + Sync + Send + Clone + 'static,
|
||||||
|
>(
|
||||||
|
f: F,
|
||||||
|
) -> impl actix_service::Service<
|
||||||
|
Request = actix_http::Request,
|
||||||
|
Response = ServiceResponse<actix_http::body::Body>,
|
||||||
|
Error = actix_http::Error,
|
||||||
|
> {
|
||||||
|
test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(IdentityService::new(f(CookieIdentityPolicy::new(
|
||||||
|
&COOKIE_KEY_MASTER,
|
||||||
|
)
|
||||||
|
.secure(false)
|
||||||
|
.name(COOKIE_NAME))))
|
||||||
|
.service(web::resource("/").to(|id: Identity| {
|
||||||
|
let identity = id.identity();
|
||||||
|
if identity.is_none() {
|
||||||
|
id.remember(COOKIE_LOGIN.to_string())
|
||||||
|
}
|
||||||
|
web::Json(identity)
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_login_cookie(identity: &'static str) -> Cookie<'static> {
|
||||||
|
let mut jar = CookieJar::new();
|
||||||
|
jar.private(&Key::from_master(&COOKIE_KEY_MASTER))
|
||||||
|
.add(Cookie::new(COOKIE_NAME, identity));
|
||||||
|
jar.get(COOKIE_NAME).unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn login_cookie(
|
||||||
|
identity: &'static str,
|
||||||
|
login_timestamp: Option<SystemTime>,
|
||||||
|
visit_timestamp: Option<SystemTime>,
|
||||||
|
) -> Cookie<'static> {
|
||||||
|
let mut jar = CookieJar::new();
|
||||||
|
let key: Vec<u8> = COOKIE_KEY_MASTER
|
||||||
|
.iter()
|
||||||
|
.chain([1, 0, 0, 0].iter())
|
||||||
|
.map(|e| *e)
|
||||||
|
.collect();
|
||||||
|
jar.private(&Key::from_master(&key)).add(Cookie::new(
|
||||||
|
COOKIE_NAME,
|
||||||
|
serde_json::to_string(&CookieValue {
|
||||||
|
identity: identity.to_string(),
|
||||||
|
login_timestamp,
|
||||||
|
visit_timestamp,
|
||||||
|
})
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
jar.get(COOKIE_NAME).unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_logged_in(response: &mut ServiceResponse, identity: Option<&str>) {
|
||||||
|
use bytes::BytesMut;
|
||||||
|
use futures::Stream;
|
||||||
|
let bytes =
|
||||||
|
test::block_on(response.take_body().fold(BytesMut::new(), |mut b, c| {
|
||||||
|
b.extend(c);
|
||||||
|
Ok::<_, Error>(b)
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let resp: Option<String> = serde_json::from_slice(&bytes[..]).unwrap();
|
||||||
|
assert_eq!(resp.as_ref().map(|s| s.borrow()), identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_legacy_login_cookie(response: &mut ServiceResponse, identity: &str) {
|
||||||
|
let mut cookies = CookieJar::new();
|
||||||
|
for cookie in response.headers().get_all(header::SET_COOKIE) {
|
||||||
|
cookies.add(Cookie::parse(cookie.to_str().unwrap().to_string()).unwrap());
|
||||||
|
}
|
||||||
|
let cookie = cookies
|
||||||
|
.private(&Key::from_master(&COOKIE_KEY_MASTER))
|
||||||
|
.get(COOKIE_NAME)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(cookie.value(), identity);
|
||||||
|
}
|
||||||
|
|
||||||
|
enum LoginTimestampCheck {
|
||||||
|
NoTimestamp,
|
||||||
|
NewTimestamp,
|
||||||
|
OldTimestamp(SystemTime),
|
||||||
|
}
|
||||||
|
|
||||||
|
enum VisitTimeStampCheck {
|
||||||
|
NoTimestamp,
|
||||||
|
NewTimestamp,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_login_cookie(
|
||||||
|
response: &mut ServiceResponse,
|
||||||
|
identity: &str,
|
||||||
|
login_timestamp: LoginTimestampCheck,
|
||||||
|
visit_timestamp: VisitTimeStampCheck,
|
||||||
|
) {
|
||||||
|
let mut cookies = CookieJar::new();
|
||||||
|
for cookie in response.headers().get_all(header::SET_COOKIE) {
|
||||||
|
cookies.add(Cookie::parse(cookie.to_str().unwrap().to_string()).unwrap());
|
||||||
|
}
|
||||||
|
let key: Vec<u8> = COOKIE_KEY_MASTER
|
||||||
|
.iter()
|
||||||
|
.chain([1, 0, 0, 0].iter())
|
||||||
|
.map(|e| *e)
|
||||||
|
.collect();
|
||||||
|
let cookie = cookies
|
||||||
|
.private(&Key::from_master(&key))
|
||||||
|
.get(COOKIE_NAME)
|
||||||
|
.unwrap();
|
||||||
|
let cv: CookieValue = serde_json::from_str(cookie.value()).unwrap();
|
||||||
|
assert_eq!(cv.identity, identity);
|
||||||
|
let now = SystemTime::now();
|
||||||
|
let t30sec_ago = now - Duration::seconds(30).to_std().unwrap();
|
||||||
|
match login_timestamp {
|
||||||
|
LoginTimestampCheck::NoTimestamp => assert_eq!(cv.login_timestamp, None),
|
||||||
|
LoginTimestampCheck::NewTimestamp => assert!(
|
||||||
|
t30sec_ago <= cv.login_timestamp.unwrap()
|
||||||
|
&& cv.login_timestamp.unwrap() <= now
|
||||||
|
),
|
||||||
|
LoginTimestampCheck::OldTimestamp(old_timestamp) => {
|
||||||
|
assert_eq!(cv.login_timestamp, Some(old_timestamp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match visit_timestamp {
|
||||||
|
VisitTimeStampCheck::NoTimestamp => assert_eq!(cv.visit_timestamp, None),
|
||||||
|
VisitTimeStampCheck::NewTimestamp => assert!(
|
||||||
|
t30sec_ago <= cv.visit_timestamp.unwrap()
|
||||||
|
&& cv.visit_timestamp.unwrap() <= now
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_no_login_cookie(response: &mut ServiceResponse) {
|
||||||
|
let mut cookies = CookieJar::new();
|
||||||
|
for cookie in response.headers().get_all(header::SET_COOKIE) {
|
||||||
|
cookies.add(Cookie::parse(cookie.to_str().unwrap().to_string()).unwrap());
|
||||||
|
}
|
||||||
|
assert!(cookies.get(COOKIE_NAME).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_legacy_cookie_is_set() {
|
||||||
|
let mut srv = create_identity_server(|c| c);
|
||||||
|
let mut resp =
|
||||||
|
test::call_service(&mut srv, TestRequest::with_uri("/").to_request());
|
||||||
|
assert_logged_in(&mut resp, None);
|
||||||
|
assert_legacy_login_cookie(&mut resp, COOKIE_LOGIN);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_legacy_cookie_works() {
|
||||||
|
let mut srv = create_identity_server(|c| c);
|
||||||
|
let cookie = legacy_login_cookie(COOKIE_LOGIN);
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, Some(COOKIE_LOGIN));
|
||||||
|
assert_no_login_cookie(&mut resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_legacy_cookie_rejected_if_visit_timestamp_needed() {
|
||||||
|
let mut srv = create_identity_server(|c| c.visit_deadline(Duration::days(90)));
|
||||||
|
let cookie = legacy_login_cookie(COOKIE_LOGIN);
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, None);
|
||||||
|
assert_login_cookie(
|
||||||
|
&mut resp,
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
LoginTimestampCheck::NoTimestamp,
|
||||||
|
VisitTimeStampCheck::NewTimestamp,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_legacy_cookie_rejected_if_login_timestamp_needed() {
|
||||||
|
let mut srv = create_identity_server(|c| c.login_deadline(Duration::days(90)));
|
||||||
|
let cookie = legacy_login_cookie(COOKIE_LOGIN);
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, None);
|
||||||
|
assert_login_cookie(
|
||||||
|
&mut resp,
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
LoginTimestampCheck::NewTimestamp,
|
||||||
|
VisitTimeStampCheck::NoTimestamp,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_cookie_rejected_if_login_timestamp_needed() {
|
||||||
|
let mut srv = create_identity_server(|c| c.login_deadline(Duration::days(90)));
|
||||||
|
let cookie = login_cookie(COOKIE_LOGIN, None, Some(SystemTime::now()));
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, None);
|
||||||
|
assert_login_cookie(
|
||||||
|
&mut resp,
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
LoginTimestampCheck::NewTimestamp,
|
||||||
|
VisitTimeStampCheck::NoTimestamp,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_cookie_rejected_if_visit_timestamp_needed() {
|
||||||
|
let mut srv = create_identity_server(|c| c.visit_deadline(Duration::days(90)));
|
||||||
|
let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, None);
|
||||||
|
assert_login_cookie(
|
||||||
|
&mut resp,
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
LoginTimestampCheck::NoTimestamp,
|
||||||
|
VisitTimeStampCheck::NewTimestamp,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_cookie_rejected_if_login_timestamp_too_old() {
|
||||||
|
let mut srv = create_identity_server(|c| c.login_deadline(Duration::days(90)));
|
||||||
|
let cookie = login_cookie(
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
Some(SystemTime::now() - Duration::days(180).to_std().unwrap()),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, None);
|
||||||
|
assert_login_cookie(
|
||||||
|
&mut resp,
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
LoginTimestampCheck::NewTimestamp,
|
||||||
|
VisitTimeStampCheck::NoTimestamp,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_cookie_rejected_if_visit_timestamp_too_old() {
|
||||||
|
let mut srv = create_identity_server(|c| c.visit_deadline(Duration::days(90)));
|
||||||
|
let cookie = login_cookie(
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
None,
|
||||||
|
Some(SystemTime::now() - Duration::days(180).to_std().unwrap()),
|
||||||
|
);
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, None);
|
||||||
|
assert_login_cookie(
|
||||||
|
&mut resp,
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
LoginTimestampCheck::NoTimestamp,
|
||||||
|
VisitTimeStampCheck::NewTimestamp,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_cookie_not_updated_on_login_deadline() {
|
||||||
|
let mut srv = create_identity_server(|c| c.login_deadline(Duration::days(90)));
|
||||||
|
let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, Some(COOKIE_LOGIN));
|
||||||
|
assert_no_login_cookie(&mut resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_cookie_updated_on_visit_deadline() {
|
||||||
|
let mut srv = create_identity_server(|c| {
|
||||||
|
c.visit_deadline(Duration::days(90))
|
||||||
|
.login_deadline(Duration::days(90))
|
||||||
|
});
|
||||||
|
let timestamp = SystemTime::now() - Duration::days(1).to_std().unwrap();
|
||||||
|
let cookie = login_cookie(COOKIE_LOGIN, Some(timestamp), Some(timestamp));
|
||||||
|
let mut resp = test::call_service(
|
||||||
|
&mut srv,
|
||||||
|
TestRequest::with_uri("/")
|
||||||
|
.cookie(cookie.clone())
|
||||||
|
.to_request(),
|
||||||
|
);
|
||||||
|
assert_logged_in(&mut resp, Some(COOKIE_LOGIN));
|
||||||
|
assert_login_cookie(
|
||||||
|
&mut resp,
|
||||||
|
COOKIE_LOGIN,
|
||||||
|
LoginTimestampCheck::OldTimestamp(timestamp),
|
||||||
|
VisitTimeStampCheck::NewTimestamp,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -116,12 +116,12 @@ impl Default for Logger {
|
|||||||
|
|
||||||
impl<S, B> Transform<S> for Logger
|
impl<S, B> Transform<S> for Logger
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<StreamLog<B>>;
|
type Response = ServiceResponse<StreamLog<B>>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = LoggerMiddleware<S>;
|
type Transform = LoggerMiddleware<S>;
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
@ -142,12 +142,12 @@ pub struct LoggerMiddleware<S> {
|
|||||||
|
|
||||||
impl<S, B> Service for LoggerMiddleware<S>
|
impl<S, B> Service for LoggerMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<StreamLog<B>>;
|
type Response = ServiceResponse<StreamLog<B>>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type Future = LoggerResponse<S, B>;
|
type Future = LoggerResponse<S, B>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -194,10 +194,10 @@ where
|
|||||||
impl<S, B> Future for LoggerResponse<S, B>
|
impl<S, B> Future for LoggerResponse<S, B>
|
||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
{
|
{
|
||||||
type Item = ServiceResponse<StreamLog<B>>;
|
type Item = ServiceResponse<StreamLog<B>>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
let res = futures::try_ready!(self.fut.poll());
|
let res = futures::try_ready!(self.fut.poll());
|
||||||
@ -457,7 +457,7 @@ impl<'a> fmt::Display for FormatDisplay<'a> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::{FnService, Service, Transform};
|
use actix_service::{IntoService, Service, Transform};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::http::{header, StatusCode};
|
use crate::http::{header, StatusCode};
|
||||||
@ -465,16 +465,16 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_logger() {
|
fn test_logger() {
|
||||||
let srv = FnService::new(|req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
req.into_response(
|
req.into_response(
|
||||||
HttpResponse::build(StatusCode::OK)
|
HttpResponse::build(StatusCode::OK)
|
||||||
.header("X-Test", "ttt")
|
.header("X-Test", "ttt")
|
||||||
.finish(),
|
.finish(),
|
||||||
)
|
)
|
||||||
});
|
};
|
||||||
let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test");
|
let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test");
|
||||||
|
|
||||||
let mut srv = block_on(logger.new_transform(srv)).unwrap();
|
let mut srv = block_on(logger.new_transform(srv.into_service())).unwrap();
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::with_header(
|
||||||
header::USER_AGENT,
|
header::USER_AGENT,
|
||||||
|
@ -1,10 +1,13 @@
|
|||||||
//! `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;
|
||||||
|
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
use crate::service::{ServiceRequest, ServiceResponse};
|
||||||
|
use crate::Error;
|
||||||
|
|
||||||
#[derive(Default, Clone, Copy)]
|
#[derive(Default, Clone, Copy)]
|
||||||
/// `Middleware` to normalize request's URI in place
|
/// `Middleware` to normalize request's URI in place
|
||||||
@ -12,15 +15,31 @@ use crate::service::{ServiceRequest, ServiceResponse};
|
|||||||
/// 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>,
|
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 = S::Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = NormalizePathNormalization<S>;
|
type Transform = NormalizePathNormalization<S>;
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
@ -38,13 +57,14 @@ 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>,
|
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 = S::Error;
|
type Error = Error;
|
||||||
type Future = S::Future;
|
type Future = S::Future;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||||
@ -59,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)
|
||||||
@ -68,21 +100,35 @@ where
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::FnService;
|
use actix_service::IntoService;
|
||||||
|
|
||||||
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() {
|
||||||
let srv = FnService::new(|req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
assert_eq!("/v1/something/", req.path());
|
assert_eq!("/v1/something/", req.path());
|
||||||
req.into_response(HttpResponse::Ok().finish())
|
req.into_response(HttpResponse::Ok().finish())
|
||||||
});
|
};
|
||||||
|
|
||||||
let mut normalize = block_on(NormalizePath.new_transform(srv)).unwrap();
|
let mut normalize =
|
||||||
|
block_on(NormalizePath.new_transform(srv.into_service())).unwrap();
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/v1//something////").to_srv_request();
|
let req = TestRequest::with_uri("/v1//something////").to_srv_request();
|
||||||
let res = block_on(normalize.call(req)).unwrap();
|
let res = block_on(normalize.call(req)).unwrap();
|
||||||
@ -93,12 +139,13 @@ mod tests {
|
|||||||
fn should_normalize_nothing() {
|
fn should_normalize_nothing() {
|
||||||
const URI: &str = "/v1/something/";
|
const URI: &str = "/v1/something/";
|
||||||
|
|
||||||
let srv = FnService::new(|req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
assert_eq!(URI, req.path());
|
assert_eq!(URI, req.path());
|
||||||
req.into_response(HttpResponse::Ok().finish())
|
req.into_response(HttpResponse::Ok().finish())
|
||||||
});
|
};
|
||||||
|
|
||||||
let mut normalize = block_on(NormalizePath.new_transform(srv)).unwrap();
|
let mut normalize =
|
||||||
|
block_on(NormalizePath.new_transform(srv.into_service())).unwrap();
|
||||||
|
|
||||||
let req = TestRequest::with_uri(URI).to_srv_request();
|
let req = TestRequest::with_uri(URI).to_srv_request();
|
||||||
let res = block_on(normalize.call(req)).unwrap();
|
let res = block_on(normalize.call(req)).unwrap();
|
||||||
|
@ -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 {
|
||||||
|
@ -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)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -72,6 +75,7 @@ impl Resource {
|
|||||||
impl<T> Resource<T>
|
impl<T> Resource<T>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -154,7 +158,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -236,6 +275,7 @@ where
|
|||||||
mw: F,
|
mw: F,
|
||||||
) -> Resource<
|
) -> Resource<
|
||||||
impl NewService<
|
impl NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -260,6 +300,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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -301,6 +342,7 @@ where
|
|||||||
mw: F,
|
mw: F,
|
||||||
) -> Resource<
|
) -> Resource<
|
||||||
impl NewService<
|
impl NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -321,6 +363,7 @@ where
|
|||||||
where
|
where
|
||||||
F: IntoNewService<U>,
|
F: IntoNewService<U>,
|
||||||
U: NewService<
|
U: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -341,6 +384,7 @@ where
|
|||||||
impl<T> HttpServiceFactory for Resource<T>
|
impl<T> HttpServiceFactory for Resource<T>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -361,6 +405,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_service_data(ext);
|
||||||
|
}
|
||||||
config.register_service(rdef, guards, self, None)
|
config.register_service(rdef, guards, self, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -368,6 +416,7 @@ where
|
|||||||
impl<T> IntoNewService<T> for Resource<T>
|
impl<T> IntoNewService<T> for Resource<T>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -377,6 +426,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,10 +436,12 @@ 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>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for ResourceFactory {
|
impl NewService for ResourceFactory {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -410,6 +462,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 +476,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 +521,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 +532,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 +552,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -523,6 +582,7 @@ impl ResourceEndpoint {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for ResourceEndpoint {
|
impl NewService for ResourceEndpoint {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
193
src/responder.rs
193
src/responder.rs
@ -1,8 +1,12 @@
|
|||||||
use actix_http::error::InternalError;
|
use actix_http::error::InternalError;
|
||||||
use actix_http::{http::StatusCode, Error, Response, ResponseBuilder};
|
use actix_http::http::{
|
||||||
|
header::IntoHeaderValue, Error as HttpError, HeaderMap, HeaderName, HttpTryFrom,
|
||||||
|
StatusCode,
|
||||||
|
};
|
||||||
|
use actix_http::{Error, Response, ResponseBuilder};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::future::{err, ok, Either as EitherFuture, FutureResult};
|
use futures::future::{err, ok, Either as EitherFuture, FutureResult};
|
||||||
use futures::{Future, IntoFuture, Poll};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||||
|
|
||||||
use crate::request::HttpRequest;
|
use crate::request::HttpRequest;
|
||||||
|
|
||||||
@ -18,6 +22,51 @@ pub trait Responder {
|
|||||||
|
|
||||||
/// Convert itself to `AsyncResult` or `Error`.
|
/// Convert itself to `AsyncResult` or `Error`.
|
||||||
fn respond_to(self, req: &HttpRequest) -> Self::Future;
|
fn respond_to(self, req: &HttpRequest) -> Self::Future;
|
||||||
|
|
||||||
|
/// Override a status code for a Responder.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_web::{HttpRequest, Responder, http::StatusCode};
|
||||||
|
///
|
||||||
|
/// fn index(req: HttpRequest) -> impl Responder {
|
||||||
|
/// "Welcome!".with_status(StatusCode::OK)
|
||||||
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
|
fn with_status(self, status: StatusCode) -> CustomResponder<Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
CustomResponder::new(self).with_status(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add header to the Responder's response.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_web::{web, HttpRequest, Responder};
|
||||||
|
/// use serde::Serialize;
|
||||||
|
///
|
||||||
|
/// #[derive(Serialize)]
|
||||||
|
/// struct MyObj {
|
||||||
|
/// name: String,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn index(req: HttpRequest) -> impl Responder {
|
||||||
|
/// web::Json(
|
||||||
|
/// MyObj{name: "Name".to_string()}
|
||||||
|
/// )
|
||||||
|
/// .with_header("x-version", "1.2.3")
|
||||||
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
|
fn with_header<K, V>(self, key: K, value: V) -> CustomResponder<Self>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
HeaderName: HttpTryFrom<K>,
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
{
|
||||||
|
CustomResponder::new(self).with_header(key, value)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Responder for Response {
|
impl Responder for Response {
|
||||||
@ -154,6 +203,117 @@ impl Responder for BytesMut {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Allows to override status code and headers for a responder.
|
||||||
|
pub struct CustomResponder<T> {
|
||||||
|
responder: T,
|
||||||
|
status: Option<StatusCode>,
|
||||||
|
headers: Option<HeaderMap>,
|
||||||
|
error: Option<HttpError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Responder> CustomResponder<T> {
|
||||||
|
fn new(responder: T) -> Self {
|
||||||
|
CustomResponder {
|
||||||
|
responder,
|
||||||
|
status: None,
|
||||||
|
headers: None,
|
||||||
|
error: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Override a status code for the Responder's response.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_web::{HttpRequest, Responder, http::StatusCode};
|
||||||
|
///
|
||||||
|
/// fn index(req: HttpRequest) -> impl Responder {
|
||||||
|
/// "Welcome!".with_status(StatusCode::OK)
|
||||||
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
|
pub fn with_status(mut self, status: StatusCode) -> Self {
|
||||||
|
self.status = Some(status);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add header to the Responder's response.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_web::{web, HttpRequest, Responder};
|
||||||
|
/// use serde::Serialize;
|
||||||
|
///
|
||||||
|
/// #[derive(Serialize)]
|
||||||
|
/// struct MyObj {
|
||||||
|
/// name: String,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn index(req: HttpRequest) -> impl Responder {
|
||||||
|
/// web::Json(
|
||||||
|
/// MyObj{name: "Name".to_string()}
|
||||||
|
/// )
|
||||||
|
/// .with_header("x-version", "1.2.3")
|
||||||
|
/// }
|
||||||
|
/// # fn main() {}
|
||||||
|
/// ```
|
||||||
|
pub fn with_header<K, V>(mut self, key: K, value: V) -> Self
|
||||||
|
where
|
||||||
|
HeaderName: HttpTryFrom<K>,
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
{
|
||||||
|
if self.headers.is_none() {
|
||||||
|
self.headers = Some(HeaderMap::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
match HeaderName::try_from(key) {
|
||||||
|
Ok(key) => match value.try_into() {
|
||||||
|
Ok(value) => {
|
||||||
|
self.headers.as_mut().unwrap().append(key, value);
|
||||||
|
}
|
||||||
|
Err(e) => self.error = Some(e.into()),
|
||||||
|
},
|
||||||
|
Err(e) => self.error = Some(e.into()),
|
||||||
|
};
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Responder> Responder for CustomResponder<T> {
|
||||||
|
type Error = T::Error;
|
||||||
|
type Future = CustomResponderFut<T>;
|
||||||
|
|
||||||
|
fn respond_to(self, req: &HttpRequest) -> Self::Future {
|
||||||
|
CustomResponderFut {
|
||||||
|
fut: self.responder.respond_to(req).into_future(),
|
||||||
|
status: self.status,
|
||||||
|
headers: self.headers,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CustomResponderFut<T: Responder> {
|
||||||
|
fut: <T::Future as IntoFuture>::Future,
|
||||||
|
status: Option<StatusCode>,
|
||||||
|
headers: Option<HeaderMap>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Responder> Future for CustomResponderFut<T> {
|
||||||
|
type Item = Response;
|
||||||
|
type Error = T::Error;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
let mut res = try_ready!(self.fut.poll());
|
||||||
|
if let Some(status) = self.status {
|
||||||
|
*res.status_mut() = status;
|
||||||
|
}
|
||||||
|
if let Some(ref headers) = self.headers {
|
||||||
|
for (k, v) in headers {
|
||||||
|
res.headers_mut().insert(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Async::Ready(res))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Combines two different responder types into a single type
|
/// Combines two different responder types into a single type
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
@ -435,4 +595,33 @@ pub(crate) mod tests {
|
|||||||
);
|
);
|
||||||
assert!(res.is_err());
|
assert!(res.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_custom_responder() {
|
||||||
|
let req = TestRequest::default().to_http_request();
|
||||||
|
let res = block_on(
|
||||||
|
"test"
|
||||||
|
.to_string()
|
||||||
|
.with_status(StatusCode::BAD_REQUEST)
|
||||||
|
.respond_to(&req),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(res.body().bin_ref(), b"test");
|
||||||
|
|
||||||
|
let res = block_on(
|
||||||
|
"test"
|
||||||
|
.to_string()
|
||||||
|
.with_header("content-type", "json")
|
||||||
|
.respond_to(&req),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert_eq!(res.body().bin_ref(), b"test");
|
||||||
|
assert_eq!(
|
||||||
|
res.headers().get(CONTENT_TYPE).unwrap(),
|
||||||
|
HeaderValue::from_static("json")
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
71
src/route.rs
71
src/route.rs
@ -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};
|
||||||
@ -28,6 +26,7 @@ type BoxedRouteService<Req, Res> = Box<
|
|||||||
|
|
||||||
type BoxedRouteNewService<Req, Res> = Box<
|
type BoxedRouteNewService<Req, Res> = Box<
|
||||||
NewService<
|
NewService<
|
||||||
|
Config = (),
|
||||||
Request = Req,
|
Request = Req,
|
||||||
Response = Res,
|
Response = Res,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -44,36 +43,26 @@ 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())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for Route {
|
impl NewService for Route {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -239,10 +228,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 +268,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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -331,6 +285,7 @@ where
|
|||||||
impl<T> RouteNewService<T>
|
impl<T> RouteNewService<T>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = (Error, ServiceRequest),
|
Error = (Error, ServiceRequest),
|
||||||
@ -347,6 +302,7 @@ where
|
|||||||
impl<T> NewService for RouteNewService<T>
|
impl<T> NewService for RouteNewService<T>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = (Error, ServiceRequest),
|
Error = (Error, ServiceRequest),
|
||||||
@ -355,6 +311,7 @@ where
|
|||||||
T::Service: 'static,
|
T::Service: 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
85
src/scope.rs
85
src/scope.rs
@ -2,15 +2,16 @@ use std::cell::RefCell;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::Response;
|
use actix_http::{Extensions, Response};
|
||||||
use actix_router::{ResourceDef, ResourceInfo, Router};
|
use actix_router::{ResourceDef, ResourceInfo, Router};
|
||||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
ApplyTransform, IntoNewService, IntoTransform, NewService, Service, Transform,
|
apply_transform, IntoNewService, IntoTransform, NewService, Service, Transform,
|
||||||
};
|
};
|
||||||
use futures::future::{ok, Either, Future, FutureResult};
|
use futures::future::{ok, Either, Future, FutureResult};
|
||||||
use futures::{Async, IntoFuture, Poll};
|
use futures::{Async, IntoFuture, Poll};
|
||||||
|
|
||||||
|
use crate::data::Data;
|
||||||
use crate::dev::{AppService, HttpServiceFactory};
|
use crate::dev::{AppService, HttpServiceFactory};
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::guard::Guard;
|
use crate::guard::Guard;
|
||||||
@ -61,6 +62,7 @@ type BoxedResponse = Either<
|
|||||||
pub struct Scope<T = ScopeEndpoint> {
|
pub struct Scope<T = ScopeEndpoint> {
|
||||||
endpoint: T,
|
endpoint: T,
|
||||||
rdef: String,
|
rdef: String,
|
||||||
|
data: Option<Extensions>,
|
||||||
services: Vec<Box<ServiceFactory>>,
|
services: Vec<Box<ServiceFactory>>,
|
||||||
guards: Vec<Box<Guard>>,
|
guards: Vec<Box<Guard>>,
|
||||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||||
@ -74,6 +76,7 @@ impl Scope {
|
|||||||
Scope {
|
Scope {
|
||||||
endpoint: ScopeEndpoint::new(fref.clone()),
|
endpoint: ScopeEndpoint::new(fref.clone()),
|
||||||
rdef: path.to_string(),
|
rdef: path.to_string(),
|
||||||
|
data: None,
|
||||||
guards: Vec::new(),
|
guards: Vec::new(),
|
||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
default: Rc::new(RefCell::new(None)),
|
default: Rc::new(RefCell::new(None)),
|
||||||
@ -85,6 +88,7 @@ impl Scope {
|
|||||||
impl<T> Scope<T>
|
impl<T> Scope<T>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -116,6 +120,39 @@ where
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set or override application data. Application data could be accessed
|
||||||
|
/// by using `Data<T>` extractor where `T` is data type.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use std::cell::Cell;
|
||||||
|
/// use actix_web::{web, App};
|
||||||
|
///
|
||||||
|
/// struct MyData {
|
||||||
|
/// counter: Cell<usize>,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn index(data: web::Data<MyData>) {
|
||||||
|
/// data.counter.set(data.counter.get() + 1);
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn main() {
|
||||||
|
/// let app = App::new().service(
|
||||||
|
/// web::scope("/app")
|
||||||
|
/// .data(MyData{ counter: Cell::new(0) })
|
||||||
|
/// .service(
|
||||||
|
/// web::resource("/index.html").route(
|
||||||
|
/// web::get().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
|
||||||
|
}
|
||||||
|
|
||||||
/// Register http service.
|
/// Register http service.
|
||||||
///
|
///
|
||||||
/// This is similar to `App's` service registration.
|
/// This is similar to `App's` service registration.
|
||||||
@ -188,6 +225,7 @@ where
|
|||||||
where
|
where
|
||||||
F: IntoNewService<U>,
|
F: IntoNewService<U>,
|
||||||
U: NewService<
|
U: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -218,6 +256,7 @@ where
|
|||||||
mw: F,
|
mw: F,
|
||||||
) -> Scope<
|
) -> Scope<
|
||||||
impl NewService<
|
impl NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -234,10 +273,11 @@ where
|
|||||||
>,
|
>,
|
||||||
F: IntoTransform<M, T::Service>,
|
F: IntoTransform<M, T::Service>,
|
||||||
{
|
{
|
||||||
let endpoint = ApplyTransform::new(mw, self.endpoint);
|
let endpoint = apply_transform(mw, self.endpoint);
|
||||||
Scope {
|
Scope {
|
||||||
endpoint,
|
endpoint,
|
||||||
rdef: self.rdef,
|
rdef: self.rdef,
|
||||||
|
data: self.data,
|
||||||
guards: self.guards,
|
guards: self.guards,
|
||||||
services: self.services,
|
services: self.services,
|
||||||
default: self.default,
|
default: self.default,
|
||||||
@ -280,6 +320,7 @@ where
|
|||||||
mw: F,
|
mw: F,
|
||||||
) -> Scope<
|
) -> Scope<
|
||||||
impl NewService<
|
impl NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -297,13 +338,14 @@ where
|
|||||||
impl<T> HttpServiceFactory for Scope<T>
|
impl<T> HttpServiceFactory for Scope<T>
|
||||||
where
|
where
|
||||||
T: NewService<
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
> + 'static,
|
> + 'static,
|
||||||
{
|
{
|
||||||
fn register(self, config: &mut AppService) {
|
fn register(mut self, config: &mut AppService) {
|
||||||
// update default resource if needed
|
// update default resource if needed
|
||||||
if self.default.borrow().is_none() {
|
if self.default.borrow().is_none() {
|
||||||
*self.default.borrow_mut() = Some(config.default_service());
|
*self.default.borrow_mut() = Some(config.default_service());
|
||||||
@ -317,11 +359,18 @@ where
|
|||||||
|
|
||||||
let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef));
|
let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef));
|
||||||
|
|
||||||
|
// custom app data storage
|
||||||
|
if let Some(ref mut ext) = self.data {
|
||||||
|
config.set_service_data(ext);
|
||||||
|
}
|
||||||
|
|
||||||
// complete scope pipeline creation
|
// complete scope pipeline creation
|
||||||
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
|
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
|
||||||
|
data: self.data.take().map(|data| Rc::new(data)),
|
||||||
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);
|
||||||
@ -349,11 +398,13 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct ScopeFactory {
|
pub struct ScopeFactory {
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
services: Rc<Vec<(ResourceDef, HttpNewService, RefCell<Option<Guards>>)>>,
|
services: Rc<Vec<(ResourceDef, HttpNewService, RefCell<Option<Guards>>)>>,
|
||||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for ScopeFactory {
|
impl NewService for ScopeFactory {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -381,6 +432,7 @@ impl NewService for ScopeFactory {
|
|||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
default: None,
|
default: None,
|
||||||
|
data: self.data.clone(),
|
||||||
default_fut,
|
default_fut,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -390,6 +442,7 @@ impl NewService for ScopeFactory {
|
|||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct ScopeFactoryResponse {
|
pub struct ScopeFactoryResponse {
|
||||||
fut: Vec<CreateScopeServiceItem>,
|
fut: Vec<CreateScopeServiceItem>,
|
||||||
|
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 = ()>>>,
|
||||||
}
|
}
|
||||||
@ -453,6 +506,7 @@ impl Future for ScopeFactoryResponse {
|
|||||||
router
|
router
|
||||||
});
|
});
|
||||||
Ok(Async::Ready(ScopeService {
|
Ok(Async::Ready(ScopeService {
|
||||||
|
data: self.data.clone(),
|
||||||
router: router.finish(),
|
router: router.finish(),
|
||||||
default: self.default.take(),
|
default: self.default.take(),
|
||||||
_ready: None,
|
_ready: None,
|
||||||
@ -464,6 +518,7 @@ impl Future for ScopeFactoryResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct ScopeService {
|
pub struct ScopeService {
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
router: Router<HttpService, Vec<Box<Guard>>>,
|
router: Router<HttpService, Vec<Box<Guard>>>,
|
||||||
default: Option<HttpService>,
|
default: Option<HttpService>,
|
||||||
_ready: Option<(ServiceRequest, ResourceInfo)>,
|
_ready: Option<(ServiceRequest, ResourceInfo)>,
|
||||||
@ -492,6 +547,9 @@ impl Service for ScopeService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if let Some((srv, _info)) = res {
|
if let Some((srv, _info)) = res {
|
||||||
|
if let Some(ref data) = self.data {
|
||||||
|
req.set_data_container(data.clone());
|
||||||
|
}
|
||||||
Either::A(srv.call(req))
|
Either::A(srv.call(req))
|
||||||
} else if let Some(ref mut default) = self.default {
|
} else if let Some(ref mut default) = self.default {
|
||||||
Either::A(default.call(req))
|
Either::A(default.call(req))
|
||||||
@ -514,6 +572,7 @@ impl ScopeEndpoint {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for ScopeEndpoint {
|
impl NewService for ScopeEndpoint {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -945,4 +1004,22 @@ mod tests {
|
|||||||
HeaderValue::from_static("0001")
|
HeaderValue::from_static("0001")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_override_data() {
|
||||||
|
let mut srv = init_service(App::new().data(1usize).service(
|
||||||
|
web::scope("app").data(10usize).route(
|
||||||
|
"/t",
|
||||||
|
web::get().to(|data: web::Data<usize>| {
|
||||||
|
assert_eq!(*data, 10);
|
||||||
|
let _ = data.clone();
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/app/t").to_request();
|
||||||
|
let resp = call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -51,8 +51,8 @@ struct Config {
|
|||||||
pub struct HttpServer<F, I, S, B>
|
pub struct HttpServer<F, I, S, B>
|
||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoNewService<S, ServerConfig>,
|
I: IntoNewService<S>,
|
||||||
S: NewService<ServerConfig, Request = Request>,
|
S: NewService<Config = ServerConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -71,8 +71,8 @@ where
|
|||||||
impl<F, I, S, B> HttpServer<F, I, S, B>
|
impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoNewService<S, ServerConfig>,
|
I: IntoNewService<S>,
|
||||||
S: NewService<ServerConfig, Request = Request>,
|
S: NewService<Config = ServerConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -442,8 +442,8 @@ where
|
|||||||
impl<F, I, S, B> HttpServer<F, I, S, B>
|
impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoNewService<S, ServerConfig>,
|
I: IntoNewService<S>,
|
||||||
S: NewService<ServerConfig, Request = Request>,
|
S: NewService<Config = ServerConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
146
src/service.rs
146
src/service.rs
@ -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};
|
||||||
@ -7,11 +8,14 @@ use actix_http::{
|
|||||||
Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response,
|
Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response,
|
||||||
ResponseHead,
|
ResponseHead,
|
||||||
};
|
};
|
||||||
use actix_router::{Path, Resource, Url};
|
use actix_router::{Path, Resource, ResourceDef, Url};
|
||||||
|
use actix_service::{IntoNewService, NewService};
|
||||||
use futures::future::{ok, FutureResult, IntoFuture};
|
use futures::future::{ok, FutureResult, IntoFuture};
|
||||||
|
|
||||||
use crate::config::{AppConfig, AppService};
|
use crate::config::{AppConfig, AppService};
|
||||||
use crate::data::Data;
|
use crate::data::Data;
|
||||||
|
use crate::dev::insert_slash;
|
||||||
|
use crate::guard::Guard;
|
||||||
use crate::info::ConnectionInfo;
|
use crate::info::ConnectionInfo;
|
||||||
use crate::request::HttpRequest;
|
use crate::request::HttpRequest;
|
||||||
|
|
||||||
@ -177,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 {
|
||||||
@ -380,10 +390,138 @@ impl<B: MessageBody> fmt::Debug for ServiceResponse<B> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct WebService {
|
||||||
|
rdef: String,
|
||||||
|
name: Option<String>,
|
||||||
|
guards: Vec<Box<Guard>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WebService {
|
||||||
|
/// Create new `WebService` instance.
|
||||||
|
pub fn new(path: &str) -> Self {
|
||||||
|
WebService {
|
||||||
|
rdef: path.to_string(),
|
||||||
|
name: None,
|
||||||
|
guards: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set service name.
|
||||||
|
///
|
||||||
|
/// Name is used for url generation.
|
||||||
|
pub fn name(mut self, name: &str) -> Self {
|
||||||
|
self.name = Some(name.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add match guard to a web service.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_web::{web, guard, dev, App, HttpResponse};
|
||||||
|
///
|
||||||
|
/// fn index(req: dev::ServiceRequest) -> dev::ServiceResponse {
|
||||||
|
/// req.into_response(HttpResponse::Ok().finish())
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn main() {
|
||||||
|
/// let app = App::new()
|
||||||
|
/// .service(
|
||||||
|
/// web::service("/app")
|
||||||
|
/// .guard(guard::Header("content-type", "text/plain"))
|
||||||
|
/// .finish(index)
|
||||||
|
/// );
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
|
||||||
|
self.guards.push(Box::new(guard));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set a service factory implementation and generate web service.
|
||||||
|
pub fn finish<T, F>(self, service: F) -> impl HttpServiceFactory
|
||||||
|
where
|
||||||
|
F: IntoNewService<T>,
|
||||||
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
|
Request = ServiceRequest,
|
||||||
|
Response = ServiceResponse,
|
||||||
|
Error = Error,
|
||||||
|
InitError = (),
|
||||||
|
> + 'static,
|
||||||
|
{
|
||||||
|
WebServiceImpl {
|
||||||
|
srv: service.into_new_service(),
|
||||||
|
rdef: self.rdef,
|
||||||
|
name: self.name,
|
||||||
|
guards: self.guards,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct WebServiceImpl<T> {
|
||||||
|
srv: T,
|
||||||
|
rdef: String,
|
||||||
|
name: Option<String>,
|
||||||
|
guards: Vec<Box<Guard>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> HttpServiceFactory for WebServiceImpl<T>
|
||||||
|
where
|
||||||
|
T: NewService<
|
||||||
|
Config = (),
|
||||||
|
Request = ServiceRequest,
|
||||||
|
Response = ServiceResponse,
|
||||||
|
Error = Error,
|
||||||
|
InitError = (),
|
||||||
|
> + 'static,
|
||||||
|
{
|
||||||
|
fn register(mut self, config: &mut AppService) {
|
||||||
|
let guards = if self.guards.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(std::mem::replace(&mut self.guards, Vec::new()))
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut rdef = if config.is_root() || !self.rdef.is_empty() {
|
||||||
|
ResourceDef::new(&insert_slash(&self.rdef))
|
||||||
|
} else {
|
||||||
|
ResourceDef::new(&self.rdef)
|
||||||
|
};
|
||||||
|
if let Some(ref name) = self.name {
|
||||||
|
*rdef.name_mut() = name.clone();
|
||||||
|
}
|
||||||
|
config.register_service(rdef, guards, self.srv, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::test::TestRequest;
|
use super::*;
|
||||||
use crate::HttpResponse;
|
use crate::test::{call_service, init_service, TestRequest};
|
||||||
|
use crate::{guard, http, web, App, HttpResponse};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_service() {
|
||||||
|
let mut srv = init_service(
|
||||||
|
App::new().service(web::service("/test").name("test").finish(
|
||||||
|
|req: ServiceRequest| req.into_response(HttpResponse::Ok().finish()),
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
let req = TestRequest::with_uri("/test").to_request();
|
||||||
|
let resp = call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), http::StatusCode::OK);
|
||||||
|
|
||||||
|
let mut srv = init_service(
|
||||||
|
App::new().service(web::service("/test").guard(guard::Get()).finish(
|
||||||
|
|req: ServiceRequest| req.into_response(HttpResponse::Ok().finish()),
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
let req = TestRequest::with_uri("/test")
|
||||||
|
.method(http::Method::PUT)
|
||||||
|
.to_request();
|
||||||
|
let resp = call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_fmt_debug() {
|
fn test_fmt_debug() {
|
||||||
|
145
src/test.rs
145
src/test.rs
@ -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::{IntoNewService, IntoService, 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()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -76,9 +110,10 @@ pub fn default_service(
|
|||||||
status_code: StatusCode,
|
status_code: StatusCode,
|
||||||
) -> impl Service<Request = ServiceRequest, Response = ServiceResponse<Body>, Error = Error>
|
) -> impl Service<Request = ServiceRequest, Response = ServiceResponse<Body>, Error = Error>
|
||||||
{
|
{
|
||||||
FnService::new(move |req: ServiceRequest| {
|
(move |req: ServiceRequest| {
|
||||||
req.into_response(HttpResponse::build(status_code).finish())
|
req.into_response(HttpResponse::build(status_code).finish())
|
||||||
})
|
})
|
||||||
|
.into_service()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This method accepts application builder instance, and constructs
|
/// This method accepts application builder instance, and constructs
|
||||||
@ -107,9 +142,9 @@ pub fn init_service<R, S, B, E>(
|
|||||||
app: R,
|
app: R,
|
||||||
) -> impl Service<Request = Request, Response = ServiceResponse<B>, Error = E>
|
) -> impl Service<Request = Request, Response = ServiceResponse<B>, Error = E>
|
||||||
where
|
where
|
||||||
R: IntoNewService<S, ServerConfig>,
|
R: IntoNewService<S>,
|
||||||
S: NewService<
|
S: NewService<
|
||||||
ServerConfig,
|
Config = ServerConfig,
|
||||||
Request = Request,
|
Request = Request,
|
||||||
Response = ServiceResponse<B>,
|
Response = ServiceResponse<B>,
|
||||||
Error = E,
|
Error = E,
|
||||||
@ -295,12 +330,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 +351,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 +363,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 +373,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 +420,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 +479,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 +506,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 +523,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 +538,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 +565,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 +587,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 +607,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 +656,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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -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))
|
||||||
/// );
|
/// );
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -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()),
|
||||||
|
@ -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();
|
||||||
|
25
src/web.rs
25
src/web.rs
@ -12,9 +12,10 @@ use crate::resource::Resource;
|
|||||||
use crate::responder::Responder;
|
use crate::responder::Responder;
|
||||||
use crate::route::Route;
|
use crate::route::Route;
|
||||||
use crate::scope::Scope;
|
use crate::scope::Scope;
|
||||||
|
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::*;
|
||||||
|
|
||||||
@ -274,6 +275,28 @@ where
|
|||||||
Route::new().to_async(handler)
|
Route::new().to_async(handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create raw service for a specific path.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # extern crate actix_web;
|
||||||
|
/// use actix_web::{dev, web, guard, App, HttpResponse};
|
||||||
|
///
|
||||||
|
/// fn my_service(req: dev::ServiceRequest) -> dev::ServiceResponse {
|
||||||
|
/// req.into_response(HttpResponse::Ok().finish())
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn main() {
|
||||||
|
/// let app = App::new().service(
|
||||||
|
/// web::service("/users/*")
|
||||||
|
/// .guard(guard::Header("content-type", "text/plain"))
|
||||||
|
/// .finish(my_service)
|
||||||
|
/// );
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn service(path: &str) -> WebService {
|
||||||
|
WebService::new(path)
|
||||||
|
}
|
||||||
|
|
||||||
/// Execute blocking function on a thread pool, returns future that resolves
|
/// Execute blocking function on a thread pool, returns future that resolves
|
||||||
/// to result of the function execution.
|
/// to result of the function execution.
|
||||||
pub fn block<F, I, E>(f: F) -> impl Future<Item = I, Error = BlockingError<E>>
|
pub fn block<F, I, E>(f: F) -> impl Future<Item = I, Error = BlockingError<E>>
|
||||||
|
@ -1,5 +1,14 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
|
* Update awc and actix-http deps
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-04-24
|
||||||
|
|
||||||
|
* Always make new connection for http client
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0] - 2019-04-16
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
* No changes
|
* No changes
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http-test"
|
name = "actix-http-test"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix http test server"
|
description = "Actix http test server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -32,10 +32,10 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.0"
|
||||||
actix-server = "0.4.3"
|
actix-server = "0.5.0"
|
||||||
actix-utils = "0.3.5"
|
actix-utils = "0.4.0"
|
||||||
awc = "0.1.0"
|
awc = "0.2.0"
|
||||||
|
|
||||||
base64 = "0.10"
|
base64 = "0.10"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
@ -55,5 +55,5 @@ tokio-timer = "0.2"
|
|||||||
openssl = { version="0.10", optional = true }
|
openssl = { version="0.10", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = "1.0.0-alpha.5"
|
actix-web = "1.0.0-beta.1"
|
||||||
actix-http = "0.1.0"
|
actix-http = "0.2.0"
|
||||||
|
@ -1 +1,9 @@
|
|||||||
# Actix http test server [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-http-test) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Actix http test server [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-http-test) [](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
|
||||||
|
@ -9,16 +9,30 @@ use actix_server::{Server, StreamServiceFactory};
|
|||||||
use awc::{error::PayloadError, ws, Client, ClientRequest, ClientResponse, Connector};
|
use awc::{error::PayloadError, ws, Client, ClientRequest, ClientResponse, Connector};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future::lazy;
|
use futures::future::lazy;
|
||||||
use futures::{Future, Stream};
|
use futures::{Future, IntoFuture, Stream};
|
||||||
use http::Method;
|
use http::Method;
|
||||||
use net2::TcpBuilder;
|
use net2::TcpBuilder;
|
||||||
|
|
||||||
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.
|
||||||
///
|
///
|
||||||
@ -31,21 +45,27 @@ 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, with runtime enabled.
|
/// 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.
|
/// Note that this function is intended to be used only for testing purpose.
|
||||||
/// This function panics on nested call.
|
/// This function panics on nested call.
|
||||||
pub fn run_on<F, R>(f: F) -> R
|
pub fn block_fn<F, R>(f: F) -> Result<R::Item, R::Error>
|
||||||
where
|
where
|
||||||
F: Fn() -> R,
|
F: FnOnce() -> R,
|
||||||
|
R: IntoFuture,
|
||||||
{
|
{
|
||||||
RT.with(move |rt| rt.borrow_mut().block_on(lazy(|| Ok::<_, ()>(f()))))
|
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f())))
|
||||||
.unwrap()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `TestServer` type.
|
/// The `TestServer` type.
|
||||||
@ -124,6 +144,7 @@ impl TestServer {
|
|||||||
|e| log::error!("Can not set alpn protocol: {:?}", e),
|
|e| log::error!("Can not set alpn protocol: {:?}", e),
|
||||||
);
|
);
|
||||||
Connector::new()
|
Connector::new()
|
||||||
|
.conn_lifetime(time::Duration::from_secs(0))
|
||||||
.timeout(time::Duration::from_millis(500))
|
.timeout(time::Duration::from_millis(500))
|
||||||
.ssl(builder.build())
|
.ssl(builder.build())
|
||||||
.finish()
|
.finish()
|
||||||
@ -131,6 +152,7 @@ impl TestServer {
|
|||||||
#[cfg(not(feature = "ssl"))]
|
#[cfg(not(feature = "ssl"))]
|
||||||
{
|
{
|
||||||
Connector::new()
|
Connector::new()
|
||||||
|
.conn_lifetime(time::Duration::from_secs(0))
|
||||||
.timeout(time::Duration::from_millis(500))
|
.timeout(time::Duration::from_millis(500))
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
@ -163,6 +185,15 @@ impl TestServerRuntime {
|
|||||||
self.rt.block_on(fut)
|
self.rt.block_on(fut)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Execute future on current core
|
||||||
|
pub fn block_on_fn<F, R>(&mut self, f: F) -> Result<R::Item, R::Error>
|
||||||
|
where
|
||||||
|
F: FnOnce() -> R,
|
||||||
|
R: Future,
|
||||||
|
{
|
||||||
|
self.rt.block_on(lazy(|| f()))
|
||||||
|
}
|
||||||
|
|
||||||
/// Execute function on current core
|
/// Execute function on current core
|
||||||
pub fn execute<F, R>(&mut self, fut: F) -> R
|
pub fn execute<F, R>(&mut self, fut: F) -> R
|
||||||
where
|
where
|
||||||
|
Reference in New Issue
Block a user