mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-14 22:17:04 +02:00
Compare commits
25 Commits
http-v0.1.
...
http-v0.1.
Author | SHA1 | Date | |
---|---|---|---|
5e4e95fb0a | |||
9f421b81b8 | |||
6decfdda1f | |||
fc9b14a933 | |||
7292d0b696 | |||
a3844c1bfd | |||
791f22bbc8 | |||
1e7f97a111 | |||
bc40f5ae40 | |||
3504a8fc0a | |||
bfe0df5ab0 | |||
ed94df189f | |||
aa255298ef | |||
da86b6e062 | |||
75e340137d | |||
e659e09e29 | |||
163ca89cf4 | |||
85b598a614 | |||
b64851c5ec | |||
cc8420377e | |||
5740f1e63a | |||
c943e95812 | |||
4c0ebd55d3 | |||
e7ec77aa81 | |||
ddfd7523f7 |
@ -15,6 +15,10 @@
|
|||||||
|
|
||||||
* Rename `test::call_success` to `test::call_service`
|
* Rename `test::call_success` to `test::call_service`
|
||||||
|
|
||||||
|
* Removed `ServiceRequest::from_parts()` as it is unsafe to create from parts.
|
||||||
|
|
||||||
|
* `CookieIdentityPolicy::max_age()` accepts value in seconds
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
* Fixed `TestRequest::app_data()`
|
* Fixed `TestRequest::app_data()`
|
||||||
|
18
Cargo.toml
18
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web"
|
name = "actix-web"
|
||||||
version = "1.0.0-alpha.6"
|
version = "1.0.0-beta.1"
|
||||||
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"
|
||||||
@ -15,6 +15,9 @@ license = "MIT/Apache-2.0"
|
|||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
||||||
|
|
||||||
[badges]
|
[badges]
|
||||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||||
codecov = { repository = "actix/actix-web", branch = "master", service = "github" }
|
codecov = { repository = "actix/actix-web", branch = "master", service = "github" }
|
||||||
@ -37,9 +40,6 @@ members = [
|
|||||||
"test-server",
|
"test-server",
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
|
||||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client"]
|
default = ["brotli", "flate2-zlib", "secure-cookies", "client"]
|
||||||
|
|
||||||
@ -71,11 +71,11 @@ actix-utils = "0.3.4"
|
|||||||
actix-router = "0.1.2"
|
actix-router = "0.1.2"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-web-codegen = "0.1.0-alpha.6"
|
actix-web-codegen = "0.1.0-alpha.6"
|
||||||
actix-http = { version = "0.1.0-alpha.5", features=["fail"] }
|
actix-http = { version = "0.1.0", features=["fail"] }
|
||||||
actix-server = "0.4.3"
|
actix-server = "0.4.3"
|
||||||
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.0-alpha.6", optional = true }
|
awc = { version = "0.1.0", optional = true }
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
@ -90,7 +90,7 @@ regex = "1.0"
|
|||||||
serde = { version = "1.0", features=["derive"] }
|
serde = { version = "1.0", features=["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde_urlencoded = "0.5.3"
|
serde_urlencoded = "0.5.3"
|
||||||
time = "0.1"
|
time = "0.1.42"
|
||||||
url = { version="1.7", features=["query_encoding"] }
|
url = { version="1.7", features=["query_encoding"] }
|
||||||
|
|
||||||
# ssl support
|
# ssl support
|
||||||
@ -98,8 +98,8 @@ 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.0-alpha.5", features=["ssl", "brotli", "flate2-zlib"] }
|
actix-http = { version = "0.1.0", features=["ssl", "brotli", "flate2-zlib"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||||
actix-files = { version = "0.1.0-alpha.6" }
|
actix-files = { version = "0.1.0-alpha.6" }
|
||||||
rand = "0.6"
|
rand = "0.6"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
|
@ -128,7 +128,7 @@
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
* AsyncResponder is removed.
|
* AsyncResponder is removed, use `.to_async()` registration method and `impl Future<>` as result type.
|
||||||
|
|
||||||
instead of
|
instead of
|
||||||
|
|
||||||
|
@ -411,17 +411,16 @@ impl FilesService {
|
|||||||
fn handle_err(
|
fn handle_err(
|
||||||
&mut self,
|
&mut self,
|
||||||
e: io::Error,
|
e: io::Error,
|
||||||
req: HttpRequest,
|
req: ServiceRequest,
|
||||||
payload: Payload,
|
|
||||||
) -> Either<
|
) -> Either<
|
||||||
FutureResult<ServiceResponse, Error>,
|
FutureResult<ServiceResponse, Error>,
|
||||||
Box<Future<Item = ServiceResponse, Error = Error>>,
|
Box<Future<Item = ServiceResponse, Error = Error>>,
|
||||||
> {
|
> {
|
||||||
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
||||||
if let Some(ref mut default) = self.default {
|
if let Some(ref mut default) = self.default {
|
||||||
default.call(ServiceRequest::from_parts(req, payload))
|
default.call(req)
|
||||||
} else {
|
} else {
|
||||||
Either::A(ok(ServiceResponse::from_err(e, req.clone())))
|
Either::A(ok(req.error_response(e)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -440,17 +439,17 @@ impl Service for FilesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||||
let (req, pl) = req.into_parts();
|
// let (req, pl) = req.into_parts();
|
||||||
|
|
||||||
let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) {
|
let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) {
|
||||||
Ok(item) => item,
|
Ok(item) => item,
|
||||||
Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req.clone()))),
|
Err(e) => return Either::A(ok(req.error_response(e))),
|
||||||
};
|
};
|
||||||
|
|
||||||
// full filepath
|
// full filepath
|
||||||
let path = match self.directory.join(&real_path.0).canonicalize() {
|
let path = match self.directory.join(&real_path.0).canonicalize() {
|
||||||
Ok(path) => path,
|
Ok(path) => path,
|
||||||
Err(e) => return self.handle_err(e, req, pl),
|
Err(e) => return self.handle_err(e, req),
|
||||||
};
|
};
|
||||||
|
|
||||||
if path.is_dir() {
|
if path.is_dir() {
|
||||||
@ -466,24 +465,26 @@ impl Service for FilesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
named_file.flags = self.file_flags;
|
named_file.flags = self.file_flags;
|
||||||
|
let (req, _) = req.into_parts();
|
||||||
Either::A(ok(match named_file.respond_to(&req) {
|
Either::A(ok(match named_file.respond_to(&req) {
|
||||||
Ok(item) => ServiceResponse::new(req.clone(), item),
|
Ok(item) => ServiceResponse::new(req, item),
|
||||||
Err(e) => ServiceResponse::from_err(e, req.clone()),
|
Err(e) => ServiceResponse::from_err(e, req),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
Err(e) => return self.handle_err(e, req, pl),
|
Err(e) => return self.handle_err(e, req),
|
||||||
}
|
}
|
||||||
} else if self.show_index {
|
} else if self.show_index {
|
||||||
let dir = Directory::new(self.directory.clone(), path);
|
let dir = Directory::new(self.directory.clone(), path);
|
||||||
|
let (req, _) = req.into_parts();
|
||||||
let x = (self.renderer)(&dir, &req);
|
let x = (self.renderer)(&dir, &req);
|
||||||
match x {
|
match x {
|
||||||
Ok(resp) => Either::A(ok(resp)),
|
Ok(resp) => Either::A(ok(resp)),
|
||||||
Err(e) => return self.handle_err(e, req, pl),
|
Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Either::A(ok(ServiceResponse::from_err(
|
Either::A(ok(ServiceResponse::from_err(
|
||||||
FilesError::IsDirectory,
|
FilesError::IsDirectory,
|
||||||
req.clone(),
|
req.into_parts().0,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -496,16 +497,15 @@ impl Service for FilesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
named_file.flags = self.file_flags;
|
named_file.flags = self.file_flags;
|
||||||
|
let (req, _) = req.into_parts();
|
||||||
match named_file.respond_to(&req) {
|
match named_file.respond_to(&req) {
|
||||||
Ok(item) => {
|
Ok(item) => {
|
||||||
Either::A(ok(ServiceResponse::new(req.clone(), item)))
|
Either::A(ok(ServiceResponse::new(req.clone(), item)))
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||||
Either::A(ok(ServiceResponse::from_err(e, req.clone())))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
Err(e) => self.handle_err(e, req),
|
||||||
Err(e) => self.handle_err(e, req, pl),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-framed"
|
name = "actix-framed"
|
||||||
version = "0.1.0-alpha.1"
|
version = "0.1.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"
|
||||||
@ -25,13 +25,13 @@ actix-service = "0.3.6"
|
|||||||
actix-utils = "0.3.4"
|
actix-utils = "0.3.4"
|
||||||
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-alpha.5"
|
actix-http = "0.1.0"
|
||||||
|
|
||||||
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.1", features=["ssl"] }
|
actix-server = { version = "0.4.3", features=["ssl"] }
|
||||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
actix-connect = { version = "0.1.4", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||||
|
@ -1,5 +1,10 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
|
* Update tests
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0-alpha.1] - 2019-04-12
|
## [0.1.0-alpha.1] - 2019-04-12
|
||||||
|
|
||||||
* Initial release
|
* Initial release
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_http::{body, ws, Error, HttpService, Response};
|
use actix_http::{body, http::StatusCode, ws, Error, HttpService, Response};
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_service::{IntoNewService, NewService};
|
use actix_service::{IntoNewService, NewService};
|
||||||
use actix_utils::framed::FramedTransport;
|
use actix_utils::framed::FramedTransport;
|
||||||
@ -99,6 +99,11 @@ fn test_service() {
|
|||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// non ws request
|
||||||
|
let res = srv.block_on(srv.get("/index.html").send()).unwrap();
|
||||||
|
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
// not found
|
||||||
assert!(srv.ws_at("/test").is_err());
|
assert!(srv.ws_at("/test").is_err());
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
|
@ -1,5 +1,16 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-04-19
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
* Cookie::max_age() accepts value in seconds
|
||||||
|
|
||||||
|
* Cookie::max_age_time() accepts value in time::Duration
|
||||||
|
|
||||||
|
* Allow to specify server address for client connector
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0] - 2019-04-16
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http"
|
name = "actix-http"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
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"
|
||||||
@ -46,7 +46,7 @@ secure-cookies = ["ring"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.3.6"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-connect = "0.1.4"
|
actix-connect = "0.1.5"
|
||||||
actix-utils = "0.3.5"
|
actix-utils = "0.3.5"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.1"
|
||||||
actix-threadpool = "0.1.0"
|
actix-threadpool = "0.1.0"
|
||||||
@ -77,7 +77,7 @@ serde_json = "1.0"
|
|||||||
sha1 = "0.6"
|
sha1 = "0.6"
|
||||||
slab = "0.4"
|
slab = "0.4"
|
||||||
serde_urlencoded = "0.5.5"
|
serde_urlencoded = "0.5.5"
|
||||||
time = "0.1"
|
time = "0.1.42"
|
||||||
tokio-tcp = "0.1.3"
|
tokio-tcp = "0.1.3"
|
||||||
tokio-timer = "0.2.8"
|
tokio-timer = "0.2.8"
|
||||||
tokio-current-thread = "0.1"
|
tokio-current-thread = "0.1"
|
||||||
@ -93,12 +93,13 @@ flate2 = { version="1.0.7", optional = true, default-features = false }
|
|||||||
# optional deps
|
# optional deps
|
||||||
failure = { version = "0.1.5", optional = true }
|
failure = { version = "0.1.5", optional = true }
|
||||||
openssl = { version="0.10", optional = true }
|
openssl = { version="0.10", optional = true }
|
||||||
|
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.4.3", features=["ssl"] }
|
||||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
actix-connect = { version = "0.1.4", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.1.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" }
|
||||||
|
@ -14,6 +14,7 @@ use tokio_tcp::TcpStream;
|
|||||||
use super::connection::Connection;
|
use super::connection::Connection;
|
||||||
use super::error::ConnectError;
|
use super::error::ConnectError;
|
||||||
use super::pool::{ConnectionPool, Protocol};
|
use super::pool::{ConnectionPool, Protocol};
|
||||||
|
use super::Connect;
|
||||||
|
|
||||||
#[cfg(feature = "ssl")]
|
#[cfg(feature = "ssl")]
|
||||||
use openssl::ssl::SslConnector;
|
use openssl::ssl::SslConnector;
|
||||||
@ -177,13 +178,15 @@ where
|
|||||||
/// its combinator chain.
|
/// its combinator chain.
|
||||||
pub fn finish(
|
pub fn finish(
|
||||||
self,
|
self,
|
||||||
) -> impl Service<Request = Uri, Response = impl Connection, Error = ConnectError> + Clone
|
) -> impl Service<Request = Connect, Response = impl Connection, Error = ConnectError>
|
||||||
{
|
+ Clone {
|
||||||
#[cfg(not(feature = "ssl"))]
|
#[cfg(not(feature = "ssl"))]
|
||||||
{
|
{
|
||||||
let connector = TimeoutService::new(
|
let connector = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
apply_fn(self.connector, |msg: Uri, srv| srv.call(msg.into()))
|
apply_fn(self.connector, |msg: Connect, srv| {
|
||||||
|
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||||
|
})
|
||||||
.map_err(ConnectError::from)
|
.map_err(ConnectError::from)
|
||||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||||
)
|
)
|
||||||
@ -209,7 +212,9 @@ where
|
|||||||
|
|
||||||
let ssl_service = TimeoutService::new(
|
let ssl_service = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
apply_fn(self.connector.clone(), |msg: Uri, srv| srv.call(msg.into()))
|
apply_fn(self.connector.clone(), |msg: Connect, srv| {
|
||||||
|
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||||
|
})
|
||||||
.map_err(ConnectError::from)
|
.map_err(ConnectError::from)
|
||||||
.and_then(
|
.and_then(
|
||||||
OpensslConnector::service(self.ssl)
|
OpensslConnector::service(self.ssl)
|
||||||
@ -237,7 +242,9 @@ where
|
|||||||
|
|
||||||
let tcp_service = TimeoutService::new(
|
let tcp_service = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
apply_fn(self.connector.clone(), |msg: Uri, srv| srv.call(msg.into()))
|
apply_fn(self.connector.clone(), |msg: Connect, srv| {
|
||||||
|
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||||
|
})
|
||||||
.map_err(ConnectError::from)
|
.map_err(ConnectError::from)
|
||||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||||
)
|
)
|
||||||
@ -264,15 +271,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
|
||||||
#[deprecated(since = "0.1.0-alpha4", note = "please use `.finish()` method")]
|
|
||||||
pub fn service(
|
|
||||||
self,
|
|
||||||
) -> impl Service<Request = Uri, Response = impl Connection, Error = ConnectError> + Clone
|
|
||||||
{
|
|
||||||
self.finish()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "ssl"))]
|
#[cfg(not(feature = "ssl"))]
|
||||||
@ -286,7 +284,7 @@ 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 = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
||||||
}
|
}
|
||||||
@ -294,7 +292,7 @@ mod connect_impl {
|
|||||||
impl<T, Io> Clone for InnerConnector<T, Io>
|
impl<T, Io> Clone for InnerConnector<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
@ -307,9 +305,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 = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
type Request = Uri;
|
type Request = Connect;
|
||||||
type Response = IoConnection<Io>;
|
type Response = IoConnection<Io>;
|
||||||
type Error = ConnectError;
|
type Error = ConnectError;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
@ -321,8 +319,8 @@ mod connect_impl {
|
|||||||
self.tcp_pool.poll_ready()
|
self.tcp_pool.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Uri) -> Self::Future {
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
match req.scheme_str() {
|
match req.uri.scheme_str() {
|
||||||
Some("https") | Some("wss") => {
|
Some("https") | Some("wss") => {
|
||||||
Either::B(err(ConnectError::SslIsNotSupported))
|
Either::B(err(ConnectError::SslIsNotSupported))
|
||||||
}
|
}
|
||||||
@ -346,8 +344,8 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
pub(crate) tcp_pool: ConnectionPool<T1, Io1>,
|
pub(crate) tcp_pool: ConnectionPool<T1, Io1>,
|
||||||
pub(crate) ssl_pool: ConnectionPool<T2, Io2>,
|
pub(crate) ssl_pool: ConnectionPool<T2, Io2>,
|
||||||
@ -357,9 +355,9 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone,
|
||||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>
|
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
@ -374,10 +372,10 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
type Request = Uri;
|
type Request = Connect;
|
||||||
type Response = EitherConnection<Io1, Io2>;
|
type Response = EitherConnection<Io1, Io2>;
|
||||||
type Error = ConnectError;
|
type Error = ConnectError;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
@ -392,8 +390,8 @@ mod connect_impl {
|
|||||||
self.tcp_pool.poll_ready()
|
self.tcp_pool.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Uri) -> Self::Future {
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
match req.scheme_str() {
|
match req.uri.scheme_str() {
|
||||||
Some("https") | Some("wss") => {
|
Some("https") | Some("wss") => {
|
||||||
Either::B(Either::B(InnerConnectorResponseB {
|
Either::B(Either::B(InnerConnectorResponseB {
|
||||||
fut: self.ssl_pool.call(req),
|
fut: self.ssl_pool.call(req),
|
||||||
@ -411,7 +409,7 @@ 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 = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
||||||
_t: PhantomData<Io2>,
|
_t: PhantomData<Io2>,
|
||||||
@ -419,7 +417,7 @@ 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 = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
@ -437,7 +435,7 @@ 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 = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
||||||
_t: PhantomData<Io1>,
|
_t: PhantomData<Io1>,
|
||||||
@ -445,7 +443,7 @@ 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 = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
//! Http client api
|
//! Http client api
|
||||||
|
use http::Uri;
|
||||||
|
|
||||||
mod connection;
|
mod connection;
|
||||||
mod connector;
|
mod connector;
|
||||||
mod error;
|
mod error;
|
||||||
@ -10,3 +12,9 @@ pub use self::connection::Connection;
|
|||||||
pub use self::connector::Connector;
|
pub use self::connector::Connector;
|
||||||
pub use self::error::{ConnectError, InvalidUrl, SendRequestError};
|
pub use self::error::{ConnectError, InvalidUrl, SendRequestError};
|
||||||
pub use self::pool::Protocol;
|
pub use self::pool::Protocol;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Connect {
|
||||||
|
pub uri: Uri,
|
||||||
|
pub addr: Option<std::net::SocketAddr>,
|
||||||
|
}
|
||||||
|
@ -13,13 +13,14 @@ use futures::unsync::oneshot;
|
|||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
use h2::client::{handshake, Handshake};
|
use h2::client::{handshake, Handshake};
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
use http::uri::{Authority, Uri};
|
use http::uri::Authority;
|
||||||
use indexmap::IndexSet;
|
use indexmap::IndexSet;
|
||||||
use slab::Slab;
|
use slab::Slab;
|
||||||
use tokio_timer::{sleep, Delay};
|
use tokio_timer::{sleep, Delay};
|
||||||
|
|
||||||
use super::connection::{ConnectionType, IoConnection};
|
use super::connection::{ConnectionType, IoConnection};
|
||||||
use super::error::ConnectError;
|
use super::error::ConnectError;
|
||||||
|
use super::Connect;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq)]
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
/// Protocol version
|
/// Protocol version
|
||||||
@ -48,7 +49,7 @@ 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 = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
connector: T,
|
connector: T,
|
||||||
@ -87,9 +88,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 = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
type Request = Uri;
|
type Request = Connect;
|
||||||
type Response = IoConnection<Io>;
|
type Response = IoConnection<Io>;
|
||||||
type Error = ConnectError;
|
type Error = ConnectError;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
@ -101,8 +102,8 @@ where
|
|||||||
self.0.poll_ready()
|
self.0.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Uri) -> Self::Future {
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
let key = if let Some(authority) = req.authority_part() {
|
let key = if let Some(authority) = req.uri.authority_part() {
|
||||||
authority.clone().into()
|
authority.clone().into()
|
||||||
} else {
|
} else {
|
||||||
return Either::A(err(ConnectError::Unresolverd));
|
return Either::A(err(ConnectError::Unresolverd));
|
||||||
@ -292,7 +293,10 @@ pub(crate) struct Inner<Io> {
|
|||||||
limit: usize,
|
limit: usize,
|
||||||
acquired: usize,
|
acquired: usize,
|
||||||
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
||||||
waiters: Slab<(Uri, oneshot::Sender<Result<IoConnection<Io>, ConnectError>>)>,
|
waiters: Slab<(
|
||||||
|
Connect,
|
||||||
|
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||||
|
)>,
|
||||||
waiters_queue: IndexSet<(Key, usize)>,
|
waiters_queue: IndexSet<(Key, usize)>,
|
||||||
task: AtomicTask,
|
task: AtomicTask,
|
||||||
}
|
}
|
||||||
@ -331,14 +335,14 @@ where
|
|||||||
/// connection is not available, wait
|
/// connection is not available, wait
|
||||||
fn wait_for(
|
fn wait_for(
|
||||||
&mut self,
|
&mut self,
|
||||||
connect: Uri,
|
connect: Connect,
|
||||||
) -> (
|
) -> (
|
||||||
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
||||||
usize,
|
usize,
|
||||||
) {
|
) {
|
||||||
let (tx, rx) = oneshot::channel();
|
let (tx, rx) = oneshot::channel();
|
||||||
|
|
||||||
let key: Key = connect.authority_part().unwrap().clone().into();
|
let key: Key = connect.uri.authority_part().unwrap().clone().into();
|
||||||
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));
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
|
|
||||||
use time::{Duration, Tm};
|
use chrono::Duration;
|
||||||
|
use time::Tm;
|
||||||
|
|
||||||
use super::{Cookie, SameSite};
|
use super::{Cookie, SameSite};
|
||||||
|
|
||||||
@ -16,7 +17,6 @@ use super::{Cookie, SameSite};
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let cookie: Cookie = Cookie::build("name", "value")
|
/// let cookie: Cookie = Cookie::build("name", "value")
|
||||||
@ -24,7 +24,7 @@ use super::{Cookie, SameSite};
|
|||||||
/// .path("/")
|
/// .path("/")
|
||||||
/// .secure(true)
|
/// .secure(true)
|
||||||
/// .http_only(true)
|
/// .http_only(true)
|
||||||
/// .max_age(Duration::days(1))
|
/// .max_age(84600)
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
@ -79,6 +79,26 @@ impl CookieBuilder {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets the `max_age` field in seconds in the cookie being built.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_http::cookie::Cookie;
|
||||||
|
///
|
||||||
|
/// # fn main() {
|
||||||
|
/// let c = Cookie::build("foo", "bar")
|
||||||
|
/// .max_age(1800)
|
||||||
|
/// .finish();
|
||||||
|
///
|
||||||
|
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
#[inline]
|
||||||
|
pub fn max_age(self, seconds: i64) -> CookieBuilder {
|
||||||
|
self.max_age_time(Duration::seconds(seconds))
|
||||||
|
}
|
||||||
|
|
||||||
/// Sets the `max_age` field in the cookie being built.
|
/// Sets the `max_age` field in the cookie being built.
|
||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
@ -88,14 +108,14 @@ impl CookieBuilder {
|
|||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let c = Cookie::build("foo", "bar")
|
/// let c = Cookie::build("foo", "bar")
|
||||||
/// .max_age(time::Duration::minutes(30))
|
/// .max_age_time(time::Duration::minutes(30))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
///
|
///
|
||||||
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
|
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn max_age(mut self, value: Duration) -> CookieBuilder {
|
pub fn max_age_time(mut self, value: Duration) -> CookieBuilder {
|
||||||
self.cookie.set_max_age(value);
|
self.cookie.set_max_age(value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@ -200,7 +220,7 @@ impl CookieBuilder {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let c = Cookie::build("foo", "bar")
|
/// let c = Cookie::build("foo", "bar")
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::mem::replace;
|
use std::mem::replace;
|
||||||
|
|
||||||
use time::{self, Duration};
|
use chrono::Duration;
|
||||||
|
|
||||||
use super::delta::DeltaCookie;
|
use super::delta::DeltaCookie;
|
||||||
use super::Cookie;
|
use super::Cookie;
|
||||||
@ -188,7 +188,7 @@ impl CookieJar {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::{CookieJar, Cookie};
|
/// use actix_http::cookie::{CookieJar, Cookie};
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut jar = CookieJar::new();
|
/// let mut jar = CookieJar::new();
|
||||||
@ -241,7 +241,7 @@ impl CookieJar {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::{CookieJar, Cookie};
|
/// use actix_http::cookie::{CookieJar, Cookie};
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut jar = CookieJar::new();
|
/// let mut jar = CookieJar::new();
|
||||||
@ -537,8 +537,8 @@ mod test {
|
|||||||
#[test]
|
#[test]
|
||||||
#[cfg(feature = "secure-cookies")]
|
#[cfg(feature = "secure-cookies")]
|
||||||
fn delta() {
|
fn delta() {
|
||||||
|
use chrono::Duration;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
let mut c = CookieJar::new();
|
let mut c = CookieJar::new();
|
||||||
|
|
||||||
|
@ -65,8 +65,9 @@ use std::borrow::Cow;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use chrono::Duration;
|
||||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||||
use time::{Duration, Tm};
|
use time::Tm;
|
||||||
|
|
||||||
pub use self::builder::CookieBuilder;
|
pub use self::builder::CookieBuilder;
|
||||||
pub use self::draft::*;
|
pub use self::draft::*;
|
||||||
@ -624,7 +625,7 @@ impl<'c> Cookie<'c> {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut c = Cookie::new("name", "value");
|
/// let mut c = Cookie::new("name", "value");
|
||||||
@ -703,7 +704,7 @@ impl<'c> Cookie<'c> {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut c = Cookie::new("foo", "bar");
|
/// let mut c = Cookie::new("foo", "bar");
|
||||||
@ -977,7 +978,7 @@ impl<'a, 'b> PartialEq<Cookie<'b>> for Cookie<'a> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{Cookie, SameSite};
|
use super::{Cookie, SameSite};
|
||||||
use time::{strptime, Duration};
|
use time::strptime;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn format() {
|
fn format() {
|
||||||
@ -987,9 +988,7 @@ mod tests {
|
|||||||
let cookie = Cookie::build("foo", "bar").http_only(true).finish();
|
let cookie = Cookie::build("foo", "bar").http_only(true).finish();
|
||||||
assert_eq!(&cookie.to_string(), "foo=bar; HttpOnly");
|
assert_eq!(&cookie.to_string(), "foo=bar; HttpOnly");
|
||||||
|
|
||||||
let cookie = Cookie::build("foo", "bar")
|
let cookie = Cookie::build("foo", "bar").max_age(10).finish();
|
||||||
.max_age(Duration::seconds(10))
|
|
||||||
.finish();
|
|
||||||
assert_eq!(&cookie.to_string(), "foo=bar; Max-Age=10");
|
assert_eq!(&cookie.to_string(), "foo=bar; Max-Age=10");
|
||||||
|
|
||||||
let cookie = Cookie::build("foo", "bar").secure(true).finish();
|
let cookie = Cookie::build("foo", "bar").secure(true).finish();
|
||||||
|
@ -5,8 +5,8 @@ use std::error::Error;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::str::Utf8Error;
|
use std::str::Utf8Error;
|
||||||
|
|
||||||
|
use chrono::Duration;
|
||||||
use percent_encoding::percent_decode;
|
use percent_encoding::percent_decode;
|
||||||
use time::{self, Duration};
|
|
||||||
|
|
||||||
use super::{Cookie, CookieStr, SameSite};
|
use super::{Cookie, CookieStr, SameSite};
|
||||||
|
|
||||||
@ -220,7 +220,8 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{Cookie, SameSite};
|
use super::{Cookie, SameSite};
|
||||||
use time::{strptime, Duration};
|
use chrono::Duration;
|
||||||
|
use time::strptime;
|
||||||
|
|
||||||
macro_rules! assert_eq_parse {
|
macro_rules! assert_eq_parse {
|
||||||
($string:expr, $expected:expr) => {
|
($string:expr, $expected:expr) => {
|
||||||
@ -418,9 +419,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn do_not_panic_on_large_max_ages() {
|
fn do_not_panic_on_large_max_ages() {
|
||||||
let max_seconds = Duration::max_value().num_seconds();
|
let max_seconds = Duration::max_value().num_seconds();
|
||||||
let expected = Cookie::build("foo", "bar")
|
let expected = Cookie::build("foo", "bar").max_age(max_seconds).finish();
|
||||||
.max_age(Duration::seconds(max_seconds))
|
|
||||||
.finish();
|
|
||||||
assert_eq_parse!(format!(" foo=bar; Max-Age={:?}", max_seconds + 1), expected);
|
assert_eq_parse!(format!(" foo=bar; Max-Age={:?}", max_seconds + 1), expected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -178,3 +178,28 @@ impl<P> fmt::Debug for Request<P> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use http::HttpTryFrom;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_basics() {
|
||||||
|
let msg = Message::new();
|
||||||
|
let mut req = Request::from(msg);
|
||||||
|
req.headers_mut().insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
header::HeaderValue::from_static("text/plain"),
|
||||||
|
);
|
||||||
|
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
||||||
|
|
||||||
|
*req.uri_mut() = Uri::try_from("/index.html?q=1").unwrap();
|
||||||
|
assert_eq!(req.uri().path(), "/index.html");
|
||||||
|
assert_eq!(req.uri().query(), Some("q=1"));
|
||||||
|
|
||||||
|
let s = format!("{:?}", req);
|
||||||
|
println!("T: {:?}", s);
|
||||||
|
assert!(s.contains("Request HTTP/1.1 GET:/index.html"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -860,7 +860,7 @@ mod tests {
|
|||||||
.domain("www.rust-lang.org")
|
.domain("www.rust-lang.org")
|
||||||
.path("/test")
|
.path("/test")
|
||||||
.http_only(true)
|
.http_only(true)
|
||||||
.max_age(time::Duration::days(1))
|
.max_age_time(time::Duration::days(1))
|
||||||
.finish(),
|
.finish(),
|
||||||
)
|
)
|
||||||
.del_cookie(&cookies[1])
|
.del_cookie(&cookies[1])
|
||||||
|
@ -18,7 +18,7 @@ name = "actix_multipart"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-alpha.3"
|
actix-web = "1.0.0-alpha.6"
|
||||||
actix-service = "0.3.4"
|
actix-service = "0.3.4"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
@ -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.0-alpha.3"
|
actix-http = "0.1.0"
|
@ -1,5 +1,8 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
|
||||||
|
* `CookieSession::max_age()` accepts value in seconds
|
||||||
|
|
||||||
## [0.1.0-alpha.6] - 2019-04-14
|
## [0.1.0-alpha.6] - 2019-04-14
|
||||||
|
|
||||||
* Update actix-web alpha.6
|
* Update actix-web alpha.6
|
||||||
|
@ -32,7 +32,7 @@ futures = "0.1.25"
|
|||||||
hashbrown = "0.2.0"
|
hashbrown = "0.2.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
time = "0.1"
|
time = "0.1.42"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
|
@ -27,7 +27,6 @@ use derive_more::{Display, From};
|
|||||||
use futures::future::{ok, Future, FutureResult};
|
use futures::future::{ok, Future, FutureResult};
|
||||||
use futures::Poll;
|
use futures::Poll;
|
||||||
use serde_json::error::Error as JsonError;
|
use serde_json::error::Error as JsonError;
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
use crate::Session;
|
use crate::Session;
|
||||||
|
|
||||||
@ -57,7 +56,7 @@ struct CookieSessionInner {
|
|||||||
domain: Option<String>,
|
domain: Option<String>,
|
||||||
secure: bool,
|
secure: bool,
|
||||||
http_only: bool,
|
http_only: bool,
|
||||||
max_age: Option<Duration>,
|
max_age: Option<time::Duration>,
|
||||||
same_site: Option<SameSite>,
|
same_site: Option<SameSite>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -250,7 +249,12 @@ impl CookieSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the `max-age` field in the session cookie being built.
|
/// Sets the `max-age` field in the session cookie being built.
|
||||||
pub fn max_age(mut self, value: Duration) -> CookieSession {
|
pub fn max_age(self, seconds: i64) -> CookieSession {
|
||||||
|
self.max_age_time(time::Duration::seconds(seconds))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the `max-age` field in the session cookie being built.
|
||||||
|
pub fn max_age_time(mut self, value: time::Duration) -> CookieSession {
|
||||||
Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
|
Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@ -317,6 +321,7 @@ where
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use actix_web::{test, web, App};
|
use actix_web::{test, web, App};
|
||||||
|
use bytes::Bytes;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cookie_session() {
|
fn cookie_session() {
|
||||||
@ -338,6 +343,26 @@ mod tests {
|
|||||||
.is_some());
|
.is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn private_cookie() {
|
||||||
|
let mut app = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(CookieSession::private(&[0; 32]).secure(false))
|
||||||
|
.service(web::resource("/").to(|ses: Session| {
|
||||||
|
let _ = ses.set("counter", 100);
|
||||||
|
"test"
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
let request = test::TestRequest::get().to_request();
|
||||||
|
let response = test::block_on(app.call(request)).unwrap();
|
||||||
|
assert!(response
|
||||||
|
.response()
|
||||||
|
.cookies()
|
||||||
|
.find(|c| c.name() == "actix-session")
|
||||||
|
.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cookie_session_extractor() {
|
fn cookie_session_extractor() {
|
||||||
let mut app = test::init_service(
|
let mut app = test::init_service(
|
||||||
@ -357,4 +382,44 @@ mod tests {
|
|||||||
.find(|c| c.name() == "actix-session")
|
.find(|c| c.name() == "actix-session")
|
||||||
.is_some());
|
.is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn basics() {
|
||||||
|
let mut app = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(
|
||||||
|
CookieSession::signed(&[0; 32])
|
||||||
|
.path("/test/")
|
||||||
|
.name("actix-test")
|
||||||
|
.domain("localhost")
|
||||||
|
.http_only(true)
|
||||||
|
.same_site(SameSite::Lax)
|
||||||
|
.max_age(100),
|
||||||
|
)
|
||||||
|
.service(web::resource("/").to(|ses: Session| {
|
||||||
|
let _ = ses.set("counter", 100);
|
||||||
|
"test"
|
||||||
|
}))
|
||||||
|
.service(web::resource("/test/").to(|ses: Session| {
|
||||||
|
let val: usize = ses.get("counter").unwrap().unwrap();
|
||||||
|
format!("counter: {}", val)
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
let request = test::TestRequest::get().to_request();
|
||||||
|
let response = test::block_on(app.call(request)).unwrap();
|
||||||
|
let cookie = response
|
||||||
|
.response()
|
||||||
|
.cookies()
|
||||||
|
.find(|c| c.name() == "actix-test")
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
assert_eq!(cookie.path().unwrap(), "/test/");
|
||||||
|
|
||||||
|
let request = test::TestRequest::with_uri("/test/")
|
||||||
|
.cookie(cookie)
|
||||||
|
.to_request();
|
||||||
|
let body = test::read_response(&mut app, request);
|
||||||
|
assert_eq!(body, Bytes::from_static(b"counter: 100"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,11 +20,11 @@ path = "src/lib.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.8.0"
|
actix = "0.8.0"
|
||||||
actix-web = "1.0.0-alpha.5"
|
actix-web = "1.0.0-alpha.5"
|
||||||
actix-http = "0.1.0-alpha.5"
|
actix-http = "0.1.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-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||||
|
@ -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.0-alpha.5", features=["ssl"] }
|
actix-http = { version = "0.1.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||||
futures = { version = "0.1" }
|
futures = { version = "0.1" }
|
||||||
|
@ -1,5 +1,21 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-04-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to specify server address for http and ws requests.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* `ClientRequest::if_true()` and `ClientRequest::if_some()` use instance instead of ref
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
|
* No changes
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0-alpha.6] - 2019-04-14
|
## [0.1.0-alpha.6] - 2019-04-14
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "awc"
|
name = "awc"
|
||||||
version = "0.1.0-alpha.6"
|
version = "0.1.1"
|
||||||
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"
|
||||||
@ -38,7 +38,7 @@ 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.3.6"
|
||||||
actix-http = "0.1.0-alpha.5"
|
actix-http = "0.1.1"
|
||||||
base64 = "0.10.1"
|
base64 = "0.10.1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.14"
|
||||||
@ -56,10 +56,10 @@ 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-alpha.6", features=["ssl"] }
|
||||||
actix-http = { version = "0.1.0-alpha.5", features=["ssl"] }
|
actix-http = { version = "0.1.1", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||||
actix-utils = "0.3.4"
|
actix-utils = "0.3.4"
|
||||||
actix-server = { version = "0.4.1", features=["ssl"] }
|
actix-server = { version = "0.4.3", 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"
|
||||||
|
@ -1 +1,33 @@
|
|||||||
# Actix http client [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/awc) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Actix http client [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/awc) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
An HTTP Client
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [User Guide](https://actix.rs/docs/)
|
||||||
|
* [API Documentation](https://docs.rs/awc/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [awc](https://crates.io/crates/awc)
|
||||||
|
* Minimum supported Rust version: 1.33 or later
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_rt::System;
|
||||||
|
use awc::Client;
|
||||||
|
use futures::future::{Future, lazy};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
System::new("test").block_on(lazy(|| {
|
||||||
|
let mut client = Client::default();
|
||||||
|
|
||||||
|
client.get("http://www.rust-lang.org") // <- Create request builder
|
||||||
|
.header("User-Agent", "Actix-web")
|
||||||
|
.send() // <- Send http request
|
||||||
|
.and_then(|response| { // <- server http response
|
||||||
|
println!("Response: {:?}", response);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
@ -3,8 +3,8 @@ use std::fmt;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use actix_http::client::{ConnectError, Connection, Connector};
|
use actix_http::client::{Connect, ConnectError, Connection, Connector};
|
||||||
use actix_http::http::{header, HeaderMap, HeaderName, HttpTryFrom, Uri};
|
use actix_http::http::{header, HeaderMap, HeaderName, HttpTryFrom};
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
|
|
||||||
use crate::connect::ConnectorWrapper;
|
use crate::connect::ConnectorWrapper;
|
||||||
@ -40,7 +40,7 @@ impl ClientBuilder {
|
|||||||
/// Use custom connector service.
|
/// Use custom connector service.
|
||||||
pub fn connector<T>(mut self, connector: T) -> Self
|
pub fn connector<T>(mut self, connector: T) -> Self
|
||||||
where
|
where
|
||||||
T: Service<Request = Uri, Error = ConnectError> + 'static,
|
T: Service<Request = Connect, Error = ConnectError> + 'static,
|
||||||
T::Response: Connection,
|
T::Response: Connection,
|
||||||
<T::Response as Connection>::Future: 'static,
|
<T::Response as Connection>::Future: 'static,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
use std::{fmt, io};
|
use std::{fmt, io, net};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_http::body::Body;
|
use actix_http::body::Body;
|
||||||
use actix_http::client::{ConnectError, Connection, SendRequestError};
|
use actix_http::client::{
|
||||||
|
Connect as ClientConnect, ConnectError, Connection, SendRequestError,
|
||||||
|
};
|
||||||
use actix_http::h1::ClientCodec;
|
use actix_http::h1::ClientCodec;
|
||||||
use actix_http::{http, RequestHead, ResponseHead};
|
use actix_http::{RequestHead, ResponseHead};
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use futures::{Future, Poll};
|
use futures::{Future, Poll};
|
||||||
|
|
||||||
@ -17,12 +19,14 @@ pub(crate) trait Connect {
|
|||||||
&mut self,
|
&mut self,
|
||||||
head: RequestHead,
|
head: RequestHead,
|
||||||
body: Body,
|
body: Body,
|
||||||
|
addr: Option<net::SocketAddr>,
|
||||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>>;
|
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>>;
|
||||||
|
|
||||||
/// Send request, returns Response and Framed
|
/// Send request, returns Response and Framed
|
||||||
fn open_tunnel(
|
fn open_tunnel(
|
||||||
&mut self,
|
&mut self,
|
||||||
head: RequestHead,
|
head: RequestHead,
|
||||||
|
addr: Option<net::SocketAddr>,
|
||||||
) -> Box<
|
) -> Box<
|
||||||
Future<
|
Future<
|
||||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||||
@ -33,7 +37,7 @@ pub(crate) trait Connect {
|
|||||||
|
|
||||||
impl<T> Connect for ConnectorWrapper<T>
|
impl<T> Connect for ConnectorWrapper<T>
|
||||||
where
|
where
|
||||||
T: Service<Request = http::Uri, Error = ConnectError>,
|
T: Service<Request = ClientConnect, Error = ConnectError>,
|
||||||
T::Response: Connection,
|
T::Response: Connection,
|
||||||
<T::Response as Connection>::Io: 'static,
|
<T::Response as Connection>::Io: 'static,
|
||||||
<T::Response as Connection>::Future: 'static,
|
<T::Response as Connection>::Future: 'static,
|
||||||
@ -44,11 +48,15 @@ where
|
|||||||
&mut self,
|
&mut self,
|
||||||
head: RequestHead,
|
head: RequestHead,
|
||||||
body: Body,
|
body: Body,
|
||||||
|
addr: Option<net::SocketAddr>,
|
||||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>> {
|
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>> {
|
||||||
Box::new(
|
Box::new(
|
||||||
self.0
|
self.0
|
||||||
// connect to the host
|
// connect to the host
|
||||||
.call(head.uri.clone())
|
.call(ClientConnect {
|
||||||
|
uri: head.uri.clone(),
|
||||||
|
addr,
|
||||||
|
})
|
||||||
.from_err()
|
.from_err()
|
||||||
// send request
|
// send request
|
||||||
.and_then(move |connection| connection.send_request(head, body))
|
.and_then(move |connection| connection.send_request(head, body))
|
||||||
@ -59,6 +67,7 @@ where
|
|||||||
fn open_tunnel(
|
fn open_tunnel(
|
||||||
&mut self,
|
&mut self,
|
||||||
head: RequestHead,
|
head: RequestHead,
|
||||||
|
addr: Option<net::SocketAddr>,
|
||||||
) -> Box<
|
) -> Box<
|
||||||
Future<
|
Future<
|
||||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||||
@ -68,7 +77,10 @@ where
|
|||||||
Box::new(
|
Box::new(
|
||||||
self.0
|
self.0
|
||||||
// connect to the host
|
// connect to the host
|
||||||
.call(head.uri.clone())
|
.call(ClientConnect {
|
||||||
|
uri: head.uri.clone(),
|
||||||
|
addr,
|
||||||
|
})
|
||||||
.from_err()
|
.from_err()
|
||||||
// send request
|
// send request
|
||||||
.and_then(move |connection| connection.open_tunnel(head))
|
.and_then(move |connection| connection.open_tunnel(head))
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
use std::fmt;
|
|
||||||
use std::fmt::Write as FmtWrite;
|
use std::fmt::Write as FmtWrite;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
use std::{fmt, net};
|
||||||
|
|
||||||
use bytes::{BufMut, Bytes, BytesMut};
|
use bytes::{BufMut, Bytes, BytesMut};
|
||||||
use futures::future::{err, Either};
|
use futures::future::{err, Either};
|
||||||
@ -60,6 +60,7 @@ const HTTPS_ENCODING: &str = "gzip, deflate";
|
|||||||
pub struct ClientRequest {
|
pub struct ClientRequest {
|
||||||
pub(crate) head: RequestHead,
|
pub(crate) head: RequestHead,
|
||||||
err: Option<HttpError>,
|
err: Option<HttpError>,
|
||||||
|
addr: Option<net::SocketAddr>,
|
||||||
cookies: Option<CookieJar>,
|
cookies: Option<CookieJar>,
|
||||||
response_decompress: bool,
|
response_decompress: bool,
|
||||||
timeout: Option<Duration>,
|
timeout: Option<Duration>,
|
||||||
@ -76,6 +77,7 @@ impl ClientRequest {
|
|||||||
config,
|
config,
|
||||||
head: RequestHead::default(),
|
head: RequestHead::default(),
|
||||||
err: None,
|
err: None,
|
||||||
|
addr: None,
|
||||||
cookies: None,
|
cookies: None,
|
||||||
timeout: None,
|
timeout: None,
|
||||||
response_decompress: true,
|
response_decompress: true,
|
||||||
@ -97,6 +99,15 @@ impl ClientRequest {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set socket address of the server.
|
||||||
|
///
|
||||||
|
/// This address is used for connection. If address is not
|
||||||
|
/// provided url's host name get resolved.
|
||||||
|
pub fn address(mut self, addr: net::SocketAddr) -> Self {
|
||||||
|
self.addr = Some(addr);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Set HTTP method of this request.
|
/// Set HTTP method of this request.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn method(mut self, method: Method) -> Self {
|
pub fn method(mut self, method: Method) -> Self {
|
||||||
@ -331,27 +342,29 @@ impl ClientRequest {
|
|||||||
|
|
||||||
/// This method calls provided closure with builder reference if
|
/// This method calls provided closure with builder reference if
|
||||||
/// value is `true`.
|
/// value is `true`.
|
||||||
pub fn if_true<F>(mut self, value: bool, f: F) -> Self
|
pub fn if_true<F>(self, value: bool, f: F) -> Self
|
||||||
where
|
where
|
||||||
F: FnOnce(&mut ClientRequest),
|
F: FnOnce(ClientRequest) -> ClientRequest,
|
||||||
{
|
{
|
||||||
if value {
|
if value {
|
||||||
f(&mut self);
|
f(self)
|
||||||
}
|
} else {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// This method calls provided closure with builder reference if
|
/// This method calls provided closure with builder reference if
|
||||||
/// value is `Some`.
|
/// value is `Some`.
|
||||||
pub fn if_some<T, F>(mut self, value: Option<T>, f: F) -> Self
|
pub fn if_some<T, F>(self, value: Option<T>, f: F) -> Self
|
||||||
where
|
where
|
||||||
F: FnOnce(T, &mut ClientRequest),
|
F: FnOnce(T, ClientRequest) -> ClientRequest,
|
||||||
{
|
{
|
||||||
if let Some(val) = value {
|
if let Some(val) = value {
|
||||||
f(val, &mut self);
|
f(val, self)
|
||||||
}
|
} else {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Complete request construction and send body.
|
/// Complete request construction and send body.
|
||||||
pub fn send_body<B>(
|
pub fn send_body<B>(
|
||||||
@ -433,7 +446,7 @@ impl ClientRequest {
|
|||||||
let fut = config
|
let fut = config
|
||||||
.connector
|
.connector
|
||||||
.borrow_mut()
|
.borrow_mut()
|
||||||
.send_request(head, body.into())
|
.send_request(head, body.into(), slf.addr)
|
||||||
.map(move |res| {
|
.map(move |res| {
|
||||||
res.map_body(|head, payload| {
|
res.map_body(|head, payload| {
|
||||||
if response_decompress {
|
if response_decompress {
|
||||||
@ -564,9 +577,21 @@ mod tests {
|
|||||||
.version(Version::HTTP_2)
|
.version(Version::HTTP_2)
|
||||||
.set(header::Date(SystemTime::now().into()))
|
.set(header::Date(SystemTime::now().into()))
|
||||||
.content_type("plain/text")
|
.content_type("plain/text")
|
||||||
|
.if_true(true, |req| req.header(header::SERVER, "awc"))
|
||||||
|
.if_true(false, |req| req.header(header::EXPECT, "awc"))
|
||||||
|
.if_some(Some("server"), |val, req| {
|
||||||
|
req.header(header::USER_AGENT, val)
|
||||||
|
})
|
||||||
|
.if_some(Option::<&str>::None, |_, req| {
|
||||||
|
req.header(header::ALLOW, "1")
|
||||||
|
})
|
||||||
.content_length(100);
|
.content_length(100);
|
||||||
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!(req.headers().contains_key(header::SERVER));
|
||||||
|
assert!(req.headers().contains_key(header::USER_AGENT));
|
||||||
|
assert!(!req.headers().contains_key(header::ALLOW));
|
||||||
|
assert!(!req.headers().contains_key(header::EXPECT));
|
||||||
assert_eq!(req.head.version, Version::HTTP_2);
|
assert_eq!(req.head.version, Version::HTTP_2);
|
||||||
let _ = req.headers_mut();
|
let _ = req.headers_mut();
|
||||||
let _ = req.send_body("");
|
let _ = req.send_body("");
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
//! Websockets client
|
//! Websockets client
|
||||||
use std::fmt::Write as FmtWrite;
|
use std::fmt::Write as FmtWrite;
|
||||||
|
use std::net::SocketAddr;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::{fmt, str};
|
use std::{fmt, str};
|
||||||
|
|
||||||
@ -29,6 +30,7 @@ pub struct WebsocketsRequest {
|
|||||||
err: Option<HttpError>,
|
err: Option<HttpError>,
|
||||||
origin: Option<HeaderValue>,
|
origin: Option<HeaderValue>,
|
||||||
protocols: Option<String>,
|
protocols: Option<String>,
|
||||||
|
addr: Option<SocketAddr>,
|
||||||
max_size: usize,
|
max_size: usize,
|
||||||
server_mode: bool,
|
server_mode: bool,
|
||||||
cookies: Option<CookieJar>,
|
cookies: Option<CookieJar>,
|
||||||
@ -55,6 +57,7 @@ impl WebsocketsRequest {
|
|||||||
head,
|
head,
|
||||||
err,
|
err,
|
||||||
config,
|
config,
|
||||||
|
addr: None,
|
||||||
origin: None,
|
origin: None,
|
||||||
protocols: None,
|
protocols: None,
|
||||||
max_size: 65_536,
|
max_size: 65_536,
|
||||||
@ -63,6 +66,15 @@ impl WebsocketsRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set socket address of the server.
|
||||||
|
///
|
||||||
|
/// This address is used for connection. If address is not
|
||||||
|
/// provided url's host name get resolved.
|
||||||
|
pub fn address(mut self, addr: SocketAddr) -> Self {
|
||||||
|
self.addr = Some(addr);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Set supported websocket protocols
|
/// Set supported websocket protocols
|
||||||
pub fn protocols<U, V>(mut self, protos: U) -> Self
|
pub fn protocols<U, V>(mut self, protos: U) -> Self
|
||||||
where
|
where
|
||||||
@ -274,7 +286,7 @@ impl WebsocketsRequest {
|
|||||||
.config
|
.config
|
||||||
.connector
|
.connector
|
||||||
.borrow_mut()
|
.borrow_mut()
|
||||||
.open_tunnel(head)
|
.open_tunnel(head, self.addr)
|
||||||
.from_err()
|
.from_err()
|
||||||
.and_then(move |(head, framed)| {
|
.and_then(move |(head, framed)| {
|
||||||
// verify response
|
// verify response
|
||||||
@ -445,12 +457,14 @@ mod tests {
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
"Bearer someS3cr3tAutht0k3n"
|
"Bearer someS3cr3tAutht0k3n"
|
||||||
);
|
);
|
||||||
|
let _ = req.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn basics() {
|
fn basics() {
|
||||||
|
actix_http_test::run_on(|| {
|
||||||
let req = Client::new()
|
let req = Client::new()
|
||||||
.ws("/")
|
.ws("http://localhost/")
|
||||||
.origin("test-origin")
|
.origin("test-origin")
|
||||||
.max_frame_size(100)
|
.max_frame_size(100)
|
||||||
.server_mode()
|
.server_mode()
|
||||||
@ -470,5 +484,14 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("json")
|
header::HeaderValue::from_static("json")
|
||||||
);
|
);
|
||||||
let _ = req.connect();
|
let _ = req.connect();
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(Client::new().ws("/").connect().poll().is_err());
|
||||||
|
assert!(Client::new().ws("http:///test").connect().poll().is_err());
|
||||||
|
assert!(Client::new()
|
||||||
|
.ws("hmm://test.com/")
|
||||||
|
.connect()
|
||||||
|
.poll()
|
||||||
|
.is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@ -63,6 +64,38 @@ fn test_simple() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_json() {
|
||||||
|
let mut srv = TestServer::new(|| {
|
||||||
|
HttpService::new(App::new().service(
|
||||||
|
web::resource("/").route(web::to(|_: web::Json<String>| HttpResponse::Ok())),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
|
let request = srv
|
||||||
|
.get("/")
|
||||||
|
.header("x-test", "111")
|
||||||
|
.send_json(&"TEST".to_string());
|
||||||
|
let response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_form() {
|
||||||
|
let mut srv = TestServer::new(|| {
|
||||||
|
HttpService::new(App::new().service(web::resource("/").route(web::to(
|
||||||
|
|_: web::Form<HashMap<String, String>>| HttpResponse::Ok(),
|
||||||
|
))))
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
let _ = data.insert("key".to_string(), "TEST".to_string());
|
||||||
|
|
||||||
|
let request = srv.get("/").header("x-test", "111").send_form(&data);
|
||||||
|
let response = srv.block_on(request).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_timeout() {
|
fn test_timeout() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
|
@ -265,13 +265,12 @@ tuple_from_req!(TupleFromRequest10, (0, A), (1, B), (2, C), (3, D), (4, E), (5,
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_http::http::header;
|
use actix_http::http::header;
|
||||||
use actix_router::ResourceDef;
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use serde_derive::Deserialize;
|
use serde_derive::Deserialize;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::test::{block_on, TestRequest};
|
use crate::test::{block_on, TestRequest};
|
||||||
use crate::types::{Form, FormConfig, Path, Query};
|
use crate::types::{Form, FormConfig};
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, PartialEq)]
|
#[derive(Deserialize, Debug, PartialEq)]
|
||||||
struct Info {
|
struct Info {
|
||||||
@ -350,58 +349,4 @@ mod tests {
|
|||||||
block_on(Result::<Form<Info>, Error>::from_request(&req, &mut pl)).unwrap();
|
block_on(Result::<Form<Info>, Error>::from_request(&req, &mut pl)).unwrap();
|
||||||
assert!(r.is_err());
|
assert!(r.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct MyStruct {
|
|
||||||
key: String,
|
|
||||||
value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Id {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Test2 {
|
|
||||||
key: String,
|
|
||||||
value: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_request_extract() {
|
|
||||||
let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
|
|
||||||
|
|
||||||
let resource = ResourceDef::new("/{key}/{value}/");
|
|
||||||
resource.match_path(req.match_info_mut());
|
|
||||||
|
|
||||||
let (req, mut pl) = req.into_parts();
|
|
||||||
let s = Path::<MyStruct>::from_request(&req, &mut pl).unwrap();
|
|
||||||
assert_eq!(s.key, "name");
|
|
||||||
assert_eq!(s.value, "user1");
|
|
||||||
|
|
||||||
let s = Path::<(String, String)>::from_request(&req, &mut pl).unwrap();
|
|
||||||
assert_eq!(s.0, "name");
|
|
||||||
assert_eq!(s.1, "user1");
|
|
||||||
|
|
||||||
let s = Query::<Id>::from_request(&req, &mut pl).unwrap();
|
|
||||||
assert_eq!(s.id, "test");
|
|
||||||
|
|
||||||
let mut req = TestRequest::with_uri("/name/32/").to_srv_request();
|
|
||||||
let resource = ResourceDef::new("/{key}/{value}/");
|
|
||||||
resource.match_path(req.match_info_mut());
|
|
||||||
|
|
||||||
let (req, mut pl) = req.into_parts();
|
|
||||||
let s = Path::<Test2>::from_request(&req, &mut pl).unwrap();
|
|
||||||
assert_eq!(s.as_ref().key, "name");
|
|
||||||
assert_eq!(s.value, 32);
|
|
||||||
|
|
||||||
let s = Path::<(String, u8)>::from_request(&req, &mut pl).unwrap();
|
|
||||||
assert_eq!(s.0, "name");
|
|
||||||
assert_eq!(s.1, 32);
|
|
||||||
|
|
||||||
let res = Path::<Vec<String>>::from_request(&req, &mut pl).unwrap();
|
|
||||||
assert_eq!(res[0], "name".to_owned());
|
|
||||||
assert_eq!(res[1], "32".to_owned());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -427,8 +427,13 @@ impl CookieIdentityPolicy {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the `max-age` field in the session cookie being built.
|
/// Sets the `max-age` field in the session cookie being built with given number of seconds.
|
||||||
pub fn max_age(mut self, value: Duration) -> CookieIdentityPolicy {
|
pub fn max_age(self, seconds: i64) -> CookieIdentityPolicy {
|
||||||
|
self.max_age_time(Duration::seconds(seconds))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the `max-age` field in the session cookie being built with `chrono::Duration`.
|
||||||
|
pub fn max_age_time(mut self, value: Duration) -> CookieIdentityPolicy {
|
||||||
Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
|
Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@ -525,4 +530,56 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
assert!(resp.headers().contains_key(header::SET_COOKIE))
|
assert!(resp.headers().contains_key(header::SET_COOKIE))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_max_age_time() {
|
||||||
|
let duration = Duration::days(1);
|
||||||
|
let mut srv = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(IdentityService::new(
|
||||||
|
CookieIdentityPolicy::new(&[0; 32])
|
||||||
|
.domain("www.rust-lang.org")
|
||||||
|
.name("actix_auth")
|
||||||
|
.path("/")
|
||||||
|
.max_age_time(duration)
|
||||||
|
.secure(true),
|
||||||
|
))
|
||||||
|
.service(web::resource("/login").to(|id: Identity| {
|
||||||
|
id.remember("test".to_string());
|
||||||
|
HttpResponse::Ok()
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
let resp =
|
||||||
|
test::call_service(&mut srv, TestRequest::with_uri("/login").to_request());
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
assert!(resp.headers().contains_key(header::SET_COOKIE));
|
||||||
|
let c = resp.response().cookies().next().unwrap().to_owned();
|
||||||
|
assert_eq!(duration, c.max_age().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_identity_max_age() {
|
||||||
|
let seconds = 60;
|
||||||
|
let mut srv = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(IdentityService::new(
|
||||||
|
CookieIdentityPolicy::new(&[0; 32])
|
||||||
|
.domain("www.rust-lang.org")
|
||||||
|
.name("actix_auth")
|
||||||
|
.path("/")
|
||||||
|
.max_age(seconds)
|
||||||
|
.secure(true),
|
||||||
|
))
|
||||||
|
.service(web::resource("/login").to(|id: Identity| {
|
||||||
|
id.remember("test".to_string());
|
||||||
|
HttpResponse::Ok()
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
let resp =
|
||||||
|
test::call_service(&mut srv, TestRequest::with_uri("/login").to_request());
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
assert!(resp.headers().contains_key(header::SET_COOKIE));
|
||||||
|
let c = resp.response().cookies().next().unwrap().to_owned();
|
||||||
|
assert_eq!(Duration::seconds(seconds as i64), c.max_age().unwrap());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,7 @@ pub mod cors;
|
|||||||
mod defaultheaders;
|
mod defaultheaders;
|
||||||
pub mod errhandlers;
|
pub mod errhandlers;
|
||||||
mod logger;
|
mod logger;
|
||||||
|
pub mod normalize;
|
||||||
|
|
||||||
pub use self::defaultheaders::DefaultHeaders;
|
pub use self::defaultheaders::DefaultHeaders;
|
||||||
pub use self::logger::Logger;
|
pub use self::logger::Logger;
|
||||||
|
108
src/middleware/normalize.rs
Normal file
108
src/middleware/normalize.rs
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
//! `Middleware` to normalize request's URI
|
||||||
|
|
||||||
|
use actix_service::{Service, Transform};
|
||||||
|
use futures::future::{self, FutureResult};
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
use crate::service::{ServiceRequest, ServiceResponse};
|
||||||
|
|
||||||
|
#[derive(Default, Clone, Copy)]
|
||||||
|
/// `Middleware` to normalize request's URI in place
|
||||||
|
///
|
||||||
|
/// Performs following:
|
||||||
|
///
|
||||||
|
/// - Merges multiple slashes into one.
|
||||||
|
pub struct NormalizePath;
|
||||||
|
|
||||||
|
impl<S> Transform<S> for NormalizePath
|
||||||
|
where
|
||||||
|
S: Service<Request = ServiceRequest, Response = ServiceResponse>,
|
||||||
|
{
|
||||||
|
type Request = ServiceRequest;
|
||||||
|
type Response = ServiceResponse;
|
||||||
|
type Error = S::Error;
|
||||||
|
type InitError = ();
|
||||||
|
type Transform = NormalizePathNormalization<S>;
|
||||||
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
|
|
||||||
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
|
future::ok(NormalizePathNormalization {
|
||||||
|
service,
|
||||||
|
merge_slash: Regex::new("//+").unwrap(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NormalizePathNormalization<S> {
|
||||||
|
service: S,
|
||||||
|
merge_slash: Regex,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> Service for NormalizePathNormalization<S>
|
||||||
|
where
|
||||||
|
S: Service<Request = ServiceRequest, Response = ServiceResponse>,
|
||||||
|
{
|
||||||
|
type Request = ServiceRequest;
|
||||||
|
type Response = ServiceResponse;
|
||||||
|
type Error = S::Error;
|
||||||
|
type Future = S::Future;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||||
|
self.service.poll_ready()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
||||||
|
let head = req.head_mut();
|
||||||
|
|
||||||
|
let path = head.uri.path();
|
||||||
|
let original_len = path.len();
|
||||||
|
let path = self.merge_slash.replace_all(path, "/");
|
||||||
|
|
||||||
|
if original_len != path.len() {
|
||||||
|
head.uri = path.parse().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.service.call(req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use actix_service::FnService;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::dev::ServiceRequest;
|
||||||
|
use crate::test::{block_on, TestRequest};
|
||||||
|
use crate::HttpResponse;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_in_place_normalization() {
|
||||||
|
let srv = FnService::new(|req: ServiceRequest| {
|
||||||
|
assert_eq!("/v1/something/", req.path());
|
||||||
|
req.into_response(HttpResponse::Ok().finish())
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut normalize = block_on(NormalizePath.new_transform(srv)).unwrap();
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/v1//something////").to_srv_request();
|
||||||
|
let res = block_on(normalize.call(req)).unwrap();
|
||||||
|
assert!(res.status().is_success());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_normalize_nothing() {
|
||||||
|
const URI: &str = "/v1/something/";
|
||||||
|
|
||||||
|
let srv = FnService::new(|req: ServiceRequest| {
|
||||||
|
assert_eq!(URI, req.path());
|
||||||
|
req.into_response(HttpResponse::Ok().finish())
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut normalize = block_on(NormalizePath.new_transform(srv)).unwrap();
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri(URI).to_srv_request();
|
||||||
|
let res = block_on(normalize.call(req)).unwrap();
|
||||||
|
assert!(res.status().is_success());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -307,11 +307,11 @@ pub(crate) mod tests {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/none").to_request();
|
let req = TestRequest::with_uri("/none").to_request();
|
||||||
let resp = TestRequest::block_on(srv.call(req)).unwrap();
|
let resp = block_on(srv.call(req)).unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/some").to_request();
|
let req = TestRequest::with_uri("/some").to_request();
|
||||||
let resp = TestRequest::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);
|
||||||
match resp.response().body() {
|
match resp.response().body() {
|
||||||
ResponseBody::Body(Body::Bytes(ref b)) => {
|
ResponseBody::Body(Body::Bytes(ref b)) => {
|
||||||
|
@ -53,7 +53,7 @@ pub struct ServiceRequest {
|
|||||||
|
|
||||||
impl ServiceRequest {
|
impl ServiceRequest {
|
||||||
/// Construct service request from parts
|
/// Construct service request from parts
|
||||||
pub fn from_parts(req: HttpRequest, payload: Payload) -> Self {
|
pub(crate) fn from_parts(req: HttpRequest, payload: Payload) -> Self {
|
||||||
ServiceRequest { req, payload }
|
ServiceRequest { req, payload }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
70
src/test.rs
70
src/test.rs
@ -58,7 +58,7 @@ where
|
|||||||
/// This function panics on nested call.
|
/// This function panics on nested call.
|
||||||
pub fn run_on<F, R>(f: F) -> R
|
pub fn run_on<F, R>(f: F) -> R
|
||||||
where
|
where
|
||||||
F: Fn() -> R,
|
F: FnOnce() -> R,
|
||||||
{
|
{
|
||||||
RT.with(move |rt| rt.borrow_mut().block_on(lazy(|| Ok::<_, ()>(f()))))
|
RT.with(move |rt| rt.borrow_mut().block_on(lazy(|| Ok::<_, ()>(f()))))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@ -117,7 +117,9 @@ where
|
|||||||
S::InitError: std::fmt::Debug,
|
S::InitError: std::fmt::Debug,
|
||||||
{
|
{
|
||||||
let cfg = ServerConfig::new("127.0.0.1:8080".parse().unwrap());
|
let cfg = ServerConfig::new("127.0.0.1:8080".parse().unwrap());
|
||||||
block_on(app.into_new_service().new_service(&cfg)).unwrap()
|
let srv = app.into_new_service();
|
||||||
|
let fut = run_on(move || srv.new_service(&cfg));
|
||||||
|
block_on(fut).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls service and waits for response future completion.
|
/// Calls service and waits for response future completion.
|
||||||
@ -146,7 +148,7 @@ where
|
|||||||
S: Service<Request = R, Response = ServiceResponse<B>, Error = E>,
|
S: Service<Request = R, Response = ServiceResponse<B>, Error = E>,
|
||||||
E: std::fmt::Debug,
|
E: std::fmt::Debug,
|
||||||
{
|
{
|
||||||
block_on(app.call(req)).unwrap()
|
block_on(run_on(move || app.call(req))).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper function that returns a response body of a TestRequest
|
/// Helper function that returns a response body of a TestRequest
|
||||||
@ -178,13 +180,15 @@ where
|
|||||||
S: Service<Request = Request, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<Request = Request, Response = ServiceResponse<B>, Error = Error>,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
{
|
{
|
||||||
block_on(app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
block_on(run_on(move || {
|
||||||
|
app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
||||||
resp.take_body()
|
resp.take_body()
|
||||||
.fold(BytesMut::new(), move |mut body, chunk| {
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
||||||
body.extend_from_slice(&chunk);
|
body.extend_from_slice(&chunk);
|
||||||
Ok::<_, Error>(body)
|
Ok::<_, Error>(body)
|
||||||
})
|
})
|
||||||
.map(|body: BytesMut| body.freeze())
|
.map(|body: BytesMut| body.freeze())
|
||||||
|
})
|
||||||
}))
|
}))
|
||||||
.unwrap_or_else(|_| panic!("read_response failed at block_on unwrap"))
|
.unwrap_or_else(|_| panic!("read_response failed at block_on unwrap"))
|
||||||
}
|
}
|
||||||
@ -229,7 +233,8 @@ where
|
|||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
T: DeserializeOwned,
|
T: DeserializeOwned,
|
||||||
{
|
{
|
||||||
block_on(app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
block_on(run_on(move || {
|
||||||
|
app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
||||||
resp.take_body()
|
resp.take_body()
|
||||||
.fold(BytesMut::new(), move |mut body, chunk| {
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
||||||
body.extend_from_slice(&chunk);
|
body.extend_from_slice(&chunk);
|
||||||
@ -240,6 +245,7 @@ where
|
|||||||
panic!("read_response_json failed during deserialization")
|
panic!("read_response_json failed during deserialization")
|
||||||
}))
|
}))
|
||||||
})
|
})
|
||||||
|
})
|
||||||
}))
|
}))
|
||||||
.unwrap_or_else(|_| panic!("read_response_json failed at block_on unwrap"))
|
.unwrap_or_else(|_| panic!("read_response_json failed at block_on unwrap"))
|
||||||
}
|
}
|
||||||
@ -330,6 +336,16 @@ impl TestRequest {
|
|||||||
TestRequest::default().method(Method::POST)
|
TestRequest::default().method(Method::POST)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create TestRequest and set method to `Method::PUT`
|
||||||
|
pub fn put() -> TestRequest {
|
||||||
|
TestRequest::default().method(Method::PUT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create TestRequest and set method to `Method::PATCH`
|
||||||
|
pub fn patch() -> TestRequest {
|
||||||
|
TestRequest::default().method(Method::PATCH)
|
||||||
|
}
|
||||||
|
|
||||||
/// 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);
|
||||||
@ -460,23 +476,6 @@ impl TestRequest {
|
|||||||
req.set_route_data(Some(Rc::new(self.route_data)));
|
req.set_route_data(Some(Rc::new(self.route_data)));
|
||||||
(req, payload)
|
(req, payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the provided future, blocking the current thread until the 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_on<F>(f: F) -> Result<F::Item, F::Error>
|
|
||||||
where
|
|
||||||
F: Future,
|
|
||||||
{
|
|
||||||
block_on(f)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -504,6 +503,33 @@ mod tests {
|
|||||||
assert_eq!(*data.get_ref(), 10);
|
assert_eq!(*data.get_ref(), 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_request_methods() {
|
||||||
|
let mut app = init_service(
|
||||||
|
App::new().service(
|
||||||
|
web::resource("/index.html")
|
||||||
|
.route(web::put().to(|| HttpResponse::Ok().body("put!")))
|
||||||
|
.route(web::patch().to(|| HttpResponse::Ok().body("patch!"))),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
let put_req = TestRequest::put()
|
||||||
|
.uri("/index.html")
|
||||||
|
.header(header::CONTENT_TYPE, "application/json")
|
||||||
|
.to_request();
|
||||||
|
|
||||||
|
let result = read_response(&mut app, put_req);
|
||||||
|
assert_eq!(result, Bytes::from_static(b"put!"));
|
||||||
|
|
||||||
|
let patch_req = TestRequest::patch()
|
||||||
|
.uri("/index.html")
|
||||||
|
.header(header::CONTENT_TYPE, "application/json")
|
||||||
|
.to_request();
|
||||||
|
|
||||||
|
let result = read_response(&mut app, patch_req);
|
||||||
|
assert_eq!(result, Bytes::from_static(b"patch!"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_response() {
|
fn test_response() {
|
||||||
let mut app = init_service(
|
let mut app = init_service(
|
||||||
|
@ -331,10 +331,6 @@ mod tests {
|
|||||||
|
|
||||||
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
|
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
|
||||||
match err {
|
match err {
|
||||||
UrlencodedError::Chunked => match other {
|
|
||||||
UrlencodedError::Chunked => true,
|
|
||||||
_ => false,
|
|
||||||
},
|
|
||||||
UrlencodedError::Overflow => match other {
|
UrlencodedError::Overflow => match other {
|
||||||
UrlencodedError::Overflow => true,
|
UrlencodedError::Overflow => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
|
@ -171,10 +171,25 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_router::ResourceDef;
|
use actix_router::ResourceDef;
|
||||||
|
use derive_more::Display;
|
||||||
|
use serde_derive::Deserialize;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::test::{block_on, TestRequest};
|
use crate::test::{block_on, TestRequest};
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug, Display)]
|
||||||
|
#[display(fmt = "MyStruct({}, {})", key, value)]
|
||||||
|
struct MyStruct {
|
||||||
|
key: String,
|
||||||
|
value: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Test2 {
|
||||||
|
key: String,
|
||||||
|
value: u32,
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_extract_path_single() {
|
fn test_extract_path_single() {
|
||||||
let resource = ResourceDef::new("/{value}/");
|
let resource = ResourceDef::new("/{value}/");
|
||||||
@ -184,6 +199,7 @@ mod tests {
|
|||||||
|
|
||||||
let (req, mut pl) = req.into_parts();
|
let (req, mut pl) = req.into_parts();
|
||||||
assert_eq!(*Path::<i8>::from_request(&req, &mut pl).unwrap(), 32);
|
assert_eq!(*Path::<i8>::from_request(&req, &mut pl).unwrap(), 32);
|
||||||
|
assert!(Path::<MyStruct>::from_request(&req, &mut pl).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -213,4 +229,46 @@ mod tests {
|
|||||||
let () = <()>::from_request(&req, &mut pl).unwrap();
|
let () = <()>::from_request(&req, &mut pl).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_request_extract() {
|
||||||
|
let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
|
||||||
|
|
||||||
|
let resource = ResourceDef::new("/{key}/{value}/");
|
||||||
|
resource.match_path(req.match_info_mut());
|
||||||
|
|
||||||
|
let (req, mut pl) = req.into_parts();
|
||||||
|
let mut s = Path::<MyStruct>::from_request(&req, &mut pl).unwrap();
|
||||||
|
assert_eq!(s.key, "name");
|
||||||
|
assert_eq!(s.value, "user1");
|
||||||
|
s.value = "user2".to_string();
|
||||||
|
assert_eq!(s.value, "user2");
|
||||||
|
assert_eq!(
|
||||||
|
format!("{}, {:?}", s, s),
|
||||||
|
"MyStruct(name, user2), MyStruct { key: \"name\", value: \"user2\" }"
|
||||||
|
);
|
||||||
|
let s = s.into_inner();
|
||||||
|
assert_eq!(s.value, "user2");
|
||||||
|
|
||||||
|
let s = Path::<(String, String)>::from_request(&req, &mut pl).unwrap();
|
||||||
|
assert_eq!(s.0, "name");
|
||||||
|
assert_eq!(s.1, "user1");
|
||||||
|
|
||||||
|
let mut req = TestRequest::with_uri("/name/32/").to_srv_request();
|
||||||
|
let resource = ResourceDef::new("/{key}/{value}/");
|
||||||
|
resource.match_path(req.match_info_mut());
|
||||||
|
|
||||||
|
let (req, mut pl) = req.into_parts();
|
||||||
|
let s = Path::<Test2>::from_request(&req, &mut pl).unwrap();
|
||||||
|
assert_eq!(s.as_ref().key, "name");
|
||||||
|
assert_eq!(s.value, 32);
|
||||||
|
|
||||||
|
let s = Path::<(String, u8)>::from_request(&req, &mut pl).unwrap();
|
||||||
|
assert_eq!(s.0, "name");
|
||||||
|
assert_eq!(s.1, 32);
|
||||||
|
|
||||||
|
let res = Path::<Vec<String>>::from_request(&req, &mut pl).unwrap();
|
||||||
|
assert_eq!(res[0], "name".to_owned());
|
||||||
|
assert_eq!(res[1], "32".to_owned());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -133,3 +133,35 @@ where
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use derive_more::Display;
|
||||||
|
use serde_derive::Deserialize;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::test::TestRequest;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug, Display)]
|
||||||
|
struct Id {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_request_extract() {
|
||||||
|
let req = TestRequest::with_uri("/name/user1/").to_srv_request();
|
||||||
|
let (req, mut pl) = req.into_parts();
|
||||||
|
assert!(Query::<Id>::from_request(&req, &mut pl).is_err());
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
|
||||||
|
let (req, mut pl) = req.into_parts();
|
||||||
|
|
||||||
|
let mut s = Query::<Id>::from_request(&req, &mut pl).unwrap();
|
||||||
|
assert_eq!(s.id, "test");
|
||||||
|
assert_eq!(format!("{}, {:?}", s, s), "test, Id { id: \"test\" }");
|
||||||
|
|
||||||
|
s.id = "test1".to_string();
|
||||||
|
let s = s.into_inner();
|
||||||
|
assert_eq!(s.id, "test1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,5 +1,10 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
|
* No changes
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0-alpha.3] - 2019-04-02
|
## [0.1.0-alpha.3] - 2019-04-02
|
||||||
|
|
||||||
* Request functions accept path #743
|
* Request functions accept path #743
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http-test"
|
name = "actix-http-test"
|
||||||
version = "0.1.0-alpha.3"
|
version = "0.1.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"
|
||||||
@ -33,9 +33,9 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
|||||||
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.3.6"
|
||||||
actix-server = "0.4.1"
|
actix-server = "0.4.3"
|
||||||
actix-utils = "0.3.5"
|
actix-utils = "0.3.5"
|
||||||
awc = "0.1.0-alpha.5"
|
awc = "0.1.0"
|
||||||
|
|
||||||
base64 = "0.10"
|
base64 = "0.10"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
@ -56,4 +56,4 @@ openssl = { version="0.10", optional = true }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = "1.0.0-alpha.5"
|
actix-web = "1.0.0-alpha.5"
|
||||||
actix-http = "0.1.0-alpha.5"
|
actix-http = "0.1.0"
|
||||||
|
@ -17,7 +17,7 @@ use futures::stream::once;
|
|||||||
use rand::{distributions::Alphanumeric, Rng};
|
use rand::{distributions::Alphanumeric, Rng};
|
||||||
|
|
||||||
use actix_web::middleware::{BodyEncoding, Compress};
|
use actix_web::middleware::{BodyEncoding, Compress};
|
||||||
use actix_web::{http, test, web, App, HttpResponse, HttpServer};
|
use actix_web::{dev, http, test, web, App, HttpResponse, HttpServer};
|
||||||
|
|
||||||
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
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 \
|
||||||
@ -89,6 +89,39 @@ fn test_body_gzip() {
|
|||||||
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
|
||||||
|
#[test]
|
||||||
|
fn test_body_gzip2() {
|
||||||
|
let mut srv = TestServer::new(|| {
|
||||||
|
h1::H1Service::new(
|
||||||
|
App::new()
|
||||||
|
.wrap(Compress::new(ContentEncoding::Gzip))
|
||||||
|
.service(web::resource("/").route(web::to(|| {
|
||||||
|
Response::Ok().body(STR).into_body::<dev::Body>()
|
||||||
|
}))),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut response = srv
|
||||||
|
.block_on(
|
||||||
|
srv.get("/")
|
||||||
|
.no_decompress()
|
||||||
|
.header(ACCEPT_ENCODING, "gzip")
|
||||||
|
.send(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// read response
|
||||||
|
let bytes = srv.block_on(response.body()).unwrap();
|
||||||
|
|
||||||
|
// decode
|
||||||
|
let mut e = GzDecoder::new(&bytes[..]);
|
||||||
|
let mut dec = Vec::new();
|
||||||
|
e.read_to_end(&mut dec).unwrap();
|
||||||
|
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
|
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
|
||||||
#[test]
|
#[test]
|
||||||
fn test_body_encoding_override() {
|
fn test_body_encoding_override() {
|
||||||
|
Reference in New Issue
Block a user