mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-24 01:38:20 +02:00
Compare commits
53 Commits
v1.0.0-alp
...
http-test-
Author | SHA1 | Date | |
---|---|---|---|
|
42644dac3f | ||
|
898ef57080 | ||
|
9702b2d88e | ||
|
d2b0afd859 | ||
|
5f6a1a8249 | ||
|
5d531989e7 | ||
|
3532602299 | ||
|
48bee55087 | ||
|
d00c9bb844 | ||
|
895e409d57 | ||
|
f0789aad05 | ||
|
7e480ab2f7 | ||
|
891f857547 | ||
|
01b1350dcc | ||
|
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 | ||
|
2986077a28 | ||
|
3744957804 | ||
|
420d3064c5 | ||
|
eb4f6b74fb | ||
|
a116c4c2c7 | ||
|
7f674febb1 | ||
|
14252f5ef2 | ||
|
7a28b32f6d | ||
|
09cdf1e302 | ||
|
1eebd47072 | ||
|
002c41a7ca | ||
|
ab4fda6084 | ||
|
f9078d41cd | ||
|
4cc2b38059 |
43
CHANGES.md
43
CHANGES.md
@@ -1,5 +1,48 @@
|
||||
# Changes
|
||||
|
||||
### Added
|
||||
|
||||
* Add helper functions for reading response body `test::read_body()`
|
||||
|
||||
* Added support for `remainder match` (i.e "/path/{tail}*")
|
||||
|
||||
|
||||
### Changed
|
||||
|
||||
* `.to_async()` handler can return `Responder` type #792
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix async web::Data factory handling
|
||||
|
||||
|
||||
## [1.0.0-beta.1] - 2019-04-20
|
||||
|
||||
### Added
|
||||
|
||||
* Add helper functions for reading test response body,
|
||||
`test::read_response()` and test::read_response_json()`
|
||||
|
||||
* Add `.peer_addr()` #744
|
||||
|
||||
* Add `NormalizePath` middleware
|
||||
|
||||
### Changed
|
||||
|
||||
* Rename `RouterConfig` to `ServiceConfig`
|
||||
|
||||
* 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 `TestRequest::app_data()`
|
||||
|
||||
|
||||
## [1.0.0-alpha.6] - 2019-04-14
|
||||
|
||||
### Changed
|
||||
|
32
Cargo.toml
32
Cargo.toml
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "1.0.0-alpha.6"
|
||||
version = "1.0.0-beta.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
@@ -15,6 +15,9 @@ license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||
codecov = { repository = "actix/actix-web", branch = "master", service = "github" }
|
||||
@@ -37,9 +40,6 @@ members = [
|
||||
"test-server",
|
||||
]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
||||
|
||||
[features]
|
||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client"]
|
||||
|
||||
@@ -68,20 +68,20 @@ rust-tls = ["rustls", "actix-server/rust-tls"]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-utils = "0.3.4"
|
||||
actix-router = "0.1.2"
|
||||
actix-router = "0.1.3"
|
||||
actix-rt = "0.2.2"
|
||||
actix-web-codegen = "0.1.0-alpha.6"
|
||||
actix-http = { version = "0.1.0-alpha.5", features=["fail"] }
|
||||
actix-server = "0.4.2"
|
||||
actix-server-config = "0.1.0"
|
||||
actix-web-codegen = "0.1.0-beta.1"
|
||||
actix-http = { version = "0.1.2", features=["fail"] }
|
||||
actix-server = "0.4.3"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
awc = { version = "0.1.0-alpha.6", optional = true }
|
||||
awc = { version = "0.1.1", optional = true }
|
||||
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
encoding = "0.2"
|
||||
futures = "0.1"
|
||||
hashbrown = "0.2.1"
|
||||
hashbrown = "0.2.2"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
net2 = "0.2.33"
|
||||
@@ -90,7 +90,7 @@ regex = "1.0"
|
||||
serde = { version = "1.0", features=["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde_urlencoded = "0.5.3"
|
||||
time = "0.1"
|
||||
time = "0.1.42"
|
||||
url = { version="1.7", features=["query_encoding"] }
|
||||
|
||||
# ssl support
|
||||
@@ -98,9 +98,9 @@ openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "^0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-http = { version = "0.1.0-alpha.5", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
||||
actix-files = { version = "0.1.0-alpha.6" }
|
||||
actix-http = { version = "0.1.2", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.1.1", features=["ssl"] }
|
||||
actix-files = { version = "0.1.0-beta.1" }
|
||||
rand = "0.6"
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
@@ -121,4 +121,4 @@ actix-web-codegen = { path = "actix-web-codegen" }
|
||||
actix-web-actors = { path = "actix-web-actors" }
|
||||
actix-session = { path = "actix-session" }
|
||||
actix-files = { path = "actix-files" }
|
||||
awc = { path = "awc" }
|
||||
awc = { path = "awc" }
|
||||
|
@@ -128,7 +128,7 @@
|
||||
```
|
||||
|
||||
|
||||
* AsyncResponder is removed.
|
||||
* AsyncResponder is removed, use `.to_async()` registration method and `impl Future<>` as result type.
|
||||
|
||||
instead of
|
||||
|
||||
|
@@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Update actix-web to beta.1
|
||||
|
||||
## [0.1.0-alpha.6] - 2019-04-14
|
||||
|
||||
* Update actix-web to alpha6
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-files"
|
||||
version = "0.1.0-alpha.6"
|
||||
version = "0.1.0-beta.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Static files support for actix web."
|
||||
readme = "README.md"
|
||||
@@ -18,7 +18,7 @@ name = "actix_files"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-alpha.6"
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-service = "0.3.4"
|
||||
bitflags = "1"
|
||||
bytes = "0.4"
|
||||
@@ -31,4 +31,4 @@ percent-encoding = "1.0"
|
||||
v_htmlescape = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-alpha.6", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0-beta.1", features=["ssl"] }
|
||||
|
@@ -10,7 +10,7 @@ use std::{cmp, io};
|
||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_web::dev::{
|
||||
HttpServiceFactory, Payload, ResourceDef, ServiceConfig, ServiceRequest,
|
||||
AppService, HttpServiceFactory, Payload, ResourceDef, ServiceRequest,
|
||||
ServiceResponse,
|
||||
};
|
||||
use actix_web::error::{BlockingError, Error, ErrorInternalServerError};
|
||||
@@ -349,7 +349,7 @@ impl Files {
|
||||
}
|
||||
|
||||
impl HttpServiceFactory for Files {
|
||||
fn register(self, config: &mut ServiceConfig) {
|
||||
fn register(self, config: &mut AppService) {
|
||||
if self.default.borrow().is_none() {
|
||||
*self.default.borrow_mut() = Some(config.default_service());
|
||||
}
|
||||
@@ -411,17 +411,16 @@ impl FilesService {
|
||||
fn handle_err(
|
||||
&mut self,
|
||||
e: io::Error,
|
||||
req: HttpRequest,
|
||||
payload: Payload,
|
||||
req: ServiceRequest,
|
||||
) -> Either<
|
||||
FutureResult<ServiceResponse, Error>,
|
||||
Box<Future<Item = ServiceResponse, Error = Error>>,
|
||||
> {
|
||||
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
||||
if let Some(ref mut default) = self.default {
|
||||
default.call(ServiceRequest::from_parts(req, payload))
|
||||
default.call(req)
|
||||
} 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 {
|
||||
let (req, pl) = req.into_parts();
|
||||
// let (req, pl) = req.into_parts();
|
||||
|
||||
let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) {
|
||||
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
|
||||
let path = match self.directory.join(&real_path.0).canonicalize() {
|
||||
Ok(path) => path,
|
||||
Err(e) => return self.handle_err(e, req, pl),
|
||||
Err(e) => return self.handle_err(e, req),
|
||||
};
|
||||
|
||||
if path.is_dir() {
|
||||
@@ -466,24 +465,26 @@ impl Service for FilesService {
|
||||
}
|
||||
|
||||
named_file.flags = self.file_flags;
|
||||
let (req, _) = req.into_parts();
|
||||
Either::A(ok(match named_file.respond_to(&req) {
|
||||
Ok(item) => ServiceResponse::new(req.clone(), item),
|
||||
Err(e) => ServiceResponse::from_err(e, req.clone()),
|
||||
Ok(item) => ServiceResponse::new(req, item),
|
||||
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 {
|
||||
let dir = Directory::new(self.directory.clone(), path);
|
||||
let (req, _) = req.into_parts();
|
||||
let x = (self.renderer)(&dir, &req);
|
||||
match x {
|
||||
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 {
|
||||
Either::A(ok(ServiceResponse::from_err(
|
||||
FilesError::IsDirectory,
|
||||
req.clone(),
|
||||
req.into_parts().0,
|
||||
)))
|
||||
}
|
||||
} else {
|
||||
@@ -496,16 +497,15 @@ impl Service for FilesService {
|
||||
}
|
||||
|
||||
named_file.flags = self.file_flags;
|
||||
let (req, _) = req.into_parts();
|
||||
match named_file.respond_to(&req) {
|
||||
Ok(item) => {
|
||||
Either::A(ok(ServiceResponse::new(req.clone(), item)))
|
||||
}
|
||||
Err(e) => {
|
||||
Either::A(ok(ServiceResponse::from_err(e, req.clone())))
|
||||
}
|
||||
Err(e) => Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||
}
|
||||
}
|
||||
Err(e) => self.handle_err(e, req, pl),
|
||||
Err(e) => self.handle_err(e, req),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -775,7 +775,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let request = TestRequest::get().uri("/").to_request();
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let content_disposition = response
|
||||
@@ -799,7 +799,7 @@ mod tests {
|
||||
.uri("/t%65st/Cargo.toml")
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.to_request();
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
|
||||
|
||||
// Invalid range header
|
||||
@@ -807,7 +807,7 @@ mod tests {
|
||||
.uri("/t%65st/Cargo.toml")
|
||||
.header(header::RANGE, "bytes=1-0")
|
||||
.to_request();
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
|
||||
assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
}
|
||||
@@ -824,7 +824,7 @@ mod tests {
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.to_request();
|
||||
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
let contentrange = response
|
||||
.headers()
|
||||
.get(header::CONTENT_RANGE)
|
||||
@@ -839,7 +839,7 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.header(header::RANGE, "bytes=10-5")
|
||||
.to_request();
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
|
||||
let contentrange = response
|
||||
.headers()
|
||||
@@ -862,7 +862,7 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.to_request();
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
@@ -878,7 +878,7 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.header(header::RANGE, "bytes=10-8")
|
||||
.to_request();
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
|
||||
// Without range header
|
||||
@@ -886,7 +886,7 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
// .no_default_headers()
|
||||
.to_request();
|
||||
let response = test::call_success(&mut srv, request);
|
||||
let response = test::call_service(&mut srv, request);
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
@@ -901,7 +901,7 @@ mod tests {
|
||||
let request = TestRequest::get()
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.to_request();
|
||||
let mut response = test::call_success(&mut srv, request);
|
||||
let mut response = test::call_service(&mut srv, request);
|
||||
|
||||
// with enabled compression
|
||||
// {
|
||||
@@ -932,7 +932,7 @@ mod tests {
|
||||
let request = TestRequest::get()
|
||||
.uri("/tests/test%20space.binary")
|
||||
.to_request();
|
||||
let mut response = test::call_success(&mut srv, request);
|
||||
let mut response = test::call_service(&mut srv, request);
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let bytes =
|
||||
@@ -975,7 +975,7 @@ mod tests {
|
||||
.uri("/")
|
||||
.header(header::ACCEPT_ENCODING, "gzip")
|
||||
.to_request();
|
||||
let res = test::call_success(&mut srv, request);
|
||||
let res = test::call_service(&mut srv, request);
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
assert!(!res.headers().contains_key(header::CONTENT_ENCODING));
|
||||
}
|
||||
@@ -994,7 +994,7 @@ mod tests {
|
||||
.uri("/")
|
||||
.header(header::ACCEPT_ENCODING, "gzip")
|
||||
.to_request();
|
||||
let res = test::call_success(&mut srv, request);
|
||||
let res = test::call_service(&mut srv, request);
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
res.headers()
|
||||
@@ -1021,20 +1021,20 @@ mod tests {
|
||||
);
|
||||
let req = TestRequest::with_uri("/missing").to_request();
|
||||
|
||||
let resp = test::call_success(&mut srv, req);
|
||||
let resp = test::call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let mut srv = test::init_service(App::new().service(Files::new("/", ".")));
|
||||
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = test::call_success(&mut srv, req);
|
||||
let resp = test::call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let mut srv = test::init_service(
|
||||
App::new().service(Files::new("/", ".").show_files_listing()),
|
||||
);
|
||||
let req = TestRequest::with_uri("/tests").to_request();
|
||||
let mut resp = test::call_success(&mut srv, req);
|
||||
let mut resp = test::call_service(&mut srv, req);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
"text/html; charset=utf-8"
|
||||
@@ -1067,7 +1067,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let req = TestRequest::with_uri("/missing").to_srv_request();
|
||||
|
||||
let mut resp = test::call_success(&mut st, req);
|
||||
let mut resp = test::call_service(&mut st, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let bytes =
|
||||
test::block_on(resp.take_body().fold(BytesMut::new(), |mut b, c| {
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-framed"
|
||||
version = "0.1.0-alpha.1"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix framed app server"
|
||||
readme = "README.md"
|
||||
@@ -25,13 +25,13 @@ actix-service = "0.3.6"
|
||||
actix-utils = "0.3.4"
|
||||
actix-router = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.1.0-alpha.5"
|
||||
actix-http = "0.1.0"
|
||||
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
|
||||
[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-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
|
@@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0] - 2019-04-16
|
||||
|
||||
* Update tests
|
||||
|
||||
|
||||
## [0.1.0-alpha.1] - 2019-04-12
|
||||
|
||||
* Initial release
|
||||
|
@@ -1,5 +1,5 @@
|
||||
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_service::{IntoNewService, NewService};
|
||||
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());
|
||||
|
||||
// client service
|
||||
|
@@ -1,5 +1,45 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.3] - 2019-04-23
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix http client pool management
|
||||
|
||||
* Fix http client wait queue management #794
|
||||
|
||||
|
||||
## [0.1.2] - 2019-04-23
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix BorrowMutError panic in client connector #793
|
||||
|
||||
|
||||
## [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
|
||||
|
||||
### Added
|
||||
|
||||
* Expose peer addr via `Request::peer_addr()` and `RequestHead::peer_addr`
|
||||
|
||||
### Changed
|
||||
|
||||
* `actix_http::encoding` always available
|
||||
|
||||
* use trust-dns-resolver 0.11.0
|
||||
|
||||
|
||||
## [0.1.0-alpha.5] - 2019-04-12
|
||||
|
||||
### Added
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "0.1.0-alpha.5"
|
||||
version = "0.1.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http primitives"
|
||||
readme = "README.md"
|
||||
@@ -46,9 +46,9 @@ secure-cookies = ["ring"]
|
||||
[dependencies]
|
||||
actix-service = "0.3.6"
|
||||
actix-codec = "0.1.2"
|
||||
actix-connect = "0.1.4"
|
||||
actix-connect = "0.1.5"
|
||||
actix-utils = "0.3.5"
|
||||
actix-server-config = "0.1.0"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
|
||||
base64 = "0.10"
|
||||
@@ -60,7 +60,7 @@ derive_more = "0.14"
|
||||
either = "1.5.2"
|
||||
encoding = "0.2"
|
||||
futures = "0.1"
|
||||
hashbrown = "0.2.0"
|
||||
hashbrown = "0.2.2"
|
||||
h2 = "0.1.16"
|
||||
http = "0.1.17"
|
||||
httparse = "1.3"
|
||||
@@ -76,12 +76,12 @@ serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
sha1 = "0.6"
|
||||
slab = "0.4"
|
||||
serde_urlencoded = "0.5.3"
|
||||
time = "0.1"
|
||||
serde_urlencoded = "0.5.5"
|
||||
time = "0.1.42"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-timer = "0.2"
|
||||
tokio-timer = "0.2.8"
|
||||
tokio-current-thread = "0.1"
|
||||
trust-dns-resolver = { version="0.11.0-alpha.3", default-features = false }
|
||||
trust-dns-resolver = { version="0.11.0", default-features = false }
|
||||
|
||||
# for secure cookie
|
||||
ring = { version = "0.14.6", optional = true }
|
||||
@@ -93,12 +93,13 @@ flate2 = { version="1.0.7", optional = true, default-features = false }
|
||||
# optional deps
|
||||
failure = { version = "0.1.5", optional = true }
|
||||
openssl = { version="0.10", optional = true }
|
||||
chrono = "0.4.6"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
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-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
openssl = { version="0.10" }
|
||||
|
@@ -14,6 +14,7 @@ use tokio_tcp::TcpStream;
|
||||
use super::connection::Connection;
|
||||
use super::error::ConnectError;
|
||||
use super::pool::{ConnectionPool, Protocol};
|
||||
use super::Connect;
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
use openssl::ssl::SslConnector;
|
||||
@@ -57,8 +58,7 @@ impl Connector<(), ()> {
|
||||
let ssl = {
|
||||
#[cfg(feature = "ssl")]
|
||||
{
|
||||
use log::error;
|
||||
use openssl::ssl::{SslConnector, SslMethod};
|
||||
use openssl::ssl::SslMethod;
|
||||
|
||||
let mut ssl = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
let _ = ssl
|
||||
@@ -114,7 +114,8 @@ where
|
||||
Request = TcpConnect<Uri>,
|
||||
Response = TcpConnection<Uri, U>,
|
||||
Error = actix_connect::ConnectError,
|
||||
> + Clone,
|
||||
> + Clone
|
||||
+ 'static,
|
||||
{
|
||||
/// Connection timeout, i.e. max time to connect to remote host including dns name resolution.
|
||||
/// Set to 1 second by default.
|
||||
@@ -178,15 +179,17 @@ where
|
||||
/// its combinator chain.
|
||||
pub fn finish(
|
||||
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"))]
|
||||
{
|
||||
let connector = TimeoutService::new(
|
||||
self.timeout,
|
||||
apply_fn(self.connector, |msg: Uri, srv| srv.call(msg.into()))
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||
apply_fn(self.connector, |msg: Connect, srv| {
|
||||
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||
})
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||
)
|
||||
.map_err(|e| match e {
|
||||
TimeoutError::Service(e) => e,
|
||||
@@ -210,26 +213,28 @@ where
|
||||
|
||||
let ssl_service = TimeoutService::new(
|
||||
self.timeout,
|
||||
apply_fn(self.connector.clone(), |msg: Uri, srv| srv.call(msg.into()))
|
||||
.map_err(ConnectError::from)
|
||||
.and_then(
|
||||
OpensslConnector::service(self.ssl)
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| {
|
||||
let sock = stream.into_parts().0;
|
||||
let h2 = sock
|
||||
.get_ref()
|
||||
.ssl()
|
||||
.selected_alpn_protocol()
|
||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||
.unwrap_or(false);
|
||||
if h2 {
|
||||
(sock, Protocol::Http2)
|
||||
} else {
|
||||
(sock, Protocol::Http1)
|
||||
}
|
||||
}),
|
||||
),
|
||||
apply_fn(self.connector.clone(), |msg: Connect, srv| {
|
||||
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||
})
|
||||
.map_err(ConnectError::from)
|
||||
.and_then(
|
||||
OpensslConnector::service(self.ssl)
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| {
|
||||
let sock = stream.into_parts().0;
|
||||
let h2 = sock
|
||||
.get_ref()
|
||||
.ssl()
|
||||
.selected_alpn_protocol()
|
||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||
.unwrap_or(false);
|
||||
if h2 {
|
||||
(sock, Protocol::Http2)
|
||||
} else {
|
||||
(sock, Protocol::Http1)
|
||||
}
|
||||
}),
|
||||
),
|
||||
)
|
||||
.map_err(|e| match e {
|
||||
TimeoutError::Service(e) => e,
|
||||
@@ -238,9 +243,11 @@ where
|
||||
|
||||
let tcp_service = TimeoutService::new(
|
||||
self.timeout,
|
||||
apply_fn(self.connector.clone(), |msg: Uri, srv| srv.call(msg.into()))
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||
apply_fn(self.connector.clone(), |msg: Connect, srv| {
|
||||
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||
})
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||
)
|
||||
.map_err(|e| match e {
|
||||
TimeoutError::Service(e) => e,
|
||||
@@ -265,15 +272,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"))]
|
||||
@@ -287,7 +285,9 @@ mod connect_impl {
|
||||
pub(crate) struct InnerConnector<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
||||
}
|
||||
@@ -295,8 +295,9 @@ mod connect_impl {
|
||||
impl<T, Io> Clone for InnerConnector<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
InnerConnector {
|
||||
@@ -308,9 +309,11 @@ mod connect_impl {
|
||||
impl<T, Io> Service for InnerConnector<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
type Request = Uri;
|
||||
type Request = Connect;
|
||||
type Response = IoConnection<Io>;
|
||||
type Error = ConnectError;
|
||||
type Future = Either<
|
||||
@@ -322,8 +325,8 @@ mod connect_impl {
|
||||
self.tcp_pool.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Uri) -> Self::Future {
|
||||
match req.scheme_str() {
|
||||
fn call(&mut self, req: Connect) -> Self::Future {
|
||||
match req.uri.scheme_str() {
|
||||
Some("https") | Some("wss") => {
|
||||
Either::B(err(ConnectError::SslIsNotSupported))
|
||||
}
|
||||
@@ -347,8 +350,8 @@ mod connect_impl {
|
||||
where
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
{
|
||||
pub(crate) tcp_pool: ConnectionPool<T1, Io1>,
|
||||
pub(crate) ssl_pool: ConnectionPool<T2, Io2>,
|
||||
@@ -358,10 +361,12 @@ mod connect_impl {
|
||||
where
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone,
|
||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone,
|
||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
InnerConnector {
|
||||
@@ -375,10 +380,14 @@ mod connect_impl {
|
||||
where
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
type Request = Uri;
|
||||
type Request = Connect;
|
||||
type Response = EitherConnection<Io1, Io2>;
|
||||
type Error = ConnectError;
|
||||
type Future = Either<
|
||||
@@ -393,8 +402,8 @@ mod connect_impl {
|
||||
self.tcp_pool.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Uri) -> Self::Future {
|
||||
match req.scheme_str() {
|
||||
fn call(&mut self, req: Connect) -> Self::Future {
|
||||
match req.uri.scheme_str() {
|
||||
Some("https") | Some("wss") => {
|
||||
Either::B(Either::B(InnerConnectorResponseB {
|
||||
fut: self.ssl_pool.call(req),
|
||||
@@ -412,7 +421,9 @@ mod connect_impl {
|
||||
pub(crate) struct InnerConnectorResponseA<T, Io1, Io2>
|
||||
where
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
||||
_t: PhantomData<Io2>,
|
||||
@@ -420,7 +431,9 @@ mod connect_impl {
|
||||
|
||||
impl<T, Io1, Io2> Future for InnerConnectorResponseA<T, Io1, Io2>
|
||||
where
|
||||
T: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
@@ -438,7 +451,9 @@ mod connect_impl {
|
||||
pub(crate) struct InnerConnectorResponseB<T, Io1, Io2>
|
||||
where
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
||||
_t: PhantomData<Io1>,
|
||||
@@ -446,7 +461,9 @@ mod connect_impl {
|
||||
|
||||
impl<T, Io1, Io2> Future for InnerConnectorResponseB<T, Io1, Io2>
|
||||
where
|
||||
T: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
Io1: AsyncRead + AsyncWrite + 'static,
|
||||
Io2: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
|
@@ -274,7 +274,7 @@ impl<Io: ConnectionLifetime> Stream for PlStream<Io> {
|
||||
Ok(Async::Ready(Some(chunk)))
|
||||
} else {
|
||||
let framed = self.framed.take().unwrap();
|
||||
let force_close = framed.get_codec().keepalive();
|
||||
let force_close = !framed.get_codec().keepalive();
|
||||
release_connection(framed, force_close);
|
||||
Ok(Async::Ready(None))
|
||||
}
|
||||
|
@@ -1,4 +1,6 @@
|
||||
//! Http client api
|
||||
use http::Uri;
|
||||
|
||||
mod connection;
|
||||
mod connector;
|
||||
mod error;
|
||||
@@ -10,3 +12,9 @@ pub use self::connection::Connection;
|
||||
pub use self::connector::Connector;
|
||||
pub use self::error::{ConnectError, InvalidUrl, SendRequestError};
|
||||
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 h2::client::{handshake, Handshake};
|
||||
use hashbrown::HashMap;
|
||||
use http::uri::{Authority, Uri};
|
||||
use http::uri::Authority;
|
||||
use indexmap::IndexSet;
|
||||
use slab::Slab;
|
||||
use tokio_timer::{sleep, Delay};
|
||||
|
||||
use super::connection::{ConnectionType, IoConnection};
|
||||
use super::error::ConnectError;
|
||||
use super::Connect;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
/// Protocol version
|
||||
@@ -48,7 +49,9 @@ pub(crate) struct ConnectionPool<T, Io: AsyncRead + AsyncWrite + 'static>(
|
||||
impl<T, Io> ConnectionPool<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
pub(crate) fn new(
|
||||
connector: T,
|
||||
@@ -68,7 +71,7 @@ where
|
||||
waiters: Slab::new(),
|
||||
waiters_queue: IndexSet::new(),
|
||||
available: HashMap::new(),
|
||||
task: AtomicTask::new(),
|
||||
task: None,
|
||||
})),
|
||||
)
|
||||
}
|
||||
@@ -87,9 +90,11 @@ where
|
||||
impl<T, Io> Service for ConnectionPool<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||
+ Clone
|
||||
+ 'static,
|
||||
{
|
||||
type Request = Uri;
|
||||
type Request = Connect;
|
||||
type Response = IoConnection<Io>;
|
||||
type Error = ConnectError;
|
||||
type Future = Either<
|
||||
@@ -101,8 +106,8 @@ where
|
||||
self.0.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Uri) -> Self::Future {
|
||||
let key = if let Some(authority) = req.authority_part() {
|
||||
fn call(&mut self, req: Connect) -> Self::Future {
|
||||
let key = if let Some(authority) = req.uri.authority_part() {
|
||||
authority.clone().into()
|
||||
} else {
|
||||
return Either::A(err(ConnectError::Unresolverd));
|
||||
@@ -112,31 +117,41 @@ where
|
||||
match self.1.as_ref().borrow_mut().acquire(&key) {
|
||||
Acquire::Acquired(io, created) => {
|
||||
// use existing connection
|
||||
Either::A(ok(IoConnection::new(
|
||||
return Either::A(ok(IoConnection::new(
|
||||
io,
|
||||
created,
|
||||
Some(Acquired(key, Some(self.1.clone()))),
|
||||
)))
|
||||
}
|
||||
Acquire::NotAvailable => {
|
||||
// connection is not available, wait
|
||||
let (rx, token) = self.1.as_ref().borrow_mut().wait_for(req);
|
||||
Either::B(Either::A(WaitForConnection {
|
||||
rx,
|
||||
key,
|
||||
token,
|
||||
inner: Some(self.1.clone()),
|
||||
}))
|
||||
)));
|
||||
}
|
||||
Acquire::Available => {
|
||||
// open new connection
|
||||
Either::B(Either::B(OpenConnection::new(
|
||||
return Either::B(Either::B(OpenConnection::new(
|
||||
key,
|
||||
self.1.clone(),
|
||||
self.0.call(req),
|
||||
)))
|
||||
)));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
// connection is not available, wait
|
||||
let (rx, token, support) = self.1.as_ref().borrow_mut().wait_for(req);
|
||||
|
||||
// start support future
|
||||
if !support {
|
||||
self.1.as_ref().borrow_mut().task = Some(AtomicTask::new());
|
||||
tokio_current_thread::spawn(ConnectorPoolSupport {
|
||||
connector: self.0.clone(),
|
||||
inner: self.1.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
Either::B(Either::A(WaitForConnection {
|
||||
rx,
|
||||
key,
|
||||
token,
|
||||
inner: Some(self.1.clone()),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,7 +259,7 @@ where
|
||||
Ok(Async::Ready(IoConnection::new(
|
||||
ConnectionType::H2(snd),
|
||||
Instant::now(),
|
||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
||||
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||
)))
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
@@ -255,12 +270,11 @@ where
|
||||
match self.fut.poll() {
|
||||
Err(err) => Err(err),
|
||||
Ok(Async::Ready((io, proto))) => {
|
||||
let _ = self.inner.take();
|
||||
if proto == Protocol::Http1 {
|
||||
Ok(Async::Ready(IoConnection::new(
|
||||
ConnectionType::H1(io),
|
||||
Instant::now(),
|
||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
||||
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||
)))
|
||||
} else {
|
||||
self.h2 = Some(handshake(io));
|
||||
@@ -278,7 +292,6 @@ enum Acquire<T> {
|
||||
NotAvailable,
|
||||
}
|
||||
|
||||
// #[derive(Debug)]
|
||||
struct AvailableConnection<Io> {
|
||||
io: ConnectionType<Io>,
|
||||
used: Instant,
|
||||
@@ -292,9 +305,12 @@ pub(crate) struct Inner<Io> {
|
||||
limit: usize,
|
||||
acquired: usize,
|
||||
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)>,
|
||||
task: AtomicTask,
|
||||
task: Option<AtomicTask>,
|
||||
}
|
||||
|
||||
impl<Io> Inner<Io> {
|
||||
@@ -310,18 +326,6 @@ impl<Io> Inner<Io> {
|
||||
self.waiters.remove(token);
|
||||
self.waiters_queue.remove(&(key.clone(), token));
|
||||
}
|
||||
|
||||
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
||||
self.acquired -= 1;
|
||||
self.available
|
||||
.entry(key.clone())
|
||||
.or_insert_with(VecDeque::new)
|
||||
.push_back(AvailableConnection {
|
||||
io,
|
||||
created,
|
||||
used: Instant::now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<Io> Inner<Io>
|
||||
@@ -331,19 +335,21 @@ where
|
||||
/// connection is not available, wait
|
||||
fn wait_for(
|
||||
&mut self,
|
||||
connect: Uri,
|
||||
connect: Connect,
|
||||
) -> (
|
||||
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
||||
usize,
|
||||
bool,
|
||||
) {
|
||||
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 token = entry.key();
|
||||
entry.insert((connect, tx));
|
||||
assert!(!self.waiters_queue.insert((key, token)));
|
||||
(rx, token)
|
||||
assert!(self.waiters_queue.insert((key, token)));
|
||||
|
||||
(rx, token, self.task.is_some())
|
||||
}
|
||||
|
||||
fn acquire(&mut self, key: &Key) -> Acquire<Io> {
|
||||
@@ -396,6 +402,19 @@ where
|
||||
Acquire::Available
|
||||
}
|
||||
|
||||
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
||||
self.acquired -= 1;
|
||||
self.available
|
||||
.entry(key.clone())
|
||||
.or_insert_with(VecDeque::new)
|
||||
.push_back(AvailableConnection {
|
||||
io,
|
||||
created,
|
||||
used: Instant::now(),
|
||||
});
|
||||
self.check_availibility();
|
||||
}
|
||||
|
||||
fn release_close(&mut self, io: ConnectionType<Io>) {
|
||||
self.acquired -= 1;
|
||||
if let Some(timeout) = self.disconnect_timeout {
|
||||
@@ -403,11 +422,12 @@ where
|
||||
tokio_current_thread::spawn(CloseConnection::new(io, timeout))
|
||||
}
|
||||
}
|
||||
self.check_availibility();
|
||||
}
|
||||
|
||||
fn check_availibility(&self) {
|
||||
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
||||
self.task.notify()
|
||||
self.task.as_ref().map(|t| t.notify());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -447,6 +467,147 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
struct ConnectorPoolSupport<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
connector: T,
|
||||
inner: Rc<RefCell<Inner<Io>>>,
|
||||
}
|
||||
|
||||
impl<T, Io> Future for ConnectorPoolSupport<T, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let mut inner = self.inner.as_ref().borrow_mut();
|
||||
inner.task.as_ref().unwrap().register();
|
||||
|
||||
// check waiters
|
||||
loop {
|
||||
let (key, token) = {
|
||||
if let Some((key, token)) = inner.waiters_queue.get_index(0) {
|
||||
(key.clone(), *token)
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
};
|
||||
match inner.acquire(&key) {
|
||||
Acquire::NotAvailable => break,
|
||||
Acquire::Acquired(io, created) => {
|
||||
let (_, tx) = inner.waiters.remove(token);
|
||||
if let Err(conn) = tx.send(Ok(IoConnection::new(
|
||||
io,
|
||||
created,
|
||||
Some(Acquired(key.clone(), Some(self.inner.clone()))),
|
||||
))) {
|
||||
let (io, created) = conn.unwrap().into_inner();
|
||||
inner.release_conn(&key, io, created);
|
||||
}
|
||||
}
|
||||
Acquire::Available => {
|
||||
let (connect, tx) = inner.waiters.remove(token);
|
||||
OpenWaitingConnection::spawn(
|
||||
key.clone(),
|
||||
tx,
|
||||
self.inner.clone(),
|
||||
self.connector.call(connect),
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = inner.waiters_queue.swap_remove_index(0);
|
||||
}
|
||||
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
struct OpenWaitingConnection<F, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
fut: F,
|
||||
key: Key,
|
||||
h2: Option<Handshake<Io, Bytes>>,
|
||||
rx: Option<oneshot::Sender<Result<IoConnection<Io>, ConnectError>>>,
|
||||
inner: Option<Rc<RefCell<Inner<Io>>>>,
|
||||
}
|
||||
|
||||
impl<F, Io> OpenWaitingConnection<F, Io>
|
||||
where
|
||||
F: Future<Item = (Io, Protocol), Error = ConnectError> + 'static,
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
fn spawn(
|
||||
key: Key,
|
||||
rx: oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||
inner: Rc<RefCell<Inner<Io>>>,
|
||||
fut: F,
|
||||
) {
|
||||
tokio_current_thread::spawn(OpenWaitingConnection {
|
||||
key,
|
||||
fut,
|
||||
h2: None,
|
||||
rx: Some(rx),
|
||||
inner: Some(inner),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Io> Drop for OpenWaitingConnection<F, Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if let Some(inner) = self.inner.take() {
|
||||
let mut inner = inner.as_ref().borrow_mut();
|
||||
inner.release();
|
||||
inner.check_availibility();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Io> Future for OpenWaitingConnection<F, Io>
|
||||
where
|
||||
F: Future<Item = (Io, Protocol), Error = ConnectError>,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll() {
|
||||
Err(err) => {
|
||||
let _ = self.inner.take();
|
||||
if let Some(rx) = self.rx.take() {
|
||||
let _ = rx.send(Err(err));
|
||||
}
|
||||
Err(())
|
||||
}
|
||||
Ok(Async::Ready((io, proto))) => {
|
||||
if proto == Protocol::Http1 {
|
||||
let rx = self.rx.take().unwrap();
|
||||
let _ = rx.send(Ok(IoConnection::new(
|
||||
ConnectionType::H1(io),
|
||||
Instant::now(),
|
||||
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||
)));
|
||||
Ok(Async::Ready(()))
|
||||
} else {
|
||||
self.h2 = Some(handshake(io));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Acquired<T>(Key, Option<Rc<RefCell<Inner<T>>>>);
|
||||
|
||||
impl<T> Acquired<T>
|
||||
|
@@ -1,6 +1,7 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use time::{Duration, Tm};
|
||||
use chrono::Duration;
|
||||
use time::Tm;
|
||||
|
||||
use super::{Cookie, SameSite};
|
||||
|
||||
@@ -16,7 +17,6 @@ use super::{Cookie, SameSite};
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_http::cookie::Cookie;
|
||||
/// use time::Duration;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let cookie: Cookie = Cookie::build("name", "value")
|
||||
@@ -24,7 +24,7 @@ use super::{Cookie, SameSite};
|
||||
/// .path("/")
|
||||
/// .secure(true)
|
||||
/// .http_only(true)
|
||||
/// .max_age(Duration::days(1))
|
||||
/// .max_age(84600)
|
||||
/// .finish();
|
||||
/// # }
|
||||
/// ```
|
||||
@@ -79,6 +79,26 @@ impl CookieBuilder {
|
||||
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.
|
||||
///
|
||||
/// # Example
|
||||
@@ -88,14 +108,14 @@ impl CookieBuilder {
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let c = Cookie::build("foo", "bar")
|
||||
/// .max_age(time::Duration::minutes(30))
|
||||
/// .max_age_time(time::Duration::minutes(30))
|
||||
/// .finish();
|
||||
///
|
||||
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
|
||||
/// # }
|
||||
/// ```
|
||||
#[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
|
||||
}
|
||||
@@ -200,7 +220,7 @@ impl CookieBuilder {
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_http::cookie::Cookie;
|
||||
/// use time::Duration;
|
||||
/// use chrono::Duration;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let c = Cookie::build("foo", "bar")
|
||||
|
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashSet;
|
||||
use std::mem::replace;
|
||||
|
||||
use time::{self, Duration};
|
||||
use chrono::Duration;
|
||||
|
||||
use super::delta::DeltaCookie;
|
||||
use super::Cookie;
|
||||
@@ -188,7 +188,7 @@ impl CookieJar {
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_http::cookie::{CookieJar, Cookie};
|
||||
/// use time::Duration;
|
||||
/// use chrono::Duration;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let mut jar = CookieJar::new();
|
||||
@@ -241,7 +241,7 @@ impl CookieJar {
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_http::cookie::{CookieJar, Cookie};
|
||||
/// use time::Duration;
|
||||
/// use chrono::Duration;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let mut jar = CookieJar::new();
|
||||
@@ -537,8 +537,8 @@ mod test {
|
||||
#[test]
|
||||
#[cfg(feature = "secure-cookies")]
|
||||
fn delta() {
|
||||
use chrono::Duration;
|
||||
use std::collections::HashMap;
|
||||
use time::Duration;
|
||||
|
||||
let mut c = CookieJar::new();
|
||||
|
||||
|
@@ -65,8 +65,9 @@ use std::borrow::Cow;
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
use chrono::Duration;
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
use time::{Duration, Tm};
|
||||
use time::Tm;
|
||||
|
||||
pub use self::builder::CookieBuilder;
|
||||
pub use self::draft::*;
|
||||
@@ -624,7 +625,7 @@ impl<'c> Cookie<'c> {
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_http::cookie::Cookie;
|
||||
/// use time::Duration;
|
||||
/// use chrono::Duration;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let mut c = Cookie::new("name", "value");
|
||||
@@ -703,7 +704,7 @@ impl<'c> Cookie<'c> {
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_http::cookie::Cookie;
|
||||
/// use time::Duration;
|
||||
/// use chrono::Duration;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let mut c = Cookie::new("foo", "bar");
|
||||
@@ -977,7 +978,7 @@ impl<'a, 'b> PartialEq<Cookie<'b>> for Cookie<'a> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Cookie, SameSite};
|
||||
use time::{strptime, Duration};
|
||||
use time::strptime;
|
||||
|
||||
#[test]
|
||||
fn format() {
|
||||
@@ -987,9 +988,7 @@ mod tests {
|
||||
let cookie = Cookie::build("foo", "bar").http_only(true).finish();
|
||||
assert_eq!(&cookie.to_string(), "foo=bar; HttpOnly");
|
||||
|
||||
let cookie = Cookie::build("foo", "bar")
|
||||
.max_age(Duration::seconds(10))
|
||||
.finish();
|
||||
let cookie = Cookie::build("foo", "bar").max_age(10).finish();
|
||||
assert_eq!(&cookie.to_string(), "foo=bar; Max-Age=10");
|
||||
|
||||
let cookie = Cookie::build("foo", "bar").secure(true).finish();
|
||||
|
@@ -5,8 +5,8 @@ use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::str::Utf8Error;
|
||||
|
||||
use chrono::Duration;
|
||||
use percent_encoding::percent_decode;
|
||||
use time::{self, Duration};
|
||||
|
||||
use super::{Cookie, CookieStr, SameSite};
|
||||
|
||||
@@ -220,7 +220,8 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Cookie, SameSite};
|
||||
use time::{strptime, Duration};
|
||||
use chrono::Duration;
|
||||
use time::strptime;
|
||||
|
||||
macro_rules! assert_eq_parse {
|
||||
($string:expr, $expected:expr) => {
|
||||
@@ -418,9 +419,7 @@ mod tests {
|
||||
#[test]
|
||||
fn do_not_panic_on_large_max_ages() {
|
||||
let max_seconds = Duration::max_value().num_seconds();
|
||||
let expected = Cookie::build("foo", "bar")
|
||||
.max_age(Duration::seconds(max_seconds))
|
||||
.finish();
|
||||
let expected = Cookie::build("foo", "bar").max_age(max_seconds).finish();
|
||||
assert_eq_parse!(format!(" foo=bar; Max-Age={:?}", max_seconds + 1), expected);
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,6 @@
|
||||
#![allow(unused_imports, unused_variables, dead_code)]
|
||||
use std::fmt;
|
||||
use std::io::{self, Write};
|
||||
use std::io::Write;
|
||||
use std::{fmt, io, net};
|
||||
|
||||
use actix_codec::{Decoder, Encoder};
|
||||
use bitflags::bitflags;
|
||||
@@ -40,7 +40,6 @@ pub struct Codec {
|
||||
// encoder part
|
||||
flags: Flags,
|
||||
encoder: encoder::MessageEncoder<Response<()>>,
|
||||
// headers_size: u32,
|
||||
}
|
||||
|
||||
impl Default for Codec {
|
||||
@@ -67,13 +66,11 @@ impl Codec {
|
||||
};
|
||||
Codec {
|
||||
config,
|
||||
flags,
|
||||
decoder: decoder::MessageDecoder::default(),
|
||||
payload: None,
|
||||
version: Version::HTTP_11,
|
||||
ctype: ConnectionType::Close,
|
||||
|
||||
flags,
|
||||
// headers_size: 0,
|
||||
encoder: encoder::MessageEncoder::default(),
|
||||
}
|
||||
}
|
||||
|
@@ -1,8 +1,9 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Instant;
|
||||
use std::{fmt, io};
|
||||
use std::{fmt, io, net};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed, FramedParts};
|
||||
use actix_codec::{Decoder, Encoder, Framed, FramedParts};
|
||||
use actix_server_config::IoStream;
|
||||
use actix_service::Service;
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bitflags::bitflags;
|
||||
@@ -81,6 +82,7 @@ where
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
flags: Flags,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
error: Option<DispatchError>,
|
||||
|
||||
state: State<S, B, X>,
|
||||
@@ -161,7 +163,7 @@ impl PartialEq for PollResponse {
|
||||
|
||||
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
@@ -220,14 +222,15 @@ where
|
||||
|
||||
Dispatcher {
|
||||
inner: DispatcherState::Normal(InnerDispatcher {
|
||||
io,
|
||||
codec,
|
||||
read_buf,
|
||||
write_buf: BytesMut::with_capacity(HW_BUFFER_SIZE),
|
||||
payload: None,
|
||||
state: State::None,
|
||||
error: None,
|
||||
peer_addr: io.peer_addr(),
|
||||
messages: VecDeque::new(),
|
||||
io,
|
||||
codec,
|
||||
read_buf,
|
||||
service,
|
||||
expect,
|
||||
upgrade,
|
||||
@@ -241,7 +244,7 @@ where
|
||||
|
||||
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
@@ -490,6 +493,7 @@ where
|
||||
match msg {
|
||||
Message::Item(mut req) => {
|
||||
let pl = self.codec.message_type();
|
||||
req.head_mut().peer_addr = self.peer_addr;
|
||||
|
||||
if pl == MessageType::Stream && self.upgrade.is_some() {
|
||||
self.messages.push_back(DispatcherMessage::Upgrade(req));
|
||||
@@ -649,7 +653,7 @@ where
|
||||
|
||||
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
@@ -1,8 +1,8 @@
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_server_config::{Io, ServerConfig as SrvConfig};
|
||||
use actix_codec::Framed;
|
||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use futures::future::{ok, FutureResult};
|
||||
@@ -104,7 +104,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
@@ -161,7 +161,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
@@ -245,7 +245,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> Service for H1ServiceHandler<T, P, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
@@ -309,7 +309,7 @@ pub struct OneRequest<T, P> {
|
||||
|
||||
impl<T, P> OneRequest<T, P>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
{
|
||||
/// Create new `H1SimpleService` instance.
|
||||
pub fn new() -> Self {
|
||||
@@ -322,7 +322,7 @@ where
|
||||
|
||||
impl<T, P> NewService<SrvConfig> for OneRequest<T, P>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
{
|
||||
type Request = Io<T, P>;
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
@@ -348,7 +348,7 @@ pub struct OneRequestService<T, P> {
|
||||
|
||||
impl<T, P> Service for OneRequestService<T, P>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
{
|
||||
type Request = Io<T, P>;
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
@@ -372,14 +372,14 @@ where
|
||||
#[doc(hidden)]
|
||||
pub struct OneRequestServiceResponse<T>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
{
|
||||
framed: Option<Framed<T, Codec>>,
|
||||
}
|
||||
|
||||
impl<T> Future for OneRequestServiceResponse<T>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
{
|
||||
type Item = (Request, Framed<T, Codec>);
|
||||
type Error = ParseError;
|
||||
|
@@ -1,9 +1,10 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
use std::time::Instant;
|
||||
use std::{fmt, mem};
|
||||
use std::{fmt, mem, net};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_server_config::IoStream;
|
||||
use actix_service::Service;
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bitflags::bitflags;
|
||||
@@ -29,14 +30,11 @@ use crate::response::Response;
|
||||
const CHUNK_SIZE: usize = 16_384;
|
||||
|
||||
/// Dispatcher for HTTP/2 protocol
|
||||
pub struct Dispatcher<
|
||||
T: AsyncRead + AsyncWrite,
|
||||
S: Service<Request = Request>,
|
||||
B: MessageBody,
|
||||
> {
|
||||
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> {
|
||||
service: CloneableService<S>,
|
||||
connection: Connection<T, Bytes>,
|
||||
config: ServiceConfig,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
ka_expire: Instant,
|
||||
ka_timer: Option<Delay>,
|
||||
_t: PhantomData<B>,
|
||||
@@ -44,7 +42,7 @@ pub struct Dispatcher<
|
||||
|
||||
impl<T, S, B> Dispatcher<T, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -56,6 +54,7 @@ where
|
||||
connection: Connection<T, Bytes>,
|
||||
config: ServiceConfig,
|
||||
timeout: Option<Delay>,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
) -> Self {
|
||||
// let keepalive = config.keep_alive_enabled();
|
||||
// let flags = if keepalive {
|
||||
@@ -76,9 +75,10 @@ where
|
||||
Dispatcher {
|
||||
service,
|
||||
config,
|
||||
peer_addr,
|
||||
connection,
|
||||
ka_expire,
|
||||
ka_timer,
|
||||
connection,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@ where
|
||||
|
||||
impl<T, S, B> Future for Dispatcher<T, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -117,6 +117,7 @@ where
|
||||
head.method = parts.method;
|
||||
head.version = parts.version;
|
||||
head.headers = parts.headers.into();
|
||||
head.peer_addr = self.peer_addr;
|
||||
tokio_current_thread::spawn(ServiceResponse::<S::Future, B> {
|
||||
state: ServiceResponseState::ServiceCall(
|
||||
self.service.call(req),
|
||||
|
@@ -3,7 +3,7 @@ use std::marker::PhantomData;
|
||||
use std::{io, net};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_server_config::{Io, ServerConfig as SrvConfig};
|
||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bytes::Bytes;
|
||||
@@ -63,7 +63,7 @@ where
|
||||
|
||||
impl<T, P, S, B> NewService<SrvConfig> for H2Service<T, P, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
@@ -95,7 +95,7 @@ pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>,
|
||||
|
||||
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
@@ -140,7 +140,7 @@ where
|
||||
|
||||
impl<T, P, S, B> Service for H2ServiceHandler<T, P, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -161,17 +161,20 @@ where
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
let io = req.into_parts().0;
|
||||
let peer_addr = io.peer_addr();
|
||||
H2ServiceHandlerResponse {
|
||||
state: State::Handshake(
|
||||
Some(self.srv.clone()),
|
||||
Some(self.cfg.clone()),
|
||||
server::handshake(req.into_parts().0),
|
||||
peer_addr,
|
||||
server::handshake(io),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum State<T: AsyncRead + AsyncWrite, S: Service<Request = Request>, B: MessageBody>
|
||||
enum State<T: IoStream, S: Service<Request = Request>, B: MessageBody>
|
||||
where
|
||||
S::Future: 'static,
|
||||
{
|
||||
@@ -179,13 +182,14 @@ where
|
||||
Handshake(
|
||||
Option<CloneableService<S>>,
|
||||
Option<ServiceConfig>,
|
||||
Option<net::SocketAddr>,
|
||||
Handshake<T, Bytes>,
|
||||
),
|
||||
}
|
||||
|
||||
pub struct H2ServiceHandlerResponse<T, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -197,7 +201,7 @@ where
|
||||
|
||||
impl<T, S, B> Future for H2ServiceHandlerResponse<T, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -210,24 +214,28 @@ where
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.state {
|
||||
State::Incoming(ref mut disp) => disp.poll(),
|
||||
State::Handshake(ref mut srv, ref mut config, ref mut handshake) => {
|
||||
match handshake.poll() {
|
||||
Ok(Async::Ready(conn)) => {
|
||||
self.state = State::Incoming(Dispatcher::new(
|
||||
srv.take().unwrap(),
|
||||
conn,
|
||||
config.take().unwrap(),
|
||||
None,
|
||||
));
|
||||
self.poll()
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(err) => {
|
||||
trace!("H2 handshake error: {}", err);
|
||||
Err(err.into())
|
||||
}
|
||||
State::Handshake(
|
||||
ref mut srv,
|
||||
ref mut config,
|
||||
ref peer_addr,
|
||||
ref mut handshake,
|
||||
) => match handshake.poll() {
|
||||
Ok(Async::Ready(conn)) => {
|
||||
self.state = State::Incoming(Dispatcher::new(
|
||||
srv.take().unwrap(),
|
||||
conn,
|
||||
config.take().unwrap(),
|
||||
None,
|
||||
peer_addr.clone(),
|
||||
));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(err) => {
|
||||
trace!("H2 handshake error: {}", err);
|
||||
Err(err.into())
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -60,6 +60,7 @@ impl Response {
|
||||
STATIC_RESP!(UnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||
STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
|
||||
STATIC_RESP!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
|
||||
STATIC_RESP!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
STATIC_RESP!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
|
||||
|
@@ -12,7 +12,6 @@ pub mod body;
|
||||
mod builder;
|
||||
pub mod client;
|
||||
mod config;
|
||||
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust", feature = "brotli"))]
|
||||
pub mod encoding;
|
||||
mod extensions;
|
||||
mod header;
|
||||
|
@@ -1,4 +1,5 @@
|
||||
use std::cell::{Ref, RefCell, RefMut};
|
||||
use std::net;
|
||||
use std::rc::Rc;
|
||||
|
||||
use bitflags::bitflags;
|
||||
@@ -43,6 +44,7 @@ pub struct RequestHead {
|
||||
pub version: Version,
|
||||
pub headers: HeaderMap,
|
||||
pub extensions: RefCell<Extensions>,
|
||||
pub peer_addr: Option<net::SocketAddr>,
|
||||
flags: Flags,
|
||||
}
|
||||
|
||||
@@ -54,6 +56,7 @@ impl Default for RequestHead {
|
||||
version: Version::HTTP_11,
|
||||
headers: HeaderMap::with_capacity(16),
|
||||
flags: Flags::empty(),
|
||||
peer_addr: None,
|
||||
extensions: RefCell::new(Extensions::new()),
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,5 @@
|
||||
use std::cell::{Ref, RefMut};
|
||||
use std::fmt;
|
||||
use std::{fmt, net};
|
||||
|
||||
use http::{header, Method, Uri, Version};
|
||||
|
||||
@@ -139,6 +139,7 @@ impl<P> Request<P> {
|
||||
}
|
||||
|
||||
/// Check if request requires connection upgrade
|
||||
#[inline]
|
||||
pub fn upgrade(&self) -> bool {
|
||||
if let Some(conn) = self.head().headers.get(header::CONNECTION) {
|
||||
if let Ok(s) = conn.to_str() {
|
||||
@@ -147,6 +148,15 @@ impl<P> Request<P> {
|
||||
}
|
||||
self.head().method == Method::CONNECT
|
||||
}
|
||||
|
||||
/// Peer socket address
|
||||
///
|
||||
/// Peer address is actual socket address, if proxy is used in front of
|
||||
/// actix http server, then peer address would be address of this proxy.
|
||||
#[inline]
|
||||
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.head().peer_addr
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> fmt::Debug for Request<P> {
|
||||
@@ -168,3 +178,28 @@ impl<P> fmt::Debug for Request<P> {
|
||||
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")
|
||||
.path("/test")
|
||||
.http_only(true)
|
||||
.max_age(time::Duration::days(1))
|
||||
.max_age_time(time::Duration::days(1))
|
||||
.finish(),
|
||||
)
|
||||
.del_cookie(&cookies[1])
|
||||
|
@@ -1,8 +1,10 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::{fmt, io};
|
||||
use std::{fmt, io, net};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_server_config::{Io as ServerIo, Protocol, ServerConfig as SrvConfig};
|
||||
use actix_server_config::{
|
||||
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
|
||||
};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||
@@ -128,7 +130,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for HttpService<T, P, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
@@ -182,7 +184,7 @@ pub struct HttpServiceResponse<
|
||||
|
||||
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
@@ -268,7 +270,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> Service for HttpServiceHandler<T, P, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -317,6 +319,7 @@ where
|
||||
let (io, _, proto) = req.into_parts();
|
||||
match proto {
|
||||
Protocol::Http2 => {
|
||||
let peer_addr = io.peer_addr();
|
||||
let io = Io {
|
||||
inner: io,
|
||||
unread: None,
|
||||
@@ -326,6 +329,7 @@ where
|
||||
server::handshake(io),
|
||||
self.cfg.clone(),
|
||||
self.srv.clone(),
|
||||
peer_addr,
|
||||
))),
|
||||
}
|
||||
}
|
||||
@@ -357,7 +361,7 @@ where
|
||||
S: Service<Request = Request>,
|
||||
S::Future: 'static,
|
||||
S::Error: Into<Error>,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
B: MessageBody,
|
||||
X: Service<Request = Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
@@ -376,12 +380,19 @@ where
|
||||
Option<CloneableService<U>>,
|
||||
)>,
|
||||
),
|
||||
Handshake(Option<(Handshake<Io<T>, Bytes>, ServiceConfig, CloneableService<S>)>),
|
||||
Handshake(
|
||||
Option<(
|
||||
Handshake<Io<T>, Bytes>,
|
||||
ServiceConfig,
|
||||
CloneableService<S>,
|
||||
Option<net::SocketAddr>,
|
||||
)>,
|
||||
),
|
||||
}
|
||||
|
||||
pub struct HttpServiceHandlerResponse<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -399,7 +410,7 @@ const HTTP2_PREFACE: [u8; 14] = *b"PRI * HTTP/2.0";
|
||||
|
||||
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
T: IoStream,
|
||||
S: Service<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
@@ -437,12 +448,17 @@ where
|
||||
}
|
||||
let (io, buf, cfg, srv, expect, upgrade) = data.take().unwrap();
|
||||
if buf[..14] == HTTP2_PREFACE[..] {
|
||||
let peer_addr = io.peer_addr();
|
||||
let io = Io {
|
||||
inner: io,
|
||||
unread: Some(buf),
|
||||
};
|
||||
self.state =
|
||||
State::Handshake(Some((server::handshake(io), cfg, srv)));
|
||||
self.state = State::Handshake(Some((
|
||||
server::handshake(io),
|
||||
cfg,
|
||||
srv,
|
||||
peer_addr,
|
||||
)));
|
||||
} else {
|
||||
self.state = State::H1(h1::Dispatcher::with_timeout(
|
||||
io,
|
||||
@@ -470,8 +486,8 @@ where
|
||||
} else {
|
||||
panic!()
|
||||
};
|
||||
let (_, cfg, srv) = data.take().unwrap();
|
||||
self.state = State::H2(Dispatcher::new(srv, conn, cfg, None));
|
||||
let (_, cfg, srv, peer_addr) = data.take().unwrap();
|
||||
self.state = State::H2(Dispatcher::new(srv, conn, cfg, None, peer_addr));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
@@ -523,3 +539,25 @@ impl<T: AsyncWrite> AsyncWrite for Io<T> {
|
||||
self.inner.write_buf(buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IoStream> IoStream for Io<T> {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.inner.peer_addr()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
||||
self.inner.set_nodelay(nodelay)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, dur: Option<std::time::Duration>) -> io::Result<()> {
|
||||
self.inner.set_linger(dur)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, dur: Option<std::time::Duration>) -> io::Result<()> {
|
||||
self.inner.set_keepalive(dur)
|
||||
}
|
||||
}
|
||||
|
@@ -4,6 +4,7 @@ use std::io;
|
||||
use std::str::FromStr;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_server_config::IoStream;
|
||||
use bytes::{Buf, Bytes, BytesMut};
|
||||
use futures::{Async, Poll};
|
||||
use http::header::{self, HeaderName, HeaderValue};
|
||||
@@ -253,3 +254,17 @@ impl AsyncWrite for TestBuffer {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
impl IoStream for TestBuffer {
|
||||
fn set_nodelay(&mut self, _nodelay: bool) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_linger(&mut self, _dur: Option<std::time::Duration>) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_keepalive(&mut self, _dur: Option<std::time::Duration>) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
@@ -35,7 +35,10 @@ fn test_h1() {
|
||||
.keep_alive(KeepAlive::Disabled)
|
||||
.client_timeout(1000)
|
||||
.client_disconnect(1000)
|
||||
.h1(|_| future::ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
future::ok::<_, ()>(Response::Ok().finish())
|
||||
})
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.get("/").send()).unwrap();
|
||||
@@ -50,6 +53,7 @@ fn test_h1_2() {
|
||||
.client_timeout(1000)
|
||||
.client_disconnect(1000)
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), http::Version::HTTP_11);
|
||||
future::ok::<_, ()>(Response::Ok().finish())
|
||||
})
|
||||
@@ -115,6 +119,7 @@ fn test_h2_1() -> std::io::Result<()> {
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), http::Version::HTTP_2);
|
||||
future::ok::<_, Error>(Response::Ok().finish())
|
||||
})
|
||||
|
@@ -1,7 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0-alpha.1] - 2019-04-xx
|
||||
## [0.1.0-beta.1] - 2019-04-21
|
||||
|
||||
* Do not support nested multipart
|
||||
|
||||
* Split multipart support to separate crate
|
||||
|
||||
* Optimize multipart handling #634, #769
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-multipart"
|
||||
version = "0.1.0-alpha.1"
|
||||
version = "0.1.0-beta.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Multipart support for actix web framework."
|
||||
readme = "README.md"
|
||||
@@ -18,8 +18,8 @@ name = "actix_multipart"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-alpha.3"
|
||||
actix-service = "0.3.4"
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-service = "0.3.6"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
httparse = "1.3"
|
||||
@@ -31,4 +31,4 @@ twoway = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.1.0-alpha.3"
|
||||
actix-http = "0.1.1"
|
@@ -168,7 +168,7 @@ impl InnerMultipart {
|
||||
match payload.readline() {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
Ok(Some(true))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
@@ -201,8 +201,7 @@ impl InnerMultipart {
|
||||
match payload.readline() {
|
||||
Some(chunk) => {
|
||||
if chunk.is_empty() {
|
||||
//ValueError("Could not find starting boundary %r"
|
||||
//% (self._boundary))
|
||||
return Err(MultipartError::Boundary);
|
||||
}
|
||||
if chunk.len() < boundary.len() {
|
||||
continue;
|
||||
@@ -505,47 +504,72 @@ impl InnerField {
|
||||
payload: &mut PayloadBuffer,
|
||||
boundary: &str,
|
||||
) -> Poll<Option<Bytes>, MultipartError> {
|
||||
match payload.read_until(b"\r") {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
let mut pos = 0;
|
||||
|
||||
let len = payload.buf.len();
|
||||
if len == 0 {
|
||||
return Ok(Async::NotReady);
|
||||
}
|
||||
|
||||
// check boundary
|
||||
if len > 4 && payload.buf[0] == b'\r' {
|
||||
let b_len = if &payload.buf[..2] == b"\r\n" && &payload.buf[2..4] == b"--" {
|
||||
Some(4)
|
||||
} else if &payload.buf[1..3] == b"--" {
|
||||
Some(3)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(b_len) = b_len {
|
||||
let b_size = boundary.len() + b_len;
|
||||
if len < b_size {
|
||||
return Ok(Async::NotReady);
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
} else {
|
||||
pos = b_size;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(mut chunk) => {
|
||||
if chunk.len() == 1 {
|
||||
payload.unprocessed(chunk);
|
||||
match payload.read_exact(boundary.len() + 4) {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
Some(mut chunk) => {
|
||||
if &chunk[..2] == b"\r\n"
|
||||
&& &chunk[2..4] == b"--"
|
||||
&& &chunk[4..] == boundary.as_bytes()
|
||||
{
|
||||
payload.unprocessed(chunk);
|
||||
Ok(Async::Ready(None))
|
||||
} else {
|
||||
// \r might be part of data stream
|
||||
let ch = chunk.split_to(1);
|
||||
payload.unprocessed(chunk);
|
||||
Ok(Async::Ready(Some(ch)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
return if let Some(idx) = twoway::find_bytes(&payload.buf[pos..], b"\r") {
|
||||
let cur = pos + idx;
|
||||
|
||||
// check if we have enough data for boundary detection
|
||||
if cur + 4 > len {
|
||||
if cur > 0 {
|
||||
Ok(Async::Ready(Some(payload.buf.split_to(cur).freeze())))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
} else {
|
||||
let to = chunk.len() - 1;
|
||||
let ch = chunk.split_to(to);
|
||||
payload.unprocessed(chunk);
|
||||
Ok(Async::Ready(Some(ch)))
|
||||
// check boundary
|
||||
if (&payload.buf[cur..cur + 2] == b"\r\n"
|
||||
&& &payload.buf[cur + 2..cur + 4] == b"--")
|
||||
|| (&payload.buf[cur..cur + 1] == b"\r"
|
||||
&& &payload.buf[cur + 1..cur + 3] == b"--")
|
||||
{
|
||||
if cur != 0 {
|
||||
// return buffer
|
||||
Ok(Async::Ready(Some(payload.buf.split_to(cur).freeze())))
|
||||
} else {
|
||||
pos = cur + 1;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// not boundary
|
||||
pos = cur + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Ok(Async::Ready(Some(payload.buf.take().freeze())));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,26 +579,27 @@ impl InnerField {
|
||||
}
|
||||
|
||||
let result = if let Some(payload) = self.payload.as_ref().unwrap().get_mut(s) {
|
||||
let res = if let Some(ref mut len) = self.length {
|
||||
InnerField::read_len(payload, len)?
|
||||
} else {
|
||||
InnerField::read_stream(payload, &self.boundary)?
|
||||
};
|
||||
if !self.eof {
|
||||
let res = if let Some(ref mut len) = self.length {
|
||||
InnerField::read_len(payload, len)?
|
||||
} else {
|
||||
InnerField::read_stream(payload, &self.boundary)?
|
||||
};
|
||||
|
||||
match res {
|
||||
Async::NotReady => Async::NotReady,
|
||||
Async::Ready(Some(bytes)) => Async::Ready(Some(bytes)),
|
||||
Async::Ready(None) => {
|
||||
self.eof = true;
|
||||
match payload.readline() {
|
||||
None => Async::Ready(None),
|
||||
Some(line) => {
|
||||
if line.as_ref() != b"\r\n" {
|
||||
log::warn!("multipart field did not read all the data or it is malformed");
|
||||
}
|
||||
Async::Ready(None)
|
||||
}
|
||||
match res {
|
||||
Async::NotReady => return Ok(Async::NotReady),
|
||||
Async::Ready(Some(bytes)) => return Ok(Async::Ready(Some(bytes))),
|
||||
Async::Ready(None) => self.eof = true,
|
||||
}
|
||||
}
|
||||
|
||||
match payload.readline() {
|
||||
None => Async::Ready(None),
|
||||
Some(line) => {
|
||||
if line.as_ref() != b"\r\n" {
|
||||
log::warn!("multipart field did not read all the data or it is malformed");
|
||||
}
|
||||
Async::Ready(None)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -704,7 +729,7 @@ impl PayloadBuffer {
|
||||
}
|
||||
|
||||
/// Read exact number of bytes
|
||||
#[inline]
|
||||
#[cfg(test)]
|
||||
fn read_exact(&mut self, size: usize) -> Option<Bytes> {
|
||||
if size <= self.buf.len() {
|
||||
Some(self.buf.split_to(size).freeze())
|
||||
@@ -875,6 +900,78 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stream() {
|
||||
run_on(|| {
|
||||
let (sender, payload) = create_stream();
|
||||
|
||||
let bytes = Bytes::from(
|
||||
"testasdadsad\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\n\r\n\
|
||||
test\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\n\r\n\
|
||||
data\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
|
||||
);
|
||||
sender.unbounded_send(Ok(bytes)).unwrap();
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static(
|
||||
"multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
|
||||
),
|
||||
);
|
||||
|
||||
let mut multipart = Multipart::new(&headers, payload);
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(mut field)) => {
|
||||
let cd = field.content_disposition().unwrap();
|
||||
assert_eq!(cd.disposition, DispositionType::FormData);
|
||||
assert_eq!(cd.parameters[0], DispositionParam::Name("file".into()));
|
||||
|
||||
assert_eq!(field.content_type().type_(), mime::TEXT);
|
||||
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
||||
|
||||
match field.poll().unwrap() {
|
||||
Async::Ready(Some(chunk)) => assert_eq!(chunk, "test"),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
match field.poll().unwrap() {
|
||||
Async::Ready(None) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(mut field)) => {
|
||||
assert_eq!(field.content_type().type_(), mime::TEXT);
|
||||
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
||||
|
||||
match field.poll() {
|
||||
Ok(Async::Ready(Some(chunk))) => assert_eq!(chunk, "data"),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
match field.poll() {
|
||||
Ok(Async::Ready(None)) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(None) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
run_on(|| {
|
||||
|
@@ -1,5 +1,11 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Update actix-web to beta.1
|
||||
|
||||
* `CookieSession::max_age()` accepts value in seconds
|
||||
|
||||
## [0.1.0-alpha.6] - 2019-04-14
|
||||
|
||||
* Update actix-web alpha.6
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-session"
|
||||
version = "0.1.0-alpha.6"
|
||||
version = "0.1.0-beta.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Session for actix web framework."
|
||||
readme = "README.md"
|
||||
@@ -24,15 +24,15 @@ default = ["cookie-session"]
|
||||
cookie-session = ["actix-web/secure-cookies"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-alpha.6"
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-service = "0.3.4"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.2.0"
|
||||
hashbrown = "0.2.2"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
time = "0.1"
|
||||
time = "0.1.42"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
|
@@ -27,7 +27,6 @@ use derive_more::{Display, From};
|
||||
use futures::future::{ok, Future, FutureResult};
|
||||
use futures::Poll;
|
||||
use serde_json::error::Error as JsonError;
|
||||
use time::Duration;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -57,7 +56,7 @@ struct CookieSessionInner {
|
||||
domain: Option<String>,
|
||||
secure: bool,
|
||||
http_only: bool,
|
||||
max_age: Option<Duration>,
|
||||
max_age: Option<time::Duration>,
|
||||
same_site: Option<SameSite>,
|
||||
}
|
||||
|
||||
@@ -250,7 +249,12 @@ impl CookieSession {
|
||||
}
|
||||
|
||||
/// 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);
|
||||
self
|
||||
}
|
||||
@@ -317,6 +321,7 @@ where
|
||||
mod tests {
|
||||
use super::*;
|
||||
use actix_web::{test, web, App};
|
||||
use bytes::Bytes;
|
||||
|
||||
#[test]
|
||||
fn cookie_session() {
|
||||
@@ -338,6 +343,26 @@ mod tests {
|
||||
.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]
|
||||
fn cookie_session_extractor() {
|
||||
let mut app = test::init_service(
|
||||
@@ -357,4 +382,44 @@ mod tests {
|
||||
.find(|c| c.name() == "actix-session")
|
||||
.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"));
|
||||
}
|
||||
}
|
||||
|
@@ -18,13 +18,13 @@ name = "actix_web_actors"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.8.0-alpha.3"
|
||||
actix-web = "1.0.0-alpha.5"
|
||||
actix-http = "0.1.0-alpha.5"
|
||||
actix = "0.8.0"
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-http = "0.1.1"
|
||||
actix-codec = "0.1.2"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.6"
|
||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
|
@@ -199,7 +199,7 @@ mod tests {
|
||||
|
||||
use actix::Actor;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::test::{block_on, call_success, init_service, TestRequest};
|
||||
use actix_web::test::{block_on, call_service, init_service, TestRequest};
|
||||
use actix_web::{web, App, HttpResponse};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
|
||||
@@ -237,7 +237,7 @@ mod tests {
|
||||
})));
|
||||
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let mut resp = call_success(&mut srv, req);
|
||||
let mut resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let body = block_on(resp.take_body().fold(
|
||||
|
@@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Gen code for actix-web 1.0.0-beta.1
|
||||
|
||||
## [0.1.0-alpha.6] - 2019-04-14
|
||||
|
||||
* Gen code for actix-web 1.0.0-alpha.6
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-codegen"
|
||||
version = "0.1.0-alpha.6"
|
||||
version = "0.1.0-beta.1"
|
||||
description = "Actix web proc macros"
|
||||
readme = "README.md"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
@@ -17,6 +17,6 @@ syn = { version = "0.15", features = ["full", "parsing"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-alpha.6" }
|
||||
actix-http = { version = "0.1.0-alpha.5", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
||||
actix-http = { version = "0.1.1", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
futures = { version = "0.1" }
|
||||
|
@@ -62,7 +62,7 @@ impl fmt::Display for Args {
|
||||
pub struct {name};
|
||||
|
||||
impl actix_web::dev::HttpServiceFactory for {name} {{
|
||||
fn register(self, config: &mut actix_web::dev::ServiceConfig) {{
|
||||
fn register(self, config: &mut actix_web::dev::AppService) {{
|
||||
{ast}
|
||||
|
||||
let resource = actix_web::Resource::new(\"{path}\"){guards}.{to}({name});
|
||||
|
@@ -1,5 +1,21 @@
|
||||
# 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
|
||||
|
||||
### Changed
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "0.1.0-alpha.6"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http client."
|
||||
readme = "README.md"
|
||||
@@ -38,7 +38,7 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-http = "0.1.0-alpha.5"
|
||||
actix-http = "0.1.2"
|
||||
base64 = "0.10.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
@@ -55,11 +55,11 @@ openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-web = { version = "1.0.0-alpha.6", features=["ssl"] }
|
||||
actix-http = { version = "0.1.0-alpha.5", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0-beta.1", features=["ssl"] }
|
||||
actix-http = { version = "0.1.2", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
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" }
|
||||
flate2 = { version="1.0.2" }
|
||||
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)
|
||||
|
||||
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::time::Duration;
|
||||
|
||||
use actix_http::client::{ConnectError, Connection, Connector};
|
||||
use actix_http::http::{header, HeaderMap, HeaderName, HttpTryFrom, Uri};
|
||||
use actix_http::client::{Connect, ConnectError, Connection, Connector};
|
||||
use actix_http::http::{header, HeaderMap, HeaderName, HttpTryFrom};
|
||||
use actix_service::Service;
|
||||
|
||||
use crate::connect::ConnectorWrapper;
|
||||
@@ -40,7 +40,7 @@ impl ClientBuilder {
|
||||
/// Use custom connector service.
|
||||
pub fn connector<T>(mut self, connector: T) -> Self
|
||||
where
|
||||
T: Service<Request = Uri, Error = ConnectError> + 'static,
|
||||
T: Service<Request = Connect, Error = ConnectError> + 'static,
|
||||
T::Response: Connection,
|
||||
<T::Response as Connection>::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_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::{http, RequestHead, ResponseHead};
|
||||
use actix_http::{RequestHead, ResponseHead};
|
||||
use actix_service::Service;
|
||||
use futures::{Future, Poll};
|
||||
|
||||
@@ -17,12 +19,14 @@ pub(crate) trait Connect {
|
||||
&mut self,
|
||||
head: RequestHead,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>>;
|
||||
|
||||
/// Send request, returns Response and Framed
|
||||
fn open_tunnel(
|
||||
&mut self,
|
||||
head: RequestHead,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
@@ -33,7 +37,7 @@ pub(crate) trait Connect {
|
||||
|
||||
impl<T> Connect for ConnectorWrapper<T>
|
||||
where
|
||||
T: Service<Request = http::Uri, Error = ConnectError>,
|
||||
T: Service<Request = ClientConnect, Error = ConnectError>,
|
||||
T::Response: Connection,
|
||||
<T::Response as Connection>::Io: 'static,
|
||||
<T::Response as Connection>::Future: 'static,
|
||||
@@ -44,11 +48,15 @@ where
|
||||
&mut self,
|
||||
head: RequestHead,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>> {
|
||||
Box::new(
|
||||
self.0
|
||||
// connect to the host
|
||||
.call(head.uri.clone())
|
||||
.call(ClientConnect {
|
||||
uri: head.uri.clone(),
|
||||
addr,
|
||||
})
|
||||
.from_err()
|
||||
// send request
|
||||
.and_then(move |connection| connection.send_request(head, body))
|
||||
@@ -59,6 +67,7 @@ where
|
||||
fn open_tunnel(
|
||||
&mut self,
|
||||
head: RequestHead,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
@@ -68,7 +77,10 @@ where
|
||||
Box::new(
|
||||
self.0
|
||||
// connect to the host
|
||||
.call(head.uri.clone())
|
||||
.call(ClientConnect {
|
||||
uri: head.uri.clone(),
|
||||
addr,
|
||||
})
|
||||
.from_err()
|
||||
// send request
|
||||
.and_then(move |connection| connection.open_tunnel(head))
|
||||
|
@@ -1,8 +1,8 @@
|
||||
use std::fmt;
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::io::Write;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
use std::{fmt, net};
|
||||
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
use futures::future::{err, Either};
|
||||
@@ -60,6 +60,7 @@ const HTTPS_ENCODING: &str = "gzip, deflate";
|
||||
pub struct ClientRequest {
|
||||
pub(crate) head: RequestHead,
|
||||
err: Option<HttpError>,
|
||||
addr: Option<net::SocketAddr>,
|
||||
cookies: Option<CookieJar>,
|
||||
response_decompress: bool,
|
||||
timeout: Option<Duration>,
|
||||
@@ -76,6 +77,7 @@ impl ClientRequest {
|
||||
config,
|
||||
head: RequestHead::default(),
|
||||
err: None,
|
||||
addr: None,
|
||||
cookies: None,
|
||||
timeout: None,
|
||||
response_decompress: true,
|
||||
@@ -97,6 +99,15 @@ impl ClientRequest {
|
||||
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.
|
||||
#[inline]
|
||||
pub fn method(mut self, method: Method) -> Self {
|
||||
@@ -331,26 +342,28 @@ impl ClientRequest {
|
||||
|
||||
/// This method calls provided closure with builder reference if
|
||||
/// 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
|
||||
F: FnOnce(&mut ClientRequest),
|
||||
F: FnOnce(ClientRequest) -> ClientRequest,
|
||||
{
|
||||
if value {
|
||||
f(&mut self);
|
||||
f(self)
|
||||
} else {
|
||||
self
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// This method calls provided closure with builder reference if
|
||||
/// 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
|
||||
F: FnOnce(T, &mut ClientRequest),
|
||||
F: FnOnce(T, ClientRequest) -> ClientRequest,
|
||||
{
|
||||
if let Some(val) = value {
|
||||
f(val, &mut self);
|
||||
f(val, self)
|
||||
} else {
|
||||
self
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Complete request construction and send body.
|
||||
@@ -433,7 +446,7 @@ impl ClientRequest {
|
||||
let fut = config
|
||||
.connector
|
||||
.borrow_mut()
|
||||
.send_request(head, body.into())
|
||||
.send_request(head, body.into(), slf.addr)
|
||||
.map(move |res| {
|
||||
res.map_body(|head, payload| {
|
||||
if response_decompress {
|
||||
@@ -544,6 +557,8 @@ impl fmt::Debug for ClientRequest {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::SystemTime;
|
||||
|
||||
use super::*;
|
||||
use crate::Client;
|
||||
|
||||
@@ -555,6 +570,33 @@ mod tests {
|
||||
assert!(repr.contains("x-test"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basics() {
|
||||
let mut req = Client::new()
|
||||
.put("/")
|
||||
.version(Version::HTTP_2)
|
||||
.set(header::Date(SystemTime::now().into()))
|
||||
.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);
|
||||
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
||||
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);
|
||||
let _ = req.headers_mut();
|
||||
let _ = req.send_body("");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_client_header() {
|
||||
let req = Client::build()
|
||||
|
@@ -134,3 +134,23 @@ impl TestResponse {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::SystemTime;
|
||||
|
||||
use super::*;
|
||||
use crate::{cookie, http::header};
|
||||
|
||||
#[test]
|
||||
fn test_basics() {
|
||||
let res = TestResponse::default()
|
||||
.version(Version::HTTP_2)
|
||||
.set(header::Date(SystemTime::now().into()))
|
||||
.cookie(cookie::Cookie::build("name", "value").finish())
|
||||
.finish();
|
||||
assert!(res.headers().contains_key(header::SET_COOKIE));
|
||||
assert!(res.headers().contains_key(header::DATE));
|
||||
assert_eq!(res.version(), Version::HTTP_2);
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,6 @@
|
||||
//! Websockets client
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::net::SocketAddr;
|
||||
use std::rc::Rc;
|
||||
use std::{fmt, str};
|
||||
|
||||
@@ -29,6 +30,7 @@ pub struct WebsocketsRequest {
|
||||
err: Option<HttpError>,
|
||||
origin: Option<HeaderValue>,
|
||||
protocols: Option<String>,
|
||||
addr: Option<SocketAddr>,
|
||||
max_size: usize,
|
||||
server_mode: bool,
|
||||
cookies: Option<CookieJar>,
|
||||
@@ -55,6 +57,7 @@ impl WebsocketsRequest {
|
||||
head,
|
||||
err,
|
||||
config,
|
||||
addr: None,
|
||||
origin: None,
|
||||
protocols: None,
|
||||
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
|
||||
pub fn protocols<U, V>(mut self, protos: U) -> Self
|
||||
where
|
||||
@@ -274,7 +286,7 @@ impl WebsocketsRequest {
|
||||
.config
|
||||
.connector
|
||||
.borrow_mut()
|
||||
.open_tunnel(head)
|
||||
.open_tunnel(head, self.addr)
|
||||
.from_err()
|
||||
.and_then(move |(head, framed)| {
|
||||
// verify response
|
||||
@@ -445,20 +457,41 @@ mod tests {
|
||||
.unwrap(),
|
||||
"Bearer someS3cr3tAutht0k3n"
|
||||
);
|
||||
let _ = req.connect();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basics() {
|
||||
let req = Client::new()
|
||||
.ws("/")
|
||||
.origin("test-origin")
|
||||
.max_frame_size(100)
|
||||
.server_mode()
|
||||
.protocols(&["v1", "v2"])
|
||||
.cookie(Cookie::build("cookie1", "value1").finish());
|
||||
assert_eq!(req.origin.unwrap().to_str().unwrap(), "test-origin");
|
||||
assert_eq!(req.max_size, 100);
|
||||
assert_eq!(req.server_mode, true);
|
||||
assert_eq!(req.protocols, Some("v1,v2".to_string()));
|
||||
actix_http_test::run_on(|| {
|
||||
let req = Client::new()
|
||||
.ws("http://localhost/")
|
||||
.origin("test-origin")
|
||||
.max_frame_size(100)
|
||||
.server_mode()
|
||||
.protocols(&["v1", "v2"])
|
||||
.set_header_if_none(header::CONTENT_TYPE, "json")
|
||||
.set_header_if_none(header::CONTENT_TYPE, "text")
|
||||
.cookie(Cookie::build("cookie1", "value1").finish());
|
||||
assert_eq!(
|
||||
req.origin.as_ref().unwrap().to_str().unwrap(),
|
||||
"test-origin"
|
||||
);
|
||||
assert_eq!(req.max_size, 100);
|
||||
assert_eq!(req.server_mode, true);
|
||||
assert_eq!(req.protocols, Some("v1,v2".to_string()));
|
||||
assert_eq!(
|
||||
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
|
||||
header::HeaderValue::from_static("json")
|
||||
);
|
||||
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,16 +1,23 @@
|
||||
use std::io::Write;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use brotli2::write::BrotliEncoder;
|
||||
use bytes::Bytes;
|
||||
use flate2::read::GzDecoder;
|
||||
use flate2::write::GzEncoder;
|
||||
use flate2::Compression;
|
||||
use futures::future::Future;
|
||||
use futures::Future;
|
||||
use rand::Rng;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_web::http::Cookie;
|
||||
use actix_service::{fn_service, NewService};
|
||||
use actix_web::http::{Cookie, Version};
|
||||
use actix_web::middleware::{BodyEncoding, Compress};
|
||||
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
|
||||
use awc::error::SendRequestError;
|
||||
|
||||
@@ -36,6 +43,30 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World";
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>(
|
||||
) -> std::io::Result<actix_server::ssl::OpensslAcceptor<T, ()>> {
|
||||
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder
|
||||
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
|
||||
.unwrap();
|
||||
builder
|
||||
.set_certificate_chain_file("../tests/cert.pem")
|
||||
.unwrap();
|
||||
builder.set_alpn_select_callback(|_, protos| {
|
||||
const H2: &[u8] = b"\x02h2";
|
||||
if protos.windows(3).any(|window| window == H2) {
|
||||
Ok(b"h2")
|
||||
} else {
|
||||
Err(openssl::ssl::AlpnError::NOACK)
|
||||
}
|
||||
});
|
||||
builder.set_alpn_protos(b"\x02h2")?;
|
||||
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_simple() {
|
||||
let mut srv =
|
||||
@@ -61,6 +92,38 @@ fn test_simple() {
|
||||
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]
|
||||
fn test_timeout() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@@ -95,11 +158,9 @@ fn test_timeout_override() {
|
||||
))))
|
||||
});
|
||||
|
||||
let client = srv.execute(|| {
|
||||
awc::Client::build()
|
||||
.timeout(Duration::from_millis(50000))
|
||||
.finish()
|
||||
});
|
||||
let client = awc::Client::build()
|
||||
.timeout(Duration::from_millis(50000))
|
||||
.finish();
|
||||
let request = client
|
||||
.get(srv.url("/"))
|
||||
.timeout(Duration::from_millis(50))
|
||||
@@ -110,58 +171,309 @@ fn test_timeout_override() {
|
||||
}
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn test_connection_close() {
|
||||
// let mut srv =
|
||||
// test::TestServer::new(|app| app.handler(|_| HttpResponse::Ok().body(STR)));
|
||||
#[test]
|
||||
fn test_connection_reuse() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
// let request = srv.get("/").header("Connection", "close").finish().unwrap();
|
||||
// let response = srv.execute(request.send()).unwrap();
|
||||
// assert!(response.status().is_success());
|
||||
// }
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||
))
|
||||
});
|
||||
|
||||
// #[test]
|
||||
// fn test_with_query_parameter() {
|
||||
// let mut srv = test::TestServer::new(|app| {
|
||||
// app.handler(|req: &HttpRequest| match req.query().get("qp") {
|
||||
// Some(_) => HttpResponse::Ok().finish(),
|
||||
// None => HttpResponse::BadRequest().finish(),
|
||||
// })
|
||||
// });
|
||||
let client = awc::Client::default();
|
||||
|
||||
// let request = srv.get("/").uri(srv.url("/?qp=5").as_str()).finish().unwrap();
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// let response = srv.execute(request.send()).unwrap();
|
||||
// assert!(response.status().is_success());
|
||||
// }
|
||||
// req 2
|
||||
let req = client.post(srv.url("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// #[test]
|
||||
// fn test_no_decompress() {
|
||||
// let mut srv =
|
||||
// test::TestServer::new(|app| app.handler(|_| HttpResponse::Ok().body(STR)));
|
||||
// one connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
// let request = srv.get("/").disable_decompress().finish().unwrap();
|
||||
// let response = srv.execute(request.send()).unwrap();
|
||||
// assert!(response.status().is_success());
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_connection_reuse_h2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
// // read response
|
||||
// let bytes = srv.execute(response.body()).unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e)),
|
||||
)
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
// let 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()));
|
||||
// disable ssl verification
|
||||
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
|
||||
|
||||
// // POST
|
||||
// let request = srv.post().disable_decompress().finish().unwrap();
|
||||
// let response = srv.execute(request.send()).unwrap();
|
||||
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
builder.set_verify(SslVerifyMode::NONE);
|
||||
let _ = builder
|
||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
|
||||
|
||||
// let bytes = srv.execute(response.body()).unwrap();
|
||||
// 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()));
|
||||
// }
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().ssl(builder.build()).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.surl("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.surl("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
// one connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_force_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||
))
|
||||
});
|
||||
|
||||
let client = awc::Client::default();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).force_close().send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.url("/")).force_close();
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_server_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.route(web::to(|| HttpResponse::Ok().force_close().finish())),
|
||||
),
|
||||
))
|
||||
});
|
||||
|
||||
let client = awc::Client::default();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.url("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_wait_queue() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(App::new().service(
|
||||
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||
)))
|
||||
});
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().limit(1).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let mut response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req2 = client.post(srv.url("/"));
|
||||
let req2_fut = srv.execute(move || {
|
||||
let mut fut = req2.send();
|
||||
assert!(fut.poll().unwrap().is_not_ready());
|
||||
fut
|
||||
});
|
||||
|
||||
// read response 1
|
||||
let bytes = srv.block_on(response.body()).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
|
||||
// req 2
|
||||
let response = srv.block_on(req2_fut).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_wait_queue_force_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(HttpService::new(
|
||||
App::new().service(
|
||||
web::resource("/")
|
||||
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
|
||||
),
|
||||
))
|
||||
});
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().limit(1).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.url("/")).send();
|
||||
let mut response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req2 = client.post(srv.url("/"));
|
||||
let req2_fut = srv.execute(move || {
|
||||
let mut fut = req2.send();
|
||||
assert!(fut.poll().unwrap().is_not_ready());
|
||||
fut
|
||||
});
|
||||
|
||||
// read response 1
|
||||
let bytes = srv.block_on(response.body()).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
|
||||
// req 2
|
||||
let response = srv.block_on(req2_fut).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// two connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_query_parameter() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::new(App::new().service(web::resource("/").to(
|
||||
|req: HttpRequest| {
|
||||
if req.query_string().contains("qp") {
|
||||
HttpResponse::Ok()
|
||||
} else {
|
||||
HttpResponse::BadRequest()
|
||||
}
|
||||
},
|
||||
)))
|
||||
});
|
||||
|
||||
let res = srv
|
||||
.block_on(awc::Client::new().get(srv.url("/?qp=5")).send())
|
||||
.unwrap();
|
||||
assert!(res.status().is_success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_decompress() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::new(App::new().wrap(Compress::default()).service(
|
||||
web::resource("/").route(web::to(|| {
|
||||
let mut res = HttpResponse::Ok().body(STR);
|
||||
res.encoding(header::ContentEncoding::Gzip);
|
||||
res
|
||||
})),
|
||||
))
|
||||
});
|
||||
|
||||
let mut res = srv
|
||||
.block_on(awc::Client::new().get(srv.url("/")).no_decompress().send())
|
||||
.unwrap();
|
||||
assert!(res.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.block_on(res.body()).unwrap();
|
||||
|
||||
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()));
|
||||
|
||||
// POST
|
||||
let mut res = srv
|
||||
.block_on(awc::Client::new().post(srv.url("/")).no_decompress().send())
|
||||
.unwrap();
|
||||
assert!(res.status().is_success());
|
||||
|
||||
let bytes = srv.block_on(res.body()).unwrap();
|
||||
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()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_client_gzip_encoding() {
|
||||
|
43
src/app.rs
43
src/app.rs
@@ -12,7 +12,7 @@ use actix_service::{
|
||||
use futures::IntoFuture;
|
||||
|
||||
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
|
||||
use crate::config::{AppConfig, AppConfigInner, RouterConfig};
|
||||
use crate::config::{AppConfig, AppConfigInner, ServiceConfig};
|
||||
use crate::data::{Data, DataFactory};
|
||||
use crate::dev::ResourceDef;
|
||||
use crate::error::Error;
|
||||
@@ -125,7 +125,7 @@ where
|
||||
/// use actix_web::{web, middleware, App, HttpResponse};
|
||||
///
|
||||
/// // this function could be located in different module
|
||||
/// fn config(cfg: &mut web::RouterConfig) {
|
||||
/// fn config(cfg: &mut web::ServiceConfig) {
|
||||
/// cfg.service(web::resource("/test")
|
||||
/// .route(web::get().to(|| HttpResponse::Ok()))
|
||||
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
|
||||
@@ -141,9 +141,9 @@ where
|
||||
/// ```
|
||||
pub fn configure<F>(mut self, f: F) -> Self
|
||||
where
|
||||
F: Fn(&mut RouterConfig),
|
||||
F: Fn(&mut ServiceConfig),
|
||||
{
|
||||
let mut cfg = RouterConfig::new();
|
||||
let mut cfg = ServiceConfig::new();
|
||||
f(&mut cfg);
|
||||
self.data.extend(cfg.data);
|
||||
self.services.extend(cfg.services);
|
||||
@@ -431,13 +431,14 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
use bytes::Bytes;
|
||||
use futures::{Future, IntoFuture};
|
||||
|
||||
use super::*;
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::test::{block_on, call_success, init_service, TestRequest};
|
||||
use crate::{web, Error, HttpResponse};
|
||||
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
|
||||
use crate::{web, Error, HttpRequest, HttpResponse};
|
||||
|
||||
#[test]
|
||||
fn test_default_resource() {
|
||||
@@ -527,7 +528,7 @@ mod tests {
|
||||
.route("/test", web::get().to(|| HttpResponse::Ok())),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
@@ -543,7 +544,7 @@ mod tests {
|
||||
.wrap(md),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
@@ -567,7 +568,7 @@ mod tests {
|
||||
.service(web::resource("/test").to(|| HttpResponse::Ok())),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
@@ -591,11 +592,33 @@ mod tests {
|
||||
}),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
HeaderValue::from_static("0001")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_external_resource() {
|
||||
let mut srv = init_service(
|
||||
App::new()
|
||||
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| {
|
||||
HttpResponse::Ok().body(format!(
|
||||
"{}",
|
||||
req.url_for("youtube", &["12345"]).unwrap()
|
||||
))
|
||||
}),
|
||||
),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = read_body(resp);
|
||||
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
|
||||
}
|
||||
}
|
||||
|
@@ -10,7 +10,7 @@ use actix_service::{fn_service, NewService, Service};
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::config::{AppConfig, ServiceConfig};
|
||||
use crate::config::{AppConfig, AppService};
|
||||
use crate::data::{DataFactory, DataFactoryResult};
|
||||
use crate::error::Error;
|
||||
use crate::guard::Guard;
|
||||
@@ -77,8 +77,7 @@ where
|
||||
loc_cfg.addr = cfg.local_addr();
|
||||
}
|
||||
|
||||
let mut config =
|
||||
ServiceConfig::new(self.config.borrow().clone(), default.clone());
|
||||
let mut config = AppService::new(self.config.borrow().clone(), default.clone());
|
||||
|
||||
// register services
|
||||
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
|
||||
@@ -163,7 +162,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
if self.endpoint.is_some() {
|
||||
if self.endpoint.is_some() && self.data.is_empty() {
|
||||
Ok(Async::Ready(AppInitService {
|
||||
service: self.endpoint.take().unwrap(),
|
||||
rmap: self.rmap.clone(),
|
||||
|
@@ -23,7 +23,7 @@ type HttpNewService =
|
||||
boxed::BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
|
||||
|
||||
/// Application configuration
|
||||
pub struct ServiceConfig {
|
||||
pub struct AppService {
|
||||
config: AppConfig,
|
||||
root: bool,
|
||||
default: Rc<HttpNewService>,
|
||||
@@ -35,10 +35,10 @@ pub struct ServiceConfig {
|
||||
)>,
|
||||
}
|
||||
|
||||
impl ServiceConfig {
|
||||
impl AppService {
|
||||
/// Crate server settings instance
|
||||
pub(crate) fn new(config: AppConfig, default: Rc<HttpNewService>) -> Self {
|
||||
ServiceConfig {
|
||||
AppService {
|
||||
config,
|
||||
default,
|
||||
root: true,
|
||||
@@ -63,7 +63,7 @@ impl ServiceConfig {
|
||||
}
|
||||
|
||||
pub(crate) fn clone_config(&self) -> Self {
|
||||
ServiceConfig {
|
||||
AppService {
|
||||
config: self.config.clone(),
|
||||
default: self.default.clone(),
|
||||
services: Vec::new(),
|
||||
@@ -165,17 +165,17 @@ impl Default for AppConfigInner {
|
||||
}
|
||||
}
|
||||
|
||||
/// Router config. It is used for external configuration.
|
||||
/// Service config is used for external configuration.
|
||||
/// Part of application configuration could be offloaded
|
||||
/// to set of external methods. This could help with
|
||||
/// modularization of big application configuration.
|
||||
pub struct RouterConfig {
|
||||
pub struct ServiceConfig {
|
||||
pub(crate) services: Vec<Box<ServiceFactory>>,
|
||||
pub(crate) data: Vec<Box<DataFactory>>,
|
||||
pub(crate) external: Vec<ResourceDef>,
|
||||
}
|
||||
|
||||
impl RouterConfig {
|
||||
impl ServiceConfig {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
services: Vec::new(),
|
||||
@@ -253,15 +253,18 @@ impl RouterConfig {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
use bytes::Bytes;
|
||||
use futures::Future;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use super::*;
|
||||
use crate::http::StatusCode;
|
||||
use crate::test::{block_on, init_service, TestRequest};
|
||||
use crate::{web, App, HttpResponse};
|
||||
use crate::http::{Method, StatusCode};
|
||||
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
|
||||
use crate::{web, App, HttpRequest, HttpResponse};
|
||||
|
||||
#[test]
|
||||
fn test_data() {
|
||||
let cfg = |cfg: &mut RouterConfig| {
|
||||
let cfg = |cfg: &mut ServiceConfig| {
|
||||
cfg.data(10usize);
|
||||
};
|
||||
|
||||
@@ -276,8 +279,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_data_factory() {
|
||||
let cfg = |cfg: &mut RouterConfig| {
|
||||
cfg.data_factory(|| Ok::<_, ()>(10usize));
|
||||
let cfg = |cfg: &mut ServiceConfig| {
|
||||
cfg.data_factory(|| {
|
||||
sleep(std::time::Duration::from_millis(50)).then(|_| {
|
||||
println!("READY");
|
||||
Ok::<_, ()>(10usize)
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
let mut srv =
|
||||
@@ -288,7 +296,7 @@ mod tests {
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let cfg2 = |cfg: &mut RouterConfig| {
|
||||
let cfg2 = |cfg: &mut ServiceConfig| {
|
||||
cfg.data_factory(|| Ok::<_, ()>(10u32));
|
||||
};
|
||||
let mut srv = init_service(
|
||||
@@ -300,4 +308,53 @@ mod tests {
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_external_resource() {
|
||||
let mut srv = init_service(
|
||||
App::new()
|
||||
.configure(|cfg| {
|
||||
cfg.external_resource(
|
||||
"youtube",
|
||||
"https://youtube.com/watch/{video_id}",
|
||||
);
|
||||
})
|
||||
.route(
|
||||
"/test",
|
||||
web::get().to(|req: HttpRequest| {
|
||||
HttpResponse::Ok().body(format!(
|
||||
"{}",
|
||||
req.url_for("youtube", &["12345"]).unwrap()
|
||||
))
|
||||
}),
|
||||
),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = read_body(resp);
|
||||
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_service() {
|
||||
let mut srv = init_service(App::new().configure(|cfg| {
|
||||
cfg.service(
|
||||
web::resource("/test").route(web::get().to(|| HttpResponse::Created())),
|
||||
)
|
||||
.route("/index.html", web::get().to(|| HttpResponse::Ok()));
|
||||
}));
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::GET)
|
||||
.to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
|
||||
let req = TestRequest::with_uri("/index.html")
|
||||
.method(Method::GET)
|
||||
.to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
}
|
||||
|
@@ -61,6 +61,7 @@ pub(crate) trait DataFactoryResult {
|
||||
/// web::get().to(index)));
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Debug)]
|
||||
pub struct Data<T>(Arc<T>);
|
||||
|
||||
impl<T> Data<T> {
|
||||
|
@@ -265,13 +265,12 @@ tuple_from_req!(TupleFromRequest10, (0, A), (1, B), (2, C), (3, D), (4, E), (5,
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_http::http::header;
|
||||
use actix_router::ResourceDef;
|
||||
use bytes::Bytes;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use super::*;
|
||||
use crate::test::{block_on, TestRequest};
|
||||
use crate::types::{Form, FormConfig, Path, Query};
|
||||
use crate::types::{Form, FormConfig};
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq)]
|
||||
struct Info {
|
||||
@@ -350,58 +349,4 @@ mod tests {
|
||||
block_on(Result::<Form<Info>, Error>::from_request(&req, &mut pl)).unwrap();
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
@@ -124,7 +124,7 @@ where
|
||||
pub trait AsyncFactory<T, R>: Clone + 'static
|
||||
where
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
fn call(&self, param: T) -> R;
|
||||
@@ -134,7 +134,7 @@ impl<F, R> AsyncFactory<(), R> for F
|
||||
where
|
||||
F: Fn() -> R + Clone + 'static,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
fn call(&self, _: ()) -> R {
|
||||
@@ -147,7 +147,7 @@ pub struct AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
hnd: F,
|
||||
@@ -158,7 +158,7 @@ impl<F, T, R> AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
pub fn new(hnd: F) -> Self {
|
||||
@@ -173,7 +173,7 @@ impl<F, T, R> Clone for AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
@@ -188,7 +188,7 @@ impl<F, T, R> Service for AsyncHandler<F, T, R>
|
||||
where
|
||||
F: AsyncFactory<T, R>,
|
||||
R: IntoFuture,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
type Request = (T, HttpRequest);
|
||||
@@ -203,32 +203,56 @@ where
|
||||
fn call(&mut self, (param, req): (T, HttpRequest)) -> Self::Future {
|
||||
AsyncHandlerServiceResponse {
|
||||
fut: self.hnd.call(param).into_future(),
|
||||
fut2: None,
|
||||
req: Some(req),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct AsyncHandlerServiceResponse<T> {
|
||||
pub struct AsyncHandlerServiceResponse<T>
|
||||
where
|
||||
T: Future,
|
||||
T::Item: Responder,
|
||||
{
|
||||
fut: T,
|
||||
fut2: Option<<<T::Item as Responder>::Future as IntoFuture>::Future>,
|
||||
req: Option<HttpRequest>,
|
||||
}
|
||||
|
||||
impl<T> Future for AsyncHandlerServiceResponse<T>
|
||||
where
|
||||
T: Future,
|
||||
T::Item: Into<Response>,
|
||||
T::Item: Responder,
|
||||
T::Error: Into<Error>,
|
||||
{
|
||||
type Item = ServiceResponse;
|
||||
type Error = Void;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut2 {
|
||||
return match fut.poll() {
|
||||
Ok(Async::Ready(res)) => Ok(Async::Ready(ServiceResponse::new(
|
||||
self.req.take().unwrap(),
|
||||
res,
|
||||
))),
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(e) => {
|
||||
let res: Response = e.into().into();
|
||||
Ok(Async::Ready(ServiceResponse::new(
|
||||
self.req.take().unwrap(),
|
||||
res,
|
||||
)))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
match self.fut.poll() {
|
||||
Ok(Async::Ready(res)) => Ok(Async::Ready(ServiceResponse::new(
|
||||
self.req.take().unwrap(),
|
||||
res.into(),
|
||||
))),
|
||||
Ok(Async::Ready(res)) => {
|
||||
self.fut2 =
|
||||
Some(res.respond_to(self.req.as_ref().unwrap()).into_future());
|
||||
return self.poll();
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(e) => {
|
||||
let res: Response = e.into().into();
|
||||
@@ -357,7 +381,7 @@ macro_rules! factory_tuple ({ $(($n:tt, $T:ident)),+} => {
|
||||
impl<Func, $($T,)+ Res> AsyncFactory<($($T,)+), Res> for Func
|
||||
where Func: Fn($($T,)+) -> Res + Clone + 'static,
|
||||
Res: IntoFuture,
|
||||
Res::Item: Into<Response>,
|
||||
Res::Item: Responder,
|
||||
Res::Error: Into<Error>,
|
||||
{
|
||||
fn call(&self, param: ($($T,)+)) -> Res {
|
||||
|
10
src/info.rs
10
src/info.rs
@@ -30,7 +30,7 @@ impl ConnectionInfo {
|
||||
let mut host = None;
|
||||
let mut scheme = None;
|
||||
let mut remote = None;
|
||||
let peer = None;
|
||||
let mut peer = None;
|
||||
|
||||
// load forwarded header
|
||||
for hdr in req.headers.get_all(&header::FORWARDED) {
|
||||
@@ -116,10 +116,10 @@ impl ConnectionInfo {
|
||||
remote = h.split(',').next().map(|v| v.trim());
|
||||
}
|
||||
}
|
||||
// if remote.is_none() {
|
||||
// get peeraddr from socketaddr
|
||||
// peer = req.peer_addr().map(|addr| format!("{}", addr));
|
||||
// }
|
||||
if remote.is_none() {
|
||||
// get peeraddr from socketaddr
|
||||
peer = req.peer_addr.map(|addr| format!("{}", addr));
|
||||
}
|
||||
}
|
||||
|
||||
ConnectionInfo {
|
||||
|
@@ -133,7 +133,7 @@ pub mod dev {
|
||||
//! use actix_web::dev::*;
|
||||
//! ```
|
||||
|
||||
pub use crate::config::{AppConfig, ServiceConfig};
|
||||
pub use crate::config::{AppConfig, AppService};
|
||||
pub use crate::info::ConnectionInfo;
|
||||
pub use crate::rmap::ResourceMap;
|
||||
pub use crate::service::{HttpServiceFactory, ServiceRequest, ServiceResponse};
|
||||
|
@@ -848,7 +848,18 @@ mod tests {
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default() {
|
||||
let mut cors =
|
||||
block_on(Cors::default().new_transform(test::ok_service())).unwrap();
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
@@ -868,7 +879,7 @@ mod tests {
|
||||
|
||||
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
||||
assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
@@ -888,7 +899,7 @@ mod tests {
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"*"[..],
|
||||
resp.headers()
|
||||
@@ -934,7 +945,7 @@ mod tests {
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
@@ -973,7 +984,7 @@ mod tests {
|
||||
.method(Method::GET)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
@@ -982,7 +993,7 @@ mod tests {
|
||||
let mut cors = Cors::new().disable_preflight().finish(test::ok_service());
|
||||
|
||||
let req = TestRequest::default().method(Method::GET).to_srv_request();
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert!(resp
|
||||
.headers()
|
||||
.get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
|
||||
@@ -991,7 +1002,7 @@ mod tests {
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"https://www.example.com"[..],
|
||||
resp.headers()
|
||||
@@ -1018,7 +1029,7 @@ mod tests {
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"*"[..],
|
||||
resp.headers()
|
||||
@@ -1064,7 +1075,7 @@ mod tests {
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"Accept, Origin"[..],
|
||||
resp.headers().get(header::VARY).unwrap().as_bytes()
|
||||
@@ -1080,7 +1091,7 @@ mod tests {
|
||||
.method(Method::OPTIONS)
|
||||
.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
|
||||
.to_srv_request();
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
|
||||
let origins_str = resp
|
||||
.headers()
|
||||
@@ -1104,7 +1115,7 @@ mod tests {
|
||||
.method(Method::GET)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"https://example.com"[..],
|
||||
resp.headers()
|
||||
@@ -1117,7 +1128,7 @@ mod tests {
|
||||
.method(Method::GET)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"https://example.org"[..],
|
||||
resp.headers()
|
||||
@@ -1140,7 +1151,7 @@ mod tests {
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"https://example.com"[..],
|
||||
resp.headers()
|
||||
@@ -1154,7 +1165,7 @@ mod tests {
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
|
||||
let resp = test::call_success(&mut cors, req);
|
||||
let resp = test::call_service(&mut cors, req);
|
||||
assert_eq!(
|
||||
&b"https://example.org"[..],
|
||||
resp.headers()
|
||||
|
@@ -172,7 +172,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let resp = test::call_success(&mut mw, TestRequest::default().to_srv_request());
|
||||
let resp = test::call_service(&mut mw, TestRequest::default().to_srv_request());
|
||||
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let resp = test::call_success(&mut mw, TestRequest::default().to_srv_request());
|
||||
let resp = test::call_service(&mut mw, TestRequest::default().to_srv_request());
|
||||
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
|
||||
}
|
||||
}
|
||||
|
@@ -427,8 +427,13 @@ impl CookieIdentityPolicy {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the `max-age` field in the session cookie being built.
|
||||
pub fn max_age(mut self, value: Duration) -> CookieIdentityPolicy {
|
||||
/// Sets the `max-age` field in the session cookie being built with given number of seconds.
|
||||
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);
|
||||
self
|
||||
}
|
||||
@@ -500,15 +505,15 @@ mod tests {
|
||||
})),
|
||||
);
|
||||
let resp =
|
||||
test::call_success(&mut srv, TestRequest::with_uri("/index").to_request());
|
||||
test::call_service(&mut srv, TestRequest::with_uri("/index").to_request());
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let resp =
|
||||
test::call_success(&mut srv, TestRequest::with_uri("/login").to_request());
|
||||
test::call_service(&mut srv, TestRequest::with_uri("/login").to_request());
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let c = resp.response().cookies().next().unwrap().to_owned();
|
||||
|
||||
let resp = test::call_success(
|
||||
let resp = test::call_service(
|
||||
&mut srv,
|
||||
TestRequest::with_uri("/index")
|
||||
.cookie(c.clone())
|
||||
@@ -516,7 +521,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
|
||||
let resp = test::call_success(
|
||||
let resp = test::call_service(
|
||||
&mut srv,
|
||||
TestRequest::with_uri("/logout")
|
||||
.cookie(c.clone())
|
||||
@@ -525,4 +530,56 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
@@ -363,13 +363,6 @@ impl FormatText {
|
||||
let rt = (rt.num_nanoseconds().unwrap_or(0) as f64) / 1_000_000.0;
|
||||
fmt.write_fmt(format_args!("{:.6}", rt))
|
||||
}
|
||||
// FormatText::RemoteAddr => {
|
||||
// if let Some(remote) = req.connection_info().remote() {
|
||||
// return remote.fmt(fmt);
|
||||
// } else {
|
||||
// "-".fmt(fmt)
|
||||
// }
|
||||
// }
|
||||
FormatText::EnvironHeader(ref name) => {
|
||||
if let Ok(val) = env::var(name) {
|
||||
fmt.write_fmt(format_args!("{}", val))
|
||||
@@ -441,6 +434,14 @@ impl FormatText {
|
||||
};
|
||||
*self = FormatText::Str(s.to_string());
|
||||
}
|
||||
FormatText::RemoteAddr => {
|
||||
let s = if let Some(remote) = req.connection_info().remote() {
|
||||
FormatText::Str(remote.to_string())
|
||||
} else {
|
||||
FormatText::Str("-".to_string())
|
||||
};
|
||||
*self = s;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
@@ -6,9 +6,11 @@ pub mod cors;
|
||||
mod defaultheaders;
|
||||
pub mod errhandlers;
|
||||
mod logger;
|
||||
mod normalize;
|
||||
|
||||
pub use self::defaultheaders::DefaultHeaders;
|
||||
pub use self::logger::Logger;
|
||||
pub use self::normalize::NormalizePath;
|
||||
|
||||
#[cfg(feature = "secure-cookies")]
|
||||
pub mod identity;
|
||||
|
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());
|
||||
}
|
||||
|
||||
}
|
@@ -1,6 +1,6 @@
|
||||
use std::cell::{Ref, RefCell, RefMut};
|
||||
use std::fmt;
|
||||
use std::rc::Rc;
|
||||
use std::{fmt, net};
|
||||
|
||||
use actix_http::http::{HeaderMap, Method, Uri, Version};
|
||||
use actix_http::{Error, Extensions, HttpMessage, Message, Payload, RequestHead};
|
||||
@@ -170,6 +170,17 @@ impl HttpRequest {
|
||||
self.url_for(name, &NO_PARAMS)
|
||||
}
|
||||
|
||||
/// Peer socket address
|
||||
///
|
||||
/// Peer address is actual socket address, if proxy is used in front of
|
||||
/// actix http server, then peer address would be address of this proxy.
|
||||
///
|
||||
/// To get client connection information `.connection_info()` should be used.
|
||||
#[inline]
|
||||
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.head().peer_addr
|
||||
}
|
||||
|
||||
/// Get *ConnectionInfo* for the current request.
|
||||
#[inline]
|
||||
pub fn connection_info(&self) -> Ref<ConnectionInfo> {
|
||||
@@ -324,7 +335,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::dev::{ResourceDef, ResourceMap};
|
||||
use crate::http::{header, StatusCode};
|
||||
use crate::test::{call_success, init_service, TestRequest};
|
||||
use crate::test::{call_service, init_service, TestRequest};
|
||||
use crate::{web, App, HttpResponse};
|
||||
|
||||
#[test]
|
||||
@@ -453,7 +464,7 @@ mod tests {
|
||||
));
|
||||
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let mut srv = init_service(App::new().data(10u32).service(
|
||||
@@ -467,7 +478,7 @@ mod tests {
|
||||
));
|
||||
|
||||
let req = TestRequest::default().to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
@@ -10,7 +10,7 @@ use actix_service::{
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
use crate::dev::{insert_slash, HttpServiceFactory, ResourceDef, ServiceConfig};
|
||||
use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef};
|
||||
use crate::extract::FromRequest;
|
||||
use crate::guard::Guard;
|
||||
use crate::handler::{AsyncFactory, Factory};
|
||||
@@ -217,7 +217,7 @@ where
|
||||
F: AsyncFactory<I, R>,
|
||||
I: FromRequest + 'static,
|
||||
R: IntoFuture + 'static,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
self.routes.push(Route::new().to_async(handler));
|
||||
@@ -347,7 +347,7 @@ where
|
||||
InitError = (),
|
||||
> + 'static,
|
||||
{
|
||||
fn register(mut self, config: &mut ServiceConfig) {
|
||||
fn register(mut self, config: &mut AppService) {
|
||||
let guards = if self.guards.is_empty() {
|
||||
None
|
||||
} else {
|
||||
@@ -545,7 +545,7 @@ mod tests {
|
||||
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::test::{call_success, init_service, TestRequest};
|
||||
use crate::test::{call_service, init_service, TestRequest};
|
||||
use crate::{web, App, Error, HttpResponse};
|
||||
|
||||
fn md<S, B>(
|
||||
@@ -577,7 +577,7 @@ mod tests {
|
||||
),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
@@ -603,7 +603,7 @@ mod tests {
|
||||
),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
@@ -618,7 +618,7 @@ mod tests {
|
||||
sleep(Duration::from_millis(100)).then(|_| HttpResponse::Ok())
|
||||
})));
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
@@ -634,13 +634,13 @@ mod tests {
|
||||
}),
|
||||
);
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::POST)
|
||||
.to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
|
||||
let mut srv = init_service(
|
||||
@@ -654,13 +654,13 @@ mod tests {
|
||||
);
|
||||
|
||||
let req = TestRequest::with_uri("/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::POST)
|
||||
.to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
@@ -307,11 +307,11 @@ pub(crate) mod tests {
|
||||
);
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
match resp.response().body() {
|
||||
ResponseBody::Body(Body::Bytes(ref b)) => {
|
||||
|
47
src/route.rs
47
src/route.rs
@@ -1,7 +1,7 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::{http::Method, Error, Extensions, Response};
|
||||
use actix_http::{http::Method, Error, Extensions};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
@@ -278,7 +278,7 @@ impl Route {
|
||||
F: AsyncFactory<T, R>,
|
||||
T: FromRequest + 'static,
|
||||
R: IntoFuture + 'static,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
self.service = Box::new(RouteNewService::new(Extract::new(
|
||||
@@ -418,18 +418,25 @@ where
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::Future;
|
||||
use serde_derive::Serialize;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use crate::http::{Method, StatusCode};
|
||||
use crate::test::{call_success, init_service, TestRequest};
|
||||
use crate::test::{call_service, init_service, read_body, TestRequest};
|
||||
use crate::{error, web, App, HttpResponse};
|
||||
|
||||
#[derive(Serialize, PartialEq, Debug)]
|
||||
struct MyObject {
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_route() {
|
||||
let mut srv =
|
||||
init_service(
|
||||
App::new().service(
|
||||
let mut srv = init_service(
|
||||
App::new()
|
||||
.service(
|
||||
web::resource("/test")
|
||||
.route(web::get().to(|| HttpResponse::Ok()))
|
||||
.route(web::put().to(|| {
|
||||
@@ -444,37 +451,51 @@ mod tests {
|
||||
Err::<HttpResponse, _>(error::ErrorBadRequest("err"))
|
||||
})
|
||||
})),
|
||||
),
|
||||
);
|
||||
)
|
||||
.service(web::resource("/json").route(web::get().to_async(|| {
|
||||
sleep(Duration::from_millis(25)).then(|_| {
|
||||
Ok::<_, crate::Error>(web::Json(MyObject {
|
||||
name: "test".to_string(),
|
||||
}))
|
||||
})
|
||||
}))),
|
||||
);
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::GET)
|
||||
.to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::POST)
|
||||
.to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::PUT)
|
||||
.to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::DELETE)
|
||||
.to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
let req = TestRequest::with_uri("/test")
|
||||
.method(Method::HEAD)
|
||||
.to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
|
||||
let req = TestRequest::with_uri("/json").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let body = read_body(resp);
|
||||
assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}"));
|
||||
}
|
||||
}
|
||||
|
10
src/scope.rs
10
src/scope.rs
@@ -11,7 +11,7 @@ use actix_service::{
|
||||
use futures::future::{ok, Either, Future, FutureResult};
|
||||
use futures::{Async, IntoFuture, Poll};
|
||||
|
||||
use crate::dev::{HttpServiceFactory, ServiceConfig};
|
||||
use crate::dev::{AppService, HttpServiceFactory};
|
||||
use crate::error::Error;
|
||||
use crate::guard::Guard;
|
||||
use crate::resource::Resource;
|
||||
@@ -303,7 +303,7 @@ where
|
||||
InitError = (),
|
||||
> + 'static,
|
||||
{
|
||||
fn register(self, config: &mut ServiceConfig) {
|
||||
fn register(self, config: &mut AppService) {
|
||||
// update default resource if needed
|
||||
if self.default.borrow().is_none() {
|
||||
*self.default.borrow_mut() = Some(config.default_service());
|
||||
@@ -535,7 +535,7 @@ mod tests {
|
||||
use crate::dev::{Body, ResponseBody};
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::test::{block_on, call_success, init_service, TestRequest};
|
||||
use crate::test::{block_on, call_service, init_service, TestRequest};
|
||||
use crate::{guard, web, App, Error, HttpRequest, HttpResponse};
|
||||
|
||||
#[test]
|
||||
@@ -912,7 +912,7 @@ mod tests {
|
||||
web::resource("/test").route(web::get().to(|| HttpResponse::Ok())),
|
||||
)));
|
||||
let req = TestRequest::with_uri("/app/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
@@ -938,7 +938,7 @@ mod tests {
|
||||
),
|
||||
);
|
||||
let req = TestRequest::with_uri("/app/test").to_request();
|
||||
let resp = call_success(&mut srv, req);
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
|
@@ -1,5 +1,5 @@
|
||||
use std::cell::{Ref, RefMut};
|
||||
use std::fmt;
|
||||
use std::{fmt, net};
|
||||
|
||||
use actix_http::body::{Body, MessageBody, ResponseBody};
|
||||
use actix_http::http::{HeaderMap, Method, StatusCode, Uri, Version};
|
||||
@@ -10,16 +10,17 @@ use actix_http::{
|
||||
use actix_router::{Path, Resource, Url};
|
||||
use futures::future::{ok, FutureResult, IntoFuture};
|
||||
|
||||
use crate::config::{AppConfig, ServiceConfig};
|
||||
use crate::config::{AppConfig, AppService};
|
||||
use crate::data::Data;
|
||||
use crate::info::ConnectionInfo;
|
||||
use crate::request::HttpRequest;
|
||||
|
||||
pub trait HttpServiceFactory {
|
||||
fn register(self, config: &mut ServiceConfig);
|
||||
fn register(self, config: &mut AppService);
|
||||
}
|
||||
|
||||
pub(crate) trait ServiceFactory {
|
||||
fn register(&mut self, config: &mut ServiceConfig);
|
||||
fn register(&mut self, config: &mut AppService);
|
||||
}
|
||||
|
||||
pub(crate) struct ServiceFactoryWrapper<T> {
|
||||
@@ -38,7 +39,7 @@ impl<T> ServiceFactory for ServiceFactoryWrapper<T>
|
||||
where
|
||||
T: HttpServiceFactory,
|
||||
{
|
||||
fn register(&mut self, config: &mut ServiceConfig) {
|
||||
fn register(&mut self, config: &mut AppService) {
|
||||
if let Some(item) = self.factory.take() {
|
||||
item.register(config)
|
||||
}
|
||||
@@ -52,7 +53,7 @@ pub struct ServiceRequest {
|
||||
|
||||
impl ServiceRequest {
|
||||
/// 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 }
|
||||
}
|
||||
|
||||
@@ -134,6 +135,23 @@ impl ServiceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
/// Peer socket address
|
||||
///
|
||||
/// Peer address is actual socket address, if proxy is used in front of
|
||||
/// actix http server, then peer address would be address of this proxy.
|
||||
///
|
||||
/// To get client connection information `ConnectionInfo` should be used.
|
||||
#[inline]
|
||||
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.head().peer_addr
|
||||
}
|
||||
|
||||
/// Get *ConnectionInfo* for the current request.
|
||||
#[inline]
|
||||
pub fn connection_info(&self) -> Ref<ConnectionInfo> {
|
||||
ConnectionInfo::get(self.head(), &*self.app_config())
|
||||
}
|
||||
|
||||
/// Get a reference to the Path parameters.
|
||||
///
|
||||
/// Params is a container for url parameters.
|
||||
|
320
src/test.rs
320
src/test.rs
@@ -4,21 +4,26 @@ use std::rc::Rc;
|
||||
|
||||
use actix_http::cookie::Cookie;
|
||||
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
|
||||
use actix_http::http::{HttpTryFrom, Method, StatusCode, Version};
|
||||
use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
|
||||
use actix_http::test::TestRequest as HttpTestRequest;
|
||||
use actix_http::{Extensions, Request};
|
||||
use actix_router::{Path, ResourceDef, Url};
|
||||
use actix_rt::Runtime;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{FnService, IntoNewService, NewService, Service};
|
||||
use bytes::Bytes;
|
||||
use futures::future::{lazy, Future};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::{
|
||||
future::{lazy, ok, Future},
|
||||
stream::Stream,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json;
|
||||
|
||||
pub use actix_http::test::TestBuffer;
|
||||
|
||||
use crate::config::{AppConfig, AppConfigInner};
|
||||
use crate::data::RouteData;
|
||||
use crate::dev::{Body, Payload};
|
||||
use crate::data::{Data, RouteData};
|
||||
use crate::dev::{Body, MessageBody, Payload};
|
||||
use crate::request::HttpRequestPool;
|
||||
use crate::rmap::ResourceMap;
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
@@ -53,7 +58,7 @@ where
|
||||
/// This function panics on nested call.
|
||||
pub fn run_on<F, R>(f: F) -> R
|
||||
where
|
||||
F: Fn() -> R,
|
||||
F: FnOnce() -> R,
|
||||
{
|
||||
RT.with(move |rt| rt.borrow_mut().block_on(lazy(|| Ok::<_, ()>(f()))))
|
||||
.unwrap()
|
||||
@@ -79,11 +84,12 @@ pub fn default_service(
|
||||
/// This method accepts application builder instance, and constructs
|
||||
/// service.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// ```rust
|
||||
/// use actix_service::Service;
|
||||
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
|
||||
///
|
||||
/// fn main() {
|
||||
/// #[test]
|
||||
/// fn test_init_service() {
|
||||
/// let mut app = test::init_service(
|
||||
/// App::new()
|
||||
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
|
||||
@@ -111,16 +117,19 @@ where
|
||||
S::InitError: std::fmt::Debug,
|
||||
{
|
||||
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.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// ```rust
|
||||
/// use actix_web::{test, App, HttpResponse, http::StatusCode};
|
||||
/// use actix_service::Service;
|
||||
///
|
||||
/// fn main() {
|
||||
/// #[test]
|
||||
/// fn test_response() {
|
||||
/// let mut app = test::init_service(
|
||||
/// App::new()
|
||||
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
|
||||
@@ -130,16 +139,155 @@ where
|
||||
/// let req = test::TestRequest::with_uri("/test").to_request();
|
||||
///
|
||||
/// // Call application
|
||||
/// let resp = test::call_success(&mut app, req);
|
||||
/// let resp = test::call_service(&mut app, req);
|
||||
/// assert_eq!(resp.status(), StatusCode::OK);
|
||||
/// }
|
||||
/// ```
|
||||
pub fn call_success<S, R, B, E>(app: &mut S, req: R) -> S::Response
|
||||
pub fn call_service<S, R, B, E>(app: &mut S, req: R) -> S::Response
|
||||
where
|
||||
S: Service<Request = R, Response = ServiceResponse<B>, Error = E>,
|
||||
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
|
||||
/// This function blocks the current thread until futures complete.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::{test, web, App, HttpResponse, http::header};
|
||||
/// use bytes::Bytes;
|
||||
///
|
||||
/// #[test]
|
||||
/// fn test_index() {
|
||||
/// let mut app = test::init_service(
|
||||
/// App::new().service(
|
||||
/// web::resource("/index.html")
|
||||
/// .route(web::post().to(
|
||||
/// || HttpResponse::Ok().body("welcome!")))));
|
||||
///
|
||||
/// let req = test::TestRequest::post()
|
||||
/// .uri("/index.html")
|
||||
/// .header(header::CONTENT_TYPE, "application/json")
|
||||
/// .to_request();
|
||||
///
|
||||
/// let result = test::read_response(&mut app, req);
|
||||
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
||||
/// }
|
||||
/// ```
|
||||
pub fn read_response<S, B>(app: &mut S, req: Request) -> Bytes
|
||||
where
|
||||
S: Service<Request = Request, Response = ServiceResponse<B>, Error = Error>,
|
||||
B: MessageBody,
|
||||
{
|
||||
block_on(run_on(move || {
|
||||
app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
||||
resp.take_body()
|
||||
.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, Error>(body)
|
||||
})
|
||||
.map(|body: BytesMut| body.freeze())
|
||||
})
|
||||
}))
|
||||
.unwrap_or_else(|_| panic!("read_response failed at block_on unwrap"))
|
||||
}
|
||||
|
||||
/// Helper function that returns a response body of a ServiceResponse.
|
||||
/// This function blocks the current thread until futures complete.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::{test, web, App, HttpResponse, http::header};
|
||||
/// use bytes::Bytes;
|
||||
///
|
||||
/// #[test]
|
||||
/// fn test_index() {
|
||||
/// let mut app = test::init_service(
|
||||
/// App::new().service(
|
||||
/// web::resource("/index.html")
|
||||
/// .route(web::post().to(
|
||||
/// || HttpResponse::Ok().body("welcome!")))));
|
||||
///
|
||||
/// let req = test::TestRequest::post()
|
||||
/// .uri("/index.html")
|
||||
/// .header(header::CONTENT_TYPE, "application/json")
|
||||
/// .to_request();
|
||||
///
|
||||
/// let resp = call_service(&mut srv, req);
|
||||
/// let result = test::read_body(resp);
|
||||
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
||||
/// }
|
||||
/// ```
|
||||
pub fn read_body<B>(mut res: ServiceResponse<B>) -> Bytes
|
||||
where
|
||||
B: MessageBody,
|
||||
{
|
||||
block_on(run_on(move || {
|
||||
res.take_body()
|
||||
.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, Error>(body)
|
||||
})
|
||||
.map(|body: BytesMut| body.freeze())
|
||||
}))
|
||||
.unwrap_or_else(|_| panic!("read_response failed at block_on unwrap"))
|
||||
}
|
||||
|
||||
/// Helper function that returns a deserialized response body of a TestRequest
|
||||
/// This function blocks the current thread until futures complete.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::{App, test, web, HttpResponse, http::header};
|
||||
/// use serde::{Serialize, Deserialize};
|
||||
///
|
||||
/// #[derive(Serialize, Deserialize)]
|
||||
/// pub struct Person {
|
||||
/// id: String,
|
||||
/// name: String
|
||||
/// }
|
||||
///
|
||||
/// #[test]
|
||||
/// fn test_add_person() {
|
||||
/// let mut app = test::init_service(
|
||||
/// App::new().service(
|
||||
/// web::resource("/people")
|
||||
/// .route(web::post().to(|person: web::Json<Person>| {
|
||||
/// HttpResponse::Ok()
|
||||
/// .json(person.into_inner())})
|
||||
/// )));
|
||||
///
|
||||
/// let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
||||
///
|
||||
/// let req = test::TestRequest::post()
|
||||
/// .uri("/people")
|
||||
/// .header(header::CONTENT_TYPE, "application/json")
|
||||
/// .set_payload(payload)
|
||||
/// .to_request();
|
||||
///
|
||||
/// let result: Person = test::read_response_json(&mut app, req);
|
||||
/// }
|
||||
/// ```
|
||||
pub fn read_response_json<S, B, T>(app: &mut S, req: Request) -> T
|
||||
where
|
||||
S: Service<Request = Request, Response = ServiceResponse<B>, Error = Error>,
|
||||
B: MessageBody,
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
block_on(run_on(move || {
|
||||
app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
||||
resp.take_body()
|
||||
.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, Error>(body)
|
||||
})
|
||||
.and_then(|body: BytesMut| {
|
||||
ok(serde_json::from_slice(&body).unwrap_or_else(|_| {
|
||||
panic!("read_response_json failed during deserialization")
|
||||
}))
|
||||
})
|
||||
})
|
||||
}))
|
||||
.unwrap_or_else(|_| panic!("read_response_json failed at block_on unwrap"))
|
||||
}
|
||||
|
||||
/// Test `Request` builder.
|
||||
@@ -151,7 +299,7 @@ where
|
||||
/// * `TestRequest::to_from` creates `ServiceFromRequest` instance, which is used for testing extractors.
|
||||
/// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// ```rust
|
||||
/// # use futures::IntoFuture;
|
||||
/// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage};
|
||||
/// use actix_web::http::{header, StatusCode};
|
||||
@@ -164,7 +312,8 @@ where
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// #[test]
|
||||
/// fn test_index() {
|
||||
/// let req = test::TestRequest::with_header("content-type", "text/plain")
|
||||
/// .to_http_request();
|
||||
///
|
||||
@@ -181,6 +330,7 @@ pub struct TestRequest {
|
||||
rmap: ResourceMap,
|
||||
config: AppConfigInner,
|
||||
route_data: Extensions,
|
||||
path: Path<Url>,
|
||||
}
|
||||
|
||||
impl Default for TestRequest {
|
||||
@@ -190,6 +340,7 @@ impl Default for TestRequest {
|
||||
rmap: ResourceMap::new(ResourceDef::new("")),
|
||||
config: AppConfigInner::default(),
|
||||
route_data: Extensions::new(),
|
||||
path: Path::new(Url::new(Uri::default())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -225,6 +376,16 @@ impl TestRequest {
|
||||
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
|
||||
pub fn version(mut self, ver: Version) -> Self {
|
||||
self.req.version(ver);
|
||||
@@ -265,6 +426,12 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set request path pattern parameter
|
||||
pub fn param(mut self, name: &'static str, value: &'static str) -> Self {
|
||||
self.path.add_static(name, value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set request payload
|
||||
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
|
||||
self.req.set_payload(data);
|
||||
@@ -274,7 +441,7 @@ impl TestRequest {
|
||||
/// Set application data. This is equivalent of `App::data()` method
|
||||
/// for testing purpose.
|
||||
pub fn app_data<T: 'static>(self, data: T) -> Self {
|
||||
self.config.extensions.borrow_mut().insert(data);
|
||||
self.config.extensions.borrow_mut().insert(Data::new(data));
|
||||
self
|
||||
}
|
||||
|
||||
@@ -300,9 +467,10 @@ impl TestRequest {
|
||||
/// Complete request creation and generate `ServiceRequest` instance
|
||||
pub fn to_srv_request(mut self) -> ServiceRequest {
|
||||
let (head, payload) = self.req.finish().into_parts();
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
let req = HttpRequest::new(
|
||||
Path::new(Url::new(head.uri.clone())),
|
||||
self.path,
|
||||
head,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
@@ -320,9 +488,10 @@ impl TestRequest {
|
||||
/// Complete request creation and generate `HttpRequest` instance
|
||||
pub fn to_http_request(mut self) -> HttpRequest {
|
||||
let (head, _) = self.req.finish().into_parts();
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
let mut req = HttpRequest::new(
|
||||
Path::new(Url::new(head.uri.clone())),
|
||||
self.path,
|
||||
head,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
@@ -335,9 +504,10 @@ impl TestRequest {
|
||||
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
||||
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
||||
let (head, payload) = self.req.finish().into_parts();
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
let mut req = HttpRequest::new(
|
||||
Path::new(Url::new(head.uri.clone())),
|
||||
self.path,
|
||||
head,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
@@ -346,21 +516,101 @@ impl TestRequest {
|
||||
req.set_route_data(Some(Rc::new(self.route_data)));
|
||||
(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)]
|
||||
mod tests {
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use super::*;
|
||||
use crate::{http::header, web, App, HttpResponse};
|
||||
|
||||
#[test]
|
||||
fn test_basics() {
|
||||
let req = TestRequest::with_hdr(header::ContentType::json())
|
||||
.version(Version::HTTP_2)
|
||||
.set(header::Date(SystemTime::now().into()))
|
||||
.param("test", "123")
|
||||
.app_data(10u32)
|
||||
.to_http_request();
|
||||
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
||||
assert!(req.headers().contains_key(header::DATE));
|
||||
assert_eq!(&req.match_info()["test"], "123");
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
let data = req.app_data::<u32>().unwrap();
|
||||
assert_eq!(*data, 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]
|
||||
fn test_response() {
|
||||
let mut app = init_service(
|
||||
App::new().service(
|
||||
web::resource("/index.html")
|
||||
.route(web::post().to(|| HttpResponse::Ok().body("welcome!"))),
|
||||
),
|
||||
);
|
||||
|
||||
let req = TestRequest::post()
|
||||
.uri("/index.html")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.to_request();
|
||||
|
||||
let result = read_response(&mut app, req);
|
||||
assert_eq!(result, Bytes::from_static(b"welcome!"));
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Person {
|
||||
id: String,
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_response_json() {
|
||||
let mut app = init_service(App::new().service(web::resource("/people").route(
|
||||
web::post().to(|person: web::Json<Person>| {
|
||||
HttpResponse::Ok().json(person.into_inner())
|
||||
}),
|
||||
)));
|
||||
|
||||
let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
||||
|
||||
let req = TestRequest::post()
|
||||
.uri("/people")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.set_payload(payload)
|
||||
.to_request();
|
||||
|
||||
let result: Person = read_response_json(&mut app, req);
|
||||
assert_eq!(&result.id, "12345");
|
||||
}
|
||||
}
|
||||
|
@@ -331,10 +331,6 @@ mod tests {
|
||||
|
||||
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
|
||||
match err {
|
||||
UrlencodedError::Chunked => match other {
|
||||
UrlencodedError::Chunked => true,
|
||||
_ => false,
|
||||
},
|
||||
UrlencodedError::Overflow => match other {
|
||||
UrlencodedError::Overflow => true,
|
||||
_ => false,
|
||||
|
@@ -171,10 +171,25 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_router::ResourceDef;
|
||||
use derive_more::Display;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use super::*;
|
||||
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]
|
||||
fn test_extract_path_single() {
|
||||
let resource = ResourceDef::new("/{value}/");
|
||||
@@ -184,6 +199,7 @@ mod tests {
|
||||
|
||||
let (req, mut pl) = req.into_parts();
|
||||
assert_eq!(*Path::<i8>::from_request(&req, &mut pl).unwrap(), 32);
|
||||
assert!(Path::<MyStruct>::from_request(&req, &mut pl).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -213,4 +229,46 @@ mod tests {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
18
src/web.rs
18
src/web.rs
@@ -1,5 +1,5 @@
|
||||
//! Essentials helper functions and types for application registration.
|
||||
use actix_http::{http::Method, Response};
|
||||
use actix_http::http::Method;
|
||||
use futures::{Future, IntoFuture};
|
||||
|
||||
pub use actix_http::Response as HttpResponse;
|
||||
@@ -13,7 +13,7 @@ use crate::responder::Responder;
|
||||
use crate::route::Route;
|
||||
use crate::scope::Scope;
|
||||
|
||||
pub use crate::config::RouterConfig;
|
||||
pub use crate::config::ServiceConfig;
|
||||
pub use crate::data::{Data, RouteData};
|
||||
pub use crate::request::HttpRequest;
|
||||
pub use crate::types::*;
|
||||
@@ -103,7 +103,7 @@ pub fn route() -> Route {
|
||||
/// * /{project_id}
|
||||
///
|
||||
pub fn get() -> Route {
|
||||
Route::new().method(Method::GET)
|
||||
method(Method::GET)
|
||||
}
|
||||
|
||||
/// Create *route* with `POST` method guard.
|
||||
@@ -123,7 +123,7 @@ pub fn get() -> Route {
|
||||
/// * /{project_id}
|
||||
///
|
||||
pub fn post() -> Route {
|
||||
Route::new().method(Method::POST)
|
||||
method(Method::POST)
|
||||
}
|
||||
|
||||
/// Create *route* with `PUT` method guard.
|
||||
@@ -143,7 +143,7 @@ pub fn post() -> Route {
|
||||
/// * /{project_id}
|
||||
///
|
||||
pub fn put() -> Route {
|
||||
Route::new().method(Method::PUT)
|
||||
method(Method::PUT)
|
||||
}
|
||||
|
||||
/// Create *route* with `PATCH` method guard.
|
||||
@@ -163,7 +163,7 @@ pub fn put() -> Route {
|
||||
/// * /{project_id}
|
||||
///
|
||||
pub fn patch() -> Route {
|
||||
Route::new().method(Method::PATCH)
|
||||
method(Method::PATCH)
|
||||
}
|
||||
|
||||
/// Create *route* with `DELETE` method guard.
|
||||
@@ -183,7 +183,7 @@ pub fn patch() -> Route {
|
||||
/// * /{project_id}
|
||||
///
|
||||
pub fn delete() -> Route {
|
||||
Route::new().method(Method::DELETE)
|
||||
method(Method::DELETE)
|
||||
}
|
||||
|
||||
/// Create *route* with `HEAD` method guard.
|
||||
@@ -203,7 +203,7 @@ pub fn delete() -> Route {
|
||||
/// * /{project_id}
|
||||
///
|
||||
pub fn head() -> Route {
|
||||
Route::new().method(Method::HEAD)
|
||||
method(Method::HEAD)
|
||||
}
|
||||
|
||||
/// Create *route* and add method guard.
|
||||
@@ -268,7 +268,7 @@ where
|
||||
F: AsyncFactory<I, R>,
|
||||
I: FromRequest + 'static,
|
||||
R: IntoFuture + 'static,
|
||||
R::Item: Into<Response>,
|
||||
R::Item: Responder,
|
||||
R::Error: Into<Error>,
|
||||
{
|
||||
Route::new().to_async(handler)
|
||||
|
@@ -1,5 +1,15 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2019-04-24
|
||||
|
||||
* Always make new connection for http client
|
||||
|
||||
|
||||
## [0.1.0] - 2019-04-16
|
||||
|
||||
* No changes
|
||||
|
||||
|
||||
## [0.1.0-alpha.3] - 2019-04-02
|
||||
|
||||
* Request functions accept path #743
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http-test"
|
||||
version = "0.1.0-alpha.3"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http test server"
|
||||
readme = "README.md"
|
||||
@@ -33,9 +33,9 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
actix-codec = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-server = "0.4.1"
|
||||
actix-server = "0.4.3"
|
||||
actix-utils = "0.3.5"
|
||||
awc = "0.1.0-alpha.5"
|
||||
awc = "0.1.1"
|
||||
|
||||
base64 = "0.10"
|
||||
bytes = "0.4"
|
||||
@@ -55,5 +55,5 @@ tokio-timer = "0.2"
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = "1.0.0-alpha.5"
|
||||
actix-http = "0.1.0-alpha.5"
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-http = "0.1.2"
|
||||
|
@@ -124,6 +124,7 @@ impl TestServer {
|
||||
|e| log::error!("Can not set alpn protocol: {:?}", e),
|
||||
);
|
||||
Connector::new()
|
||||
.conn_lifetime(time::Duration::from_secs(0))
|
||||
.timeout(time::Duration::from_millis(500))
|
||||
.ssl(builder.build())
|
||||
.finish()
|
||||
@@ -131,6 +132,7 @@ impl TestServer {
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
{
|
||||
Connector::new()
|
||||
.conn_lifetime(time::Duration::from_secs(0))
|
||||
.timeout(time::Duration::from_millis(500))
|
||||
.finish()
|
||||
}
|
||||
@@ -163,6 +165,15 @@ impl TestServerRuntime {
|
||||
self.rt.block_on(fut)
|
||||
}
|
||||
|
||||
/// Execute future on current core
|
||||
pub fn block_on_fn<F, R>(&mut self, f: F) -> Result<R::Item, R::Error>
|
||||
where
|
||||
F: FnOnce() -> R,
|
||||
R: Future,
|
||||
{
|
||||
self.rt.block_on(lazy(|| f()))
|
||||
}
|
||||
|
||||
/// Execute function on current core
|
||||
pub fn execute<F, R>(&mut self, fut: F) -> R
|
||||
where
|
||||
|
@@ -17,7 +17,7 @@ use futures::stream::once;
|
||||
use rand::{distributions::Alphanumeric, Rng};
|
||||
|
||||
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 \
|
||||
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()));
|
||||
}
|
||||
|
||||
#[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"))]
|
||||
#[test]
|
||||
fn test_body_encoding_override() {
|
||||
|
Reference in New Issue
Block a user