mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-05 10:25:21 +02:00
Compare commits
215 Commits
http-v0.1.
...
http-v0.2.
Author | SHA1 | Date | |
---|---|---|---|
baaa7b3fbb | |||
32718b7e31 | |||
c01611d8b5 | |||
7b1dcaffda | |||
c65dbaf88e | |||
c45728ac01 | |||
6f71409355 | |||
8d17c8651f | |||
b1143168e5 | |||
69456991f6 | |||
f410f3330f | |||
e1fcd203f8 | |||
0d8a4304a9 | |||
14cc5a5d6b | |||
287c2b1d18 | |||
7596ab69e0 | |||
1fdd77bffa | |||
2d424957fb | |||
dabc4fe00b | |||
5bf5b0acd2 | |||
099a8ff7d8 | |||
a28b7139e6 | |||
a0a469fe85 | |||
dbab55dd6b | |||
d2eb1edac3 | |||
5901dfee1a | |||
0e05b37082 | |||
37f4ce8604 | |||
12b5174850 | |||
b77ed193f7 | |||
d286ccb4f5 | |||
cac162aed7 | |||
a3a78ac6fb | |||
596483ff55 | |||
768859513a | |||
44bb79cd07 | |||
af9fb5d190 | |||
50a9d9e2c5 | |||
c0c71f82c0 | |||
93855b889a | |||
fa7e0fe6df | |||
b948f74b54 | |||
1a24ff8717 | |||
47fab0e393 | |||
313ac48765 | |||
d7780d53c9 | |||
ad0e6f73b3 | |||
546a8a58db | |||
acda1c075a | |||
686e5f1595 | |||
d2b6502c7a | |||
7c0f570845 | |||
382d4ca216 | |||
eaa371db8b | |||
d293ae2a69 | |||
d7ec241fd0 | |||
cd323f2ff1 | |||
32a66a99bf | |||
73ae801a13 | |||
ca4ed0932e | |||
bf48798bce | |||
9fc7c8b1af | |||
c8118e8411 | |||
65732197b8 | |||
959eef05ae | |||
e7ba67e1a8 | |||
13e618b128 | |||
36e6f0cb4b | |||
7450ae37a7 | |||
2ffda29f9b | |||
ff724e239d | |||
ee769832cf | |||
c4b7980b4f | |||
bfbac4f875 | |||
53e2f8090f | |||
e399e01a22 | |||
d9a62c4bbf | |||
a548b69679 | |||
ae64475d98 | |||
a342b1289d | |||
38f04b75a7 | |||
a771540b16 | |||
cf217d35a8 | |||
0e138e111f | |||
1fce4876f3 | |||
4a179d1ae1 | |||
a780ea10e9 | |||
6d2e190c8e | |||
b1cfbdcf7a | |||
24180f9014 | |||
15cdc680f6 | |||
666756bfbe | |||
a1b40f4314 | |||
29a0fe76d5 | |||
7753b9da6d | |||
f1764bba43 | |||
c2d7db7e06 | |||
21418c7414 | |||
fe781345d5 | |||
a614be7cb5 | |||
1eb89b8375 | |||
aa626a1e72 | |||
7f12b754e9 | |||
3f196f469d | |||
35eb378585 | |||
6db625f55b | |||
801cc2ed5d | |||
ded1e86e7e | |||
babf48c550 | |||
d3e807f6e9 | |||
7746e785c1 | |||
4e141d7f5d | |||
12842871fe | |||
fc85ae4014 | |||
5826f39dbe | |||
8ff56d7cd5 | |||
0843bce7ba | |||
dea0e0a721 | |||
e857ab1f81 | |||
0dda4b06ea | |||
cbe0226177 | |||
e8c8626878 | |||
4b215e0839 | |||
e1ff3bf8fa | |||
80f4ef9aac | |||
bba90d7f22 | |||
f8af3b86e5 | |||
6c3d8b8738 | |||
5a90e33bcc | |||
86b569e320 | |||
2350a2dc68 | |||
36d017dcc6 | |||
3bb081852c | |||
1ca58e876b | |||
e9cbcbaf03 | |||
07c9eec803 | |||
beae9ca0f7 | |||
07b9707ca1 | |||
45c05978b0 | |||
df08baf67f | |||
4066375737 | |||
a77b0b054a | |||
a17ff492a1 | |||
33b4c05557 | |||
005c055a7f | |||
3d1af19080 | |||
fa78da8156 | |||
01cfcf3b75 | |||
7ef4f5ac0b | |||
fc19ce41c4 | |||
6e00eef63a | |||
337c2febe3 | |||
f27beab016 | |||
4f1c6d1bb7 | |||
6b34909537 | |||
87284f0951 | |||
24bd5b1344 | |||
94a0d1a6bc | |||
f4e1205cbb | |||
d2c1791067 | |||
f4b4875cb1 | |||
29a841529f | |||
b51b5b763c | |||
8db6b48a76 | |||
ffd2c04cd3 | |||
70a4c36496 | |||
cba78e06ae | |||
3b3dbb4f40 | |||
7300002226 | |||
5426413cb6 | |||
2bc937f6c3 | |||
60fa0d5427 | |||
f429d3319f | |||
2e19f572ee | |||
64f603b076 | |||
679d1cd513 | |||
42644dac3f | |||
898ef57080 | |||
9702b2d88e | |||
d2b0afd859 | |||
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 |
@ -3,7 +3,7 @@ sudo: required
|
|||||||
dist: trusty
|
dist: trusty
|
||||||
|
|
||||||
cache:
|
cache:
|
||||||
cargo: true
|
# cargo: true
|
||||||
apt: true
|
apt: true
|
||||||
|
|
||||||
matrix:
|
matrix:
|
||||||
@ -26,7 +26,7 @@ before_install:
|
|||||||
|
|
||||||
before_cache: |
|
before_cache: |
|
||||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-04-02" ]]; then
|
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-04-02" ]]; then
|
||||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install cargo-tarpaulin
|
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Add clippy
|
# Add clippy
|
||||||
|
169
CHANGES.md
169
CHANGES.md
@ -1,6 +1,167 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## [1.0.0-beta.1] - 2019-04-xx
|
## [1.0.4] - 2019-07-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add `Responder` impl for `(T, StatusCode) where T: Responder`
|
||||||
|
|
||||||
|
* Allow to access app's resource map via
|
||||||
|
`ServiceRequest::resource_map()` and `HttpRequest::resource_map()` methods.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Upgrade `rand` dependency version to 0.7
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.3] - 2019-06-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Support asynchronous data factories #850
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use `encoding_rs` crate instead of unmaintained `encoding` crate
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.2] - 2019-06-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Move cors middleware to `actix-cors` crate.
|
||||||
|
|
||||||
|
* Move identity middleware to `actix-identity` crate.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-06-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add support for PathConfig #903
|
||||||
|
|
||||||
|
* Add `middleware::identity::RequestIdentity` trait to `get_identity` from `HttpMessage`.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Move cors middleware to `actix-cors` crate.
|
||||||
|
|
||||||
|
* Move identity middleware to `actix-identity` crate.
|
||||||
|
|
||||||
|
* Disable default feature `secure-cookies`.
|
||||||
|
|
||||||
|
* Allow to test an app that uses async actors #897
|
||||||
|
|
||||||
|
* Re-apply patch from #637 #894
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* HttpRequest::url_for is broken with nested scopes #915
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add `Scope::configure()` method.
|
||||||
|
|
||||||
|
* Add `ServiceRequest::set_payload()` method.
|
||||||
|
|
||||||
|
* Add `test::TestRequest::set_json()` convenience method to automatically
|
||||||
|
serialize data and set header in test requests.
|
||||||
|
|
||||||
|
* Add macros for head, options, trace, connect and patch http methods
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix Logger request time format, and use rfc3339. #867
|
||||||
|
|
||||||
|
* Clear http requests pool on app service drop #860
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-rc] - 2019-05-18
|
||||||
|
|
||||||
|
### Add
|
||||||
|
|
||||||
|
* Add `Query<T>::from_query()` to extract parameters from a query string. #846
|
||||||
|
* `QueryConfig`, similar to `JsonConfig` for customizing error handling of query extractors.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* `JsonConfig` is now `Send + Sync`, this implies that `error_handler` must be `Send + Sync` too.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Codegen with parameters in the path only resolves the first registered endpoint #841
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-beta.4] - 2019-05-12
|
||||||
|
|
||||||
|
### Add
|
||||||
|
|
||||||
|
* Allow to set/override app data on scope level
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* `App::configure` take an `FnOnce` instead of `Fn`
|
||||||
|
* Upgrade actix-net crates
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-beta.3] - 2019-05-04
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add helper function for executing futures `test::block_fn()`
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Extractor configuration could be registered with `App::data()`
|
||||||
|
or with `Resource::data()` #775
|
||||||
|
|
||||||
|
* Route data is unified with app data, `Route::data()` moved to resource
|
||||||
|
level to `Resource::data()`
|
||||||
|
|
||||||
|
* CORS handling without headers #702
|
||||||
|
|
||||||
|
* Allow to construct `Data` instances to avoid double `Arc` for `Send + Sync` types.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix `NormalizePath` middleware impl #806
|
||||||
|
|
||||||
|
### Deleted
|
||||||
|
|
||||||
|
* `App::data_factory()` is deleted.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-beta.2] - 2019-04-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add raw services support via `web::service()`
|
||||||
|
|
||||||
|
* Add helper functions for reading response body `test::read_body()`
|
||||||
|
|
||||||
|
* Add support for `remainder match` (i.e "/path/{tail}*")
|
||||||
|
|
||||||
|
* Extend `Responder` trait, allow to override status code and headers.
|
||||||
|
|
||||||
|
* Store visit and login timestamp in the identity cookie #502
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* `.to_async()` handler can return `Responder` type #792
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix async web::Data factory handling
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0-beta.1] - 2019-04-20
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
@ -9,12 +170,18 @@
|
|||||||
|
|
||||||
* Add `.peer_addr()` #744
|
* Add `.peer_addr()` #744
|
||||||
|
|
||||||
|
* Add `NormalizePath` middleware
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
* Rename `RouterConfig` to `ServiceConfig`
|
* Rename `RouterConfig` to `ServiceConfig`
|
||||||
|
|
||||||
* Rename `test::call_success` to `test::call_service`
|
* Rename `test::call_success` to `test::call_service`
|
||||||
|
|
||||||
|
* Removed `ServiceRequest::from_parts()` as it is unsafe to create from parts.
|
||||||
|
|
||||||
|
* `CookieIdentityPolicy::max_age()` accepts value in seconds
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
* Fixed `TestRequest::app_data()`
|
* Fixed `TestRequest::app_data()`
|
||||||
|
55
Cargo.toml
55
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web"
|
name = "actix-web"
|
||||||
version = "1.0.0-alpha.6"
|
version = "1.0.4"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -15,6 +15,9 @@ license = "MIT/Apache-2.0"
|
|||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
||||||
|
|
||||||
[badges]
|
[badges]
|
||||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||||
codecov = { repository = "actix/actix-web", branch = "master", service = "github" }
|
codecov = { repository = "actix/actix-web", branch = "master", service = "github" }
|
||||||
@ -28,20 +31,19 @@ members = [
|
|||||||
".",
|
".",
|
||||||
"awc",
|
"awc",
|
||||||
"actix-http",
|
"actix-http",
|
||||||
|
"actix-cors",
|
||||||
"actix-files",
|
"actix-files",
|
||||||
"actix-framed",
|
"actix-framed",
|
||||||
"actix-session",
|
"actix-session",
|
||||||
|
"actix-identity",
|
||||||
"actix-multipart",
|
"actix-multipart",
|
||||||
"actix-web-actors",
|
"actix-web-actors",
|
||||||
"actix-web-codegen",
|
"actix-web-codegen",
|
||||||
"test-server",
|
"test-server",
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
|
||||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client"]
|
default = ["brotli", "flate2-zlib", "client", "fail"]
|
||||||
|
|
||||||
# http client
|
# http client
|
||||||
client = ["awc"]
|
client = ["awc"]
|
||||||
@ -58,6 +60,8 @@ flate2-rust = ["actix-http/flate2-rust"]
|
|||||||
# sessions feature, session require "ring" crate and c compiler
|
# sessions feature, session require "ring" crate and c compiler
|
||||||
secure-cookies = ["actix-http/secure-cookies"]
|
secure-cookies = ["actix-http/secure-cookies"]
|
||||||
|
|
||||||
|
fail = ["actix-http/fail"]
|
||||||
|
|
||||||
# openssl
|
# openssl
|
||||||
ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||||
|
|
||||||
@ -66,42 +70,42 @@ rust-tls = ["rustls", "actix-server/rust-tls"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.1"
|
||||||
actix-utils = "0.3.4"
|
actix-utils = "0.4.4"
|
||||||
actix-router = "0.1.2"
|
actix-router = "0.1.5"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.4"
|
||||||
actix-web-codegen = "0.1.0-alpha.6"
|
actix-web-codegen = "0.1.2"
|
||||||
actix-http = { version = "0.1.0-alpha.5", features=["fail"] }
|
actix-http = "0.2.5"
|
||||||
actix-server = "0.4.3"
|
actix-server = "0.5.1"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.1"
|
||||||
actix-threadpool = "0.1.0"
|
actix-threadpool = "0.1.1"
|
||||||
awc = { version = "0.1.0-alpha.6", optional = true }
|
awc = { version = "0.2.1", optional = true }
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
encoding = "0.2"
|
encoding_rs = "0.8"
|
||||||
futures = "0.1"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.2.2"
|
hashbrown = "0.5.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
net2 = "0.2.33"
|
net2 = "0.2.33"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.8"
|
||||||
regex = "1.0"
|
regex = "1.0"
|
||||||
serde = { version = "1.0", features=["derive"] }
|
serde = { version = "1.0", features=["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde_urlencoded = "0.5.3"
|
serde_urlencoded = "0.5.3"
|
||||||
time = "0.1"
|
time = "0.1.42"
|
||||||
url = { version="1.7", features=["query_encoding"] }
|
url = { version="1.7", features=["query_encoding"] }
|
||||||
|
|
||||||
# ssl support
|
# ssl support
|
||||||
openssl = { version="0.10", optional = true }
|
openssl = { version="0.10", optional = true }
|
||||||
rustls = { version = "^0.15", optional = true }
|
rustls = { version = "0.15", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-http = { version = "0.1.0-alpha.5", features=["ssl", "brotli", "flate2-zlib"] }
|
actix = { version = "0.8.3" }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http = { version = "0.2.5", features=["ssl", "brotli", "flate2-zlib"] }
|
||||||
actix-files = { version = "0.1.0-alpha.6" }
|
actix-http-test = { version = "0.2.2", features=["ssl"] }
|
||||||
rand = "0.6"
|
rand = "0.7"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
tokio-timer = "0.2.8"
|
tokio-timer = "0.2.8"
|
||||||
@ -121,4 +125,5 @@ actix-web-codegen = { path = "actix-web-codegen" }
|
|||||||
actix-web-actors = { path = "actix-web-actors" }
|
actix-web-actors = { path = "actix-web-actors" }
|
||||||
actix-session = { path = "actix-session" }
|
actix-session = { path = "actix-session" }
|
||||||
actix-files = { path = "actix-files" }
|
actix-files = { path = "actix-files" }
|
||||||
|
actix-multipart = { path = "actix-multipart" }
|
||||||
awc = { path = "awc" }
|
awc = { path = "awc" }
|
||||||
|
137
MIGRATION.md
137
MIGRATION.md
@ -1,5 +1,94 @@
|
|||||||
## 1.0
|
## 1.0.1
|
||||||
|
|
||||||
|
* Cors middleware has been moved to `actix-cors` crate
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::middleware::cors::Cors;
|
||||||
|
```
|
||||||
|
|
||||||
|
use
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_cors::Cors;
|
||||||
|
```
|
||||||
|
|
||||||
|
* Identity middleware has been moved to `actix-identity` crate
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::middleware::identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||||
|
```
|
||||||
|
|
||||||
|
use
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
* Extractor configuration. In version 1.0 this is handled with the new `Data` mechanism for both setting and retrieving the configuration
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ExtractorConfig {
|
||||||
|
config: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for YourExtractor {
|
||||||
|
type Config = ExtractorConfig;
|
||||||
|
type Result = Result<YourExtractor, Error>;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, cfg: &Self::Config) -> Self::Result {
|
||||||
|
println!("use the config: {:?}", cfg.config);
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
App::new().resource("/route_with_config", |r| {
|
||||||
|
r.post().with_config(handler_fn, |cfg| {
|
||||||
|
cfg.0.config = "test".to_string();
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
use the HttpRequest to get the configuration like any other `Data` with `req.app_data::<C>()` and set it with the `data()` method on the `resource`
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ExtractorConfig {
|
||||||
|
config: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for YourExtractor {
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Result<Self, Self::Error>;
|
||||||
|
type Config = ExtractorConfig;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
|
let cfg = req.app_data::<ExtractorConfig>();
|
||||||
|
println!("config data?: {:?}", cfg.unwrap().role);
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
App::new().service(
|
||||||
|
resource("/route_with_config")
|
||||||
|
.data(ExtractorConfig {
|
||||||
|
config: "test".to_string(),
|
||||||
|
})
|
||||||
|
.route(post().to(handler_fn)),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
* Resource registration. 1.0 version uses generalized resource
|
* Resource registration. 1.0 version uses generalized resource
|
||||||
registration via `.service()` method.
|
registration via `.service()` method.
|
||||||
|
|
||||||
@ -92,6 +181,36 @@
|
|||||||
App.new().service(web::resource("/welcome").to(welcome))
|
App.new().service(web::resource("/welcome").to(welcome))
|
||||||
```
|
```
|
||||||
|
|
||||||
|
* `HttpRequest` does not provide access to request's payload stream.
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn index(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||||
|
req
|
||||||
|
.payload()
|
||||||
|
.from_err()
|
||||||
|
.fold((), |_, chunk| {
|
||||||
|
...
|
||||||
|
})
|
||||||
|
.map(|_| HttpResponse::Ok().finish())
|
||||||
|
.responder()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
use `Payload` extractor
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn index(stream: web::Payload) -> impl Future<Item=HttpResponse, Error=Error> {
|
||||||
|
stream
|
||||||
|
.from_err()
|
||||||
|
.fold((), |_, chunk| {
|
||||||
|
...
|
||||||
|
})
|
||||||
|
.map(|_| HttpResponse::Ok().finish())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
* `State` is now `Data`. You register Data during the App initialization process
|
* `State` is now `Data`. You register Data during the App initialization process
|
||||||
and then access it from handlers either using a Data extractor or using
|
and then access it from handlers either using a Data extractor or using
|
||||||
HttpRequest's api.
|
HttpRequest's api.
|
||||||
@ -128,7 +247,7 @@
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
* AsyncResponder is removed.
|
* AsyncResponder is removed, use `.to_async()` registration method and `impl Future<>` as result type.
|
||||||
|
|
||||||
instead of
|
instead of
|
||||||
|
|
||||||
@ -164,7 +283,7 @@
|
|||||||
* `HttpRequest::body()`, `HttpRequest::urlencoded()`, `HttpRequest::json()`, `HttpRequest::multipart()`
|
* `HttpRequest::body()`, `HttpRequest::urlencoded()`, `HttpRequest::json()`, `HttpRequest::multipart()`
|
||||||
method have been removed. Use `Bytes`, `String`, `Form`, `Json`, `Multipart` extractors instead.
|
method have been removed. Use `Bytes`, `String`, `Form`, `Json`, `Multipart` extractors instead.
|
||||||
|
|
||||||
instead if
|
instead of
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
fn index(req: &HttpRequest) -> Responder {
|
fn index(req: &HttpRequest) -> Responder {
|
||||||
@ -173,6 +292,7 @@
|
|||||||
...
|
...
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
use
|
use
|
||||||
|
|
||||||
@ -207,6 +327,17 @@
|
|||||||
|
|
||||||
* Actors support have been moved to `actix-web-actors` crate
|
* Actors support have been moved to `actix-web-actors` crate
|
||||||
|
|
||||||
|
* Custom Error
|
||||||
|
|
||||||
|
Instead of error_response method alone, ResponseError now provides two methods: error_response and render_response respectively. Where, error_response creates the error response and render_response returns the error response to the caller.
|
||||||
|
|
||||||
|
Simplest migration from 0.7 to 1.0 shall include below method to the custom implementation of ResponseError:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn render_response(&self) -> HttpResponse {
|
||||||
|
self.error_response()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## 0.7.15
|
## 0.7.15
|
||||||
|
|
||||||
|
@ -11,7 +11,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
|||||||
* Multipart streams
|
* Multipart streams
|
||||||
* Static assets
|
* Static assets
|
||||||
* SSL support with OpenSSL or Rustls
|
* SSL support with OpenSSL or Rustls
|
||||||
* Middlewares ([Logger, Session, CORS, CSRF, etc](https://actix.rs/docs/middleware/))
|
* Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
|
||||||
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
|
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
|
||||||
* Supports [Actix actor framework](https://github.com/actix/actix)
|
* Supports [Actix actor framework](https://github.com/actix/actix)
|
||||||
|
|
||||||
@ -22,7 +22,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
|||||||
* [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/)
|
* [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/)
|
||||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
|
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
|
||||||
* Minimum supported Rust version: 1.32 or later
|
* Minimum supported Rust version: 1.34 or later
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
@ -61,7 +61,7 @@ You may consider checking out
|
|||||||
|
|
||||||
## Benchmarks
|
## Benchmarks
|
||||||
|
|
||||||
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext)
|
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r18)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
9
actix-cors/CHANGES.md
Normal file
9
actix-cors/CHANGES.md
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.1] - unreleased
|
||||||
|
|
||||||
|
* Bump `derive_more` crate version to 0.15.0
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-06-15
|
||||||
|
|
||||||
|
* Move cors middleware to separate crate
|
23
actix-cors/Cargo.toml
Normal file
23
actix-cors/Cargo.toml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-cors"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
|
description = "Cross-origin resource sharing (CORS) for Actix applications."
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["web", "framework"]
|
||||||
|
homepage = "https://actix.rs"
|
||||||
|
repository = "https://github.com/actix/actix-web.git"
|
||||||
|
documentation = "https://docs.rs/actix-cors/"
|
||||||
|
license = "MIT/Apache-2.0"
|
||||||
|
edition = "2018"
|
||||||
|
#workspace = ".."
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "actix_cors"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-web = "1.0.0"
|
||||||
|
actix-service = "0.4.0"
|
||||||
|
derive_more = "0.15.0"
|
||||||
|
futures = "0.1.25"
|
1
actix-cors/LICENSE-APACHE
Symbolic link
1
actix-cors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-cors/LICENSE-MIT
Symbolic link
1
actix-cors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
9
actix-cors/README.md
Normal file
9
actix-cors/README.md
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [User Guide](https://actix.rs/docs/)
|
||||||
|
* [API Documentation](https://docs.rs/actix-cors/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-cors](https://crates.io/crates/actix-cors)
|
||||||
|
* Minimum supported Rust version: 1.34 or later
|
@ -7,7 +7,7 @@
|
|||||||
//! # Example
|
//! # Example
|
||||||
//!
|
//!
|
||||||
//! ```rust
|
//! ```rust
|
||||||
//! use actix_web::middleware::cors::Cors;
|
//! use actix_cors::Cors;
|
||||||
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
|
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
|
||||||
//!
|
//!
|
||||||
//! fn index(req: HttpRequest) -> &'static str {
|
//! fn index(req: HttpRequest) -> &'static str {
|
||||||
@ -42,17 +42,15 @@ use std::iter::FromIterator;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_service::{IntoTransform, Service, Transform};
|
use actix_service::{IntoTransform, Service, Transform};
|
||||||
|
use actix_web::dev::{RequestHead, ServiceRequest, ServiceResponse};
|
||||||
|
use actix_web::error::{Error, ResponseError, Result};
|
||||||
|
use actix_web::http::header::{self, HeaderName, HeaderValue};
|
||||||
|
use actix_web::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
||||||
|
use actix_web::HttpResponse;
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use futures::future::{ok, Either, Future, FutureResult};
|
use futures::future::{ok, Either, Future, FutureResult};
|
||||||
use futures::Poll;
|
use futures::Poll;
|
||||||
|
|
||||||
use crate::dev::RequestHead;
|
|
||||||
use crate::error::{ResponseError, Result};
|
|
||||||
use crate::http::header::{self, HeaderName, HeaderValue};
|
|
||||||
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
|
||||||
use crate::HttpResponse;
|
|
||||||
|
|
||||||
/// A set of errors that can occur during processing CORS
|
/// A set of errors that can occur during processing CORS
|
||||||
#[derive(Debug, Display)]
|
#[derive(Debug, Display)]
|
||||||
pub enum CorsError {
|
pub enum CorsError {
|
||||||
@ -81,13 +79,6 @@ pub enum CorsError {
|
|||||||
fmt = "The request header `Access-Control-Request-Headers` has an invalid value"
|
fmt = "The request header `Access-Control-Request-Headers` has an invalid value"
|
||||||
)]
|
)]
|
||||||
BadRequestHeaders,
|
BadRequestHeaders,
|
||||||
/// The request header `Access-Control-Request-Headers` is required but is
|
|
||||||
/// missing.
|
|
||||||
#[display(
|
|
||||||
fmt = "The request header `Access-Control-Request-Headers` is required but is
|
|
||||||
missing"
|
|
||||||
)]
|
|
||||||
MissingRequestHeaders,
|
|
||||||
/// Origin is not allowed to make this request
|
/// Origin is not allowed to make this request
|
||||||
#[display(fmt = "Origin is not allowed to make this request")]
|
#[display(fmt = "Origin is not allowed to make this request")]
|
||||||
OriginNotAllowed,
|
OriginNotAllowed,
|
||||||
@ -159,11 +150,11 @@ impl<T> AllOrSome<T> {
|
|||||||
/// # Example
|
/// # Example
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
|
/// use actix_cors::Cors;
|
||||||
/// use actix_web::http::header;
|
/// use actix_web::http::header;
|
||||||
/// use actix_web::middleware::cors;
|
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let cors = cors::Cors::new()
|
/// let cors = Cors::new()
|
||||||
/// .allowed_origin("https://www.rust-lang.org/")
|
/// .allowed_origin("https://www.rust-lang.org/")
|
||||||
/// .allowed_methods(vec!["GET", "POST"])
|
/// .allowed_methods(vec!["GET", "POST"])
|
||||||
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
||||||
@ -477,9 +468,8 @@ fn cors<'a>(
|
|||||||
|
|
||||||
impl<S, B> IntoTransform<CorsFactory, S> for Cors
|
impl<S, B> IntoTransform<CorsFactory, S> for Cors
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
fn into_transform(self) -> CorsFactory {
|
fn into_transform(self) -> CorsFactory {
|
||||||
@ -539,14 +529,13 @@ pub struct CorsFactory {
|
|||||||
|
|
||||||
impl<S, B> Transform<S> for CorsFactory
|
impl<S, B> Transform<S> for CorsFactory
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = CorsMiddleware<S>;
|
type Transform = CorsMiddleware<S>;
|
||||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||||
@ -663,15 +652,18 @@ impl Inner {
|
|||||||
Err(_) => return Err(CorsError::BadRequestHeaders),
|
Err(_) => return Err(CorsError::BadRequestHeaders),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// `Access-Control-Request-Headers` must contain 1 or more
|
||||||
if !hdrs.is_empty() && !hdrs.is_subset(allowed_headers) {
|
// `field-name`.
|
||||||
return Err(CorsError::HeadersNotAllowed);
|
if !hdrs.is_empty() {
|
||||||
|
if !hdrs.is_subset(allowed_headers) {
|
||||||
|
return Err(CorsError::HeadersNotAllowed);
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
}
|
}
|
||||||
return Ok(());
|
|
||||||
}
|
}
|
||||||
Err(CorsError::BadRequestHeaders)
|
Err(CorsError::BadRequestHeaders)
|
||||||
} else {
|
} else {
|
||||||
Err(CorsError::MissingRequestHeaders)
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -680,17 +672,16 @@ impl Inner {
|
|||||||
|
|
||||||
impl<S, B> Service for CorsMiddleware<S>
|
impl<S, B> Service for CorsMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = Error;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
FutureResult<Self::Response, Self::Error>,
|
FutureResult<Self::Response, Error>,
|
||||||
Either<S::Future, Box<Future<Item = Self::Response, Error = Self::Error>>>,
|
Either<S::Future, Box<dyn Future<Item = Self::Response, Error = Error>>>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -812,22 +803,26 @@ where
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::{FnService, Transform};
|
use actix_service::{IntoService, Transform};
|
||||||
|
use actix_web::test::{self, block_on, TestRequest};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::test::{self, block_on, TestRequest};
|
|
||||||
|
|
||||||
impl Cors {
|
impl Cors {
|
||||||
fn finish<S, B>(self, srv: S) -> CorsMiddleware<S>
|
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>
|
F: IntoService<S>,
|
||||||
+ 'static,
|
S: Service<
|
||||||
|
Request = ServiceRequest,
|
||||||
|
Response = ServiceResponse<B>,
|
||||||
|
Error = Error,
|
||||||
|
> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
|
||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
block_on(
|
block_on(
|
||||||
IntoTransform::<CorsFactory, S>::into_transform(self).new_transform(srv),
|
IntoTransform::<CorsFactory, S>::into_transform(self)
|
||||||
|
.new_transform(srv.into_service()),
|
||||||
)
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
@ -875,6 +870,7 @@ mod tests {
|
|||||||
|
|
||||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||||
.method(Method::OPTIONS)
|
.method(Method::OPTIONS)
|
||||||
|
.header(header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed")
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
|
|
||||||
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
||||||
@ -888,7 +884,7 @@ mod tests {
|
|||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
|
|
||||||
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
||||||
assert!(cors.inner.validate_allowed_headers(req.head()).is_err());
|
assert!(cors.inner.validate_allowed_headers(req.head()).is_ok());
|
||||||
|
|
||||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||||
.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
|
.header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
|
||||||
@ -1067,11 +1063,11 @@ mod tests {
|
|||||||
.allowed_headers(exposed_headers.clone())
|
.allowed_headers(exposed_headers.clone())
|
||||||
.expose_headers(exposed_headers.clone())
|
.expose_headers(exposed_headers.clone())
|
||||||
.allowed_header(header::CONTENT_TYPE)
|
.allowed_header(header::CONTENT_TYPE)
|
||||||
.finish(FnService::new(move |req: ServiceRequest| {
|
.finish(|req: ServiceRequest| {
|
||||||
req.into_response(
|
req.into_response(
|
||||||
HttpResponse::Ok().header(header::VARY, "Accept").finish(),
|
HttpResponse::Ok().header(header::VARY, "Accept").finish(),
|
||||||
)
|
)
|
||||||
}));
|
});
|
||||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||||
.method(Method::OPTIONS)
|
.method(Method::OPTIONS)
|
||||||
.to_srv_request();
|
.to_srv_request();
|
@ -1,5 +1,33 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.3] - 2019-06-28
|
||||||
|
|
||||||
|
* Do not set `Content-Length` header, let actix-http set it #930
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.2] - 2019-06-13
|
||||||
|
|
||||||
|
* Content-Length is 0 for NamedFile HEAD request #914
|
||||||
|
|
||||||
|
* Fix ring dependency from actix-web default features for #741
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-06-01
|
||||||
|
|
||||||
|
* Static files are incorrectly served as both chunked and with length #812
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-05-25
|
||||||
|
|
||||||
|
* NamedFile last-modified check always fails due to nano-seconds
|
||||||
|
in file modified date #820
|
||||||
|
|
||||||
|
## [0.1.0-beta.4] - 2019-05-12
|
||||||
|
|
||||||
|
* Update actix-web to beta.4
|
||||||
|
|
||||||
|
## [0.1.0-beta.1] - 2019-04-20
|
||||||
|
|
||||||
|
* Update actix-web to beta.1
|
||||||
|
|
||||||
## [0.1.0-alpha.6] - 2019-04-14
|
## [0.1.0-alpha.6] - 2019-04-14
|
||||||
|
|
||||||
* Update actix-web to alpha6
|
* Update actix-web to alpha6
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-files"
|
name = "actix-files"
|
||||||
version = "0.1.0-alpha.6"
|
version = "0.1.3"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Static files support for actix web."
|
description = "Static files support for actix web."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -18,12 +18,13 @@ name = "actix_files"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-alpha.6"
|
actix-web = { version = "1.0.2", default-features = false }
|
||||||
actix-service = "0.3.4"
|
actix-http = "0.2.4"
|
||||||
|
actix-service = "0.4.1"
|
||||||
bitflags = "1"
|
bitflags = "1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
mime_guess = "2.0.0-alpha"
|
mime_guess = "2.0.0-alpha"
|
||||||
@ -31,4 +32,4 @@ percent-encoding = "1.0"
|
|||||||
v_htmlescape = "0.4"
|
v_htmlescape = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "1.0.0-alpha.6", features=["ssl"] }
|
actix-web = { version = "1.0.2", features=["ssl"] }
|
||||||
|
1
actix-files/LICENSE-APACHE
Symbolic link
1
actix-files/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-files/LICENSE-MIT
Symbolic link
1
actix-files/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -1 +1,9 @@
|
|||||||
# Static files support for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-files) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Static files support for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-files) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [User Guide](https://actix.rs/docs/)
|
||||||
|
* [API Documentation](https://docs.rs/actix-files/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-files](https://crates.io/crates/actix-files)
|
||||||
|
* Minimum supported Rust version: 1.33 or later
|
||||||
|
@ -50,7 +50,7 @@ pub struct ChunkedReadFile {
|
|||||||
size: u64,
|
size: u64,
|
||||||
offset: u64,
|
offset: u64,
|
||||||
file: Option<File>,
|
file: Option<File>,
|
||||||
fut: Option<Box<Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>,
|
fut: Option<Box<dyn Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>,
|
||||||
counter: u64,
|
counter: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -334,6 +334,7 @@ impl Files {
|
|||||||
where
|
where
|
||||||
F: IntoNewService<U>,
|
F: IntoNewService<U>,
|
||||||
U: NewService<
|
U: NewService<
|
||||||
|
Config = (),
|
||||||
Request = ServiceRequest,
|
Request = ServiceRequest,
|
||||||
Response = ServiceResponse,
|
Response = ServiceResponse,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -363,12 +364,13 @@ impl HttpServiceFactory for Files {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for Files {
|
impl NewService for Files {
|
||||||
|
type Config = ();
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Service = FilesService;
|
type Service = FilesService;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
type Future = Box<dyn Future<Item = Self::Service, Error = Self::InitError>>;
|
||||||
|
|
||||||
fn new_service(&self, _: &()) -> Self::Future {
|
fn new_service(&self, _: &()) -> Self::Future {
|
||||||
let mut srv = FilesService {
|
let mut srv = FilesService {
|
||||||
@ -411,17 +413,16 @@ impl FilesService {
|
|||||||
fn handle_err(
|
fn handle_err(
|
||||||
&mut self,
|
&mut self,
|
||||||
e: io::Error,
|
e: io::Error,
|
||||||
req: HttpRequest,
|
req: ServiceRequest,
|
||||||
payload: Payload,
|
|
||||||
) -> Either<
|
) -> Either<
|
||||||
FutureResult<ServiceResponse, Error>,
|
FutureResult<ServiceResponse, Error>,
|
||||||
Box<Future<Item = ServiceResponse, Error = Error>>,
|
Box<dyn Future<Item = ServiceResponse, Error = Error>>,
|
||||||
> {
|
> {
|
||||||
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
||||||
if let Some(ref mut default) = self.default {
|
if let Some(ref mut default) = self.default {
|
||||||
default.call(ServiceRequest::from_parts(req, payload))
|
default.call(req)
|
||||||
} else {
|
} else {
|
||||||
Either::A(ok(ServiceResponse::from_err(e, req.clone())))
|
Either::A(ok(req.error_response(e)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -432,7 +433,7 @@ impl Service for FilesService {
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
FutureResult<Self::Response, Self::Error>,
|
FutureResult<Self::Response, Self::Error>,
|
||||||
Box<Future<Item = Self::Response, Error = Self::Error>>,
|
Box<dyn Future<Item = Self::Response, Error = Self::Error>>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -440,17 +441,17 @@ impl Service for FilesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||||
let (req, pl) = req.into_parts();
|
// let (req, pl) = req.into_parts();
|
||||||
|
|
||||||
let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) {
|
let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) {
|
||||||
Ok(item) => item,
|
Ok(item) => item,
|
||||||
Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req.clone()))),
|
Err(e) => return Either::A(ok(req.error_response(e))),
|
||||||
};
|
};
|
||||||
|
|
||||||
// full filepath
|
// full filepath
|
||||||
let path = match self.directory.join(&real_path.0).canonicalize() {
|
let path = match self.directory.join(&real_path.0).canonicalize() {
|
||||||
Ok(path) => path,
|
Ok(path) => path,
|
||||||
Err(e) => return self.handle_err(e, req, pl),
|
Err(e) => return self.handle_err(e, req),
|
||||||
};
|
};
|
||||||
|
|
||||||
if path.is_dir() {
|
if path.is_dir() {
|
||||||
@ -466,24 +467,26 @@ impl Service for FilesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
named_file.flags = self.file_flags;
|
named_file.flags = self.file_flags;
|
||||||
|
let (req, _) = req.into_parts();
|
||||||
Either::A(ok(match named_file.respond_to(&req) {
|
Either::A(ok(match named_file.respond_to(&req) {
|
||||||
Ok(item) => ServiceResponse::new(req.clone(), item),
|
Ok(item) => ServiceResponse::new(req, item),
|
||||||
Err(e) => ServiceResponse::from_err(e, req.clone()),
|
Err(e) => ServiceResponse::from_err(e, req),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
Err(e) => return self.handle_err(e, req, pl),
|
Err(e) => return self.handle_err(e, req),
|
||||||
}
|
}
|
||||||
} else if self.show_index {
|
} else if self.show_index {
|
||||||
let dir = Directory::new(self.directory.clone(), path);
|
let dir = Directory::new(self.directory.clone(), path);
|
||||||
|
let (req, _) = req.into_parts();
|
||||||
let x = (self.renderer)(&dir, &req);
|
let x = (self.renderer)(&dir, &req);
|
||||||
match x {
|
match x {
|
||||||
Ok(resp) => Either::A(ok(resp)),
|
Ok(resp) => Either::A(ok(resp)),
|
||||||
Err(e) => return self.handle_err(e, req, pl),
|
Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Either::A(ok(ServiceResponse::from_err(
|
Either::A(ok(ServiceResponse::from_err(
|
||||||
FilesError::IsDirectory,
|
FilesError::IsDirectory,
|
||||||
req.clone(),
|
req.into_parts().0,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -496,16 +499,15 @@ impl Service for FilesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
named_file.flags = self.file_flags;
|
named_file.flags = self.file_flags;
|
||||||
|
let (req, _) = req.into_parts();
|
||||||
match named_file.respond_to(&req) {
|
match named_file.respond_to(&req) {
|
||||||
Ok(item) => {
|
Ok(item) => {
|
||||||
Either::A(ok(ServiceResponse::new(req.clone(), item)))
|
Either::A(ok(ServiceResponse::new(req.clone(), item)))
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||||
Either::A(ok(ServiceResponse::from_err(e, req.clone())))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => self.handle_err(e, req, pl),
|
Err(e) => self.handle_err(e, req),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -853,6 +855,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_named_file_content_length_headers() {
|
fn test_named_file_content_length_headers() {
|
||||||
|
use actix_web::body::{MessageBody, ResponseBody};
|
||||||
|
|
||||||
let mut srv = test::init_service(
|
let mut srv = test::init_service(
|
||||||
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
||||||
);
|
);
|
||||||
@ -864,14 +868,13 @@ mod tests {
|
|||||||
.to_request();
|
.to_request();
|
||||||
let response = test::call_service(&mut srv, request);
|
let response = test::call_service(&mut srv, request);
|
||||||
|
|
||||||
let contentlength = response
|
// let contentlength = response
|
||||||
.headers()
|
// .headers()
|
||||||
.get(header::CONTENT_LENGTH)
|
// .get(header::CONTENT_LENGTH)
|
||||||
.unwrap()
|
// .unwrap()
|
||||||
.to_str()
|
// .to_str()
|
||||||
.unwrap();
|
// .unwrap();
|
||||||
|
// assert_eq!(contentlength, "11");
|
||||||
assert_eq!(contentlength, "11");
|
|
||||||
|
|
||||||
// Invalid range header
|
// Invalid range header
|
||||||
let request = TestRequest::get()
|
let request = TestRequest::get()
|
||||||
@ -888,14 +891,13 @@ mod tests {
|
|||||||
.to_request();
|
.to_request();
|
||||||
let response = test::call_service(&mut srv, request);
|
let response = test::call_service(&mut srv, request);
|
||||||
|
|
||||||
let contentlength = response
|
// let contentlength = response
|
||||||
.headers()
|
// .headers()
|
||||||
.get(header::CONTENT_LENGTH)
|
// .get(header::CONTENT_LENGTH)
|
||||||
.unwrap()
|
// .unwrap()
|
||||||
.to_str()
|
// .to_str()
|
||||||
.unwrap();
|
// .unwrap();
|
||||||
|
// assert_eq!(contentlength, "100");
|
||||||
assert_eq!(contentlength, "100");
|
|
||||||
|
|
||||||
// chunked
|
// chunked
|
||||||
let request = TestRequest::get()
|
let request = TestRequest::get()
|
||||||
@ -924,6 +926,29 @@ mod tests {
|
|||||||
assert_eq!(bytes.freeze(), data);
|
assert_eq!(bytes.freeze(), data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_head_content_length_headers() {
|
||||||
|
let mut srv = test::init_service(
|
||||||
|
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Valid range header
|
||||||
|
let request = TestRequest::default()
|
||||||
|
.method(Method::HEAD)
|
||||||
|
.uri("/t%65st/tests/test.binary")
|
||||||
|
.to_request();
|
||||||
|
let response = test::call_service(&mut srv, request);
|
||||||
|
|
||||||
|
// TODO: fix check
|
||||||
|
// let contentlength = response
|
||||||
|
// .headers()
|
||||||
|
// .get(header::CONTENT_LENGTH)
|
||||||
|
// .unwrap()
|
||||||
|
// .to_str()
|
||||||
|
// .unwrap();
|
||||||
|
// assert_eq!(contentlength, "100");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_static_files_with_spaces() {
|
fn test_static_files_with_spaces() {
|
||||||
let mut srv = test::init_service(
|
let mut srv = test::init_service(
|
||||||
|
@ -11,6 +11,7 @@ use bitflags::bitflags;
|
|||||||
use mime;
|
use mime;
|
||||||
use mime_guess::guess_mime_type;
|
use mime_guess::guess_mime_type;
|
||||||
|
|
||||||
|
use actix_http::body::SizedStream;
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
self, ContentDisposition, DispositionParam, DispositionType,
|
self, ContentDisposition, DispositionParam, DispositionType,
|
||||||
};
|
};
|
||||||
@ -66,6 +67,7 @@ impl NamedFile {
|
|||||||
/// let mut file = File::create("foo.txt")?;
|
/// let mut file = File::create("foo.txt")?;
|
||||||
/// file.write_all(b"Hello, world!")?;
|
/// file.write_all(b"Hello, world!")?;
|
||||||
/// let named_file = NamedFile::from_file(file, "bar.txt")?;
|
/// let named_file = NamedFile::from_file(file, "bar.txt")?;
|
||||||
|
/// # std::fs::remove_file("foo.txt");
|
||||||
/// Ok(())
|
/// Ok(())
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@ -336,7 +338,12 @@ impl Responder for NamedFile {
|
|||||||
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
|
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
|
||||||
(last_modified, req.get_header())
|
(last_modified, req.get_header())
|
||||||
{
|
{
|
||||||
m > since
|
let t1: SystemTime = m.clone().into();
|
||||||
|
let t2: SystemTime = since.clone().into();
|
||||||
|
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||||
|
(Ok(t1), Ok(t2)) => t1 > t2,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
};
|
};
|
||||||
@ -349,7 +356,12 @@ impl Responder for NamedFile {
|
|||||||
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
|
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
|
||||||
(last_modified, req.get_header())
|
(last_modified, req.get_header())
|
||||||
{
|
{
|
||||||
m <= since
|
let t1: SystemTime = m.clone().into();
|
||||||
|
let t2: SystemTime = since.clone().into();
|
||||||
|
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||||
|
(Ok(t1), Ok(t2)) => t1 <= t2,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
};
|
};
|
||||||
@ -402,28 +414,22 @@ impl Responder for NamedFile {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
resp.header(header::CONTENT_LENGTH, format!("{}", length));
|
|
||||||
|
|
||||||
if precondition_failed {
|
if precondition_failed {
|
||||||
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish());
|
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish());
|
||||||
} else if not_modified {
|
} else if not_modified {
|
||||||
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
||||||
}
|
}
|
||||||
|
|
||||||
if *req.method() == Method::HEAD {
|
let reader = ChunkedReadFile {
|
||||||
Ok(resp.finish())
|
offset,
|
||||||
} else {
|
size: length,
|
||||||
let reader = ChunkedReadFile {
|
file: Some(self.file),
|
||||||
offset,
|
fut: None,
|
||||||
size: length,
|
counter: 0,
|
||||||
file: Some(self.file),
|
};
|
||||||
fut: None,
|
if offset != 0 || length != self.md.len() {
|
||||||
counter: 0,
|
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||||
};
|
};
|
||||||
if offset != 0 || length != self.md.len() {
|
Ok(resp.body(SizedStream::new(length, reader)))
|
||||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
|
||||||
};
|
|
||||||
Ok(resp.streaming(reader))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-framed"
|
name = "actix-framed"
|
||||||
version = "0.1.0-alpha.1"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix framed app server"
|
description = "Actix framed app server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -21,17 +21,18 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.0"
|
||||||
actix-utils = "0.3.4"
|
actix-utils = "0.4.0"
|
||||||
actix-router = "0.1.2"
|
actix-router = "0.1.2"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-http = "0.1.0-alpha.5"
|
actix-http = "0.2.0"
|
||||||
|
actix-server-config = "0.1.1"
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-server = { version = "0.4.1", features=["ssl"] }
|
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
|
@ -1 +1,8 @@
|
|||||||
# Framed app for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-framed) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Framed app for actix web [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-framed) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [API Documentation](https://docs.rs/actix-framed/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-framed](https://crates.io/crates/actix-framed)
|
||||||
|
* Minimum supported Rust version: 1.33 or later
|
||||||
|
@ -1,5 +1,15 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
|
* Update dependencies
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
|
* Update tests
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0-alpha.1] - 2019-04-12
|
## [0.1.0-alpha.1] - 2019-04-12
|
||||||
|
|
||||||
* Initial release
|
* Initial release
|
||||||
|
@ -4,6 +4,7 @@ use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
|||||||
use actix_http::h1::{Codec, SendResponse};
|
use actix_http::h1::{Codec, SendResponse};
|
||||||
use actix_http::{Error, Request, Response};
|
use actix_http::{Error, Request, Response};
|
||||||
use actix_router::{Path, Router, Url};
|
use actix_router::{Path, Router, Url};
|
||||||
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
use actix_utils::cloneable::CloneableService;
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
@ -12,7 +13,7 @@ use crate::helpers::{BoxedHttpNewService, BoxedHttpService, HttpNewService};
|
|||||||
use crate::request::FramedRequest;
|
use crate::request::FramedRequest;
|
||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
|
|
||||||
type BoxedResponse = Box<Future<Item = (), Error = Error>>;
|
type BoxedResponse = Box<dyn Future<Item = (), Error = Error>>;
|
||||||
|
|
||||||
pub trait HttpServiceFactory {
|
pub trait HttpServiceFactory {
|
||||||
type Factory: NewService;
|
type Factory: NewService;
|
||||||
@ -49,6 +50,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
|||||||
where
|
where
|
||||||
U: HttpServiceFactory,
|
U: HttpServiceFactory,
|
||||||
U::Factory: NewService<
|
U::Factory: NewService<
|
||||||
|
Config = (),
|
||||||
Request = FramedRequest<T, S>,
|
Request = FramedRequest<T, S>,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
@ -59,7 +61,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
|||||||
Request = FramedRequest<T, S>,
|
Request = FramedRequest<T, S>,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
Future = Box<Future<Item = (), Error = Error>>,
|
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||||
>,
|
>,
|
||||||
{
|
{
|
||||||
let path = factory.path().to_string();
|
let path = factory.path().to_string();
|
||||||
@ -88,11 +90,12 @@ pub struct FramedAppFactory<T, S> {
|
|||||||
services: Rc<Vec<(String, BoxedHttpNewService<FramedRequest<T, S>>)>>,
|
services: Rc<Vec<(String, BoxedHttpNewService<FramedRequest<T, S>>)>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, C> NewService<C> for FramedAppFactory<T, S>
|
impl<T, S> NewService for FramedAppFactory<T, S>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
S: 'static,
|
S: 'static,
|
||||||
{
|
{
|
||||||
|
type Config = ServerConfig;
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -100,7 +103,7 @@ where
|
|||||||
type Service = CloneableService<FramedAppService<T, S>>;
|
type Service = CloneableService<FramedAppService<T, S>>;
|
||||||
type Future = CreateService<T, S>;
|
type Future = CreateService<T, S>;
|
||||||
|
|
||||||
fn new_service(&self, _: &C) -> Self::Future {
|
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||||
CreateService {
|
CreateService {
|
||||||
fut: self
|
fut: self
|
||||||
.services
|
.services
|
||||||
@ -126,7 +129,7 @@ pub struct CreateService<T, S> {
|
|||||||
enum CreateServiceItem<T, S> {
|
enum CreateServiceItem<T, S> {
|
||||||
Future(
|
Future(
|
||||||
Option<String>,
|
Option<String>,
|
||||||
Box<Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>,
|
Box<dyn Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>,
|
||||||
),
|
),
|
||||||
Service(String, BoxedHttpService<FramedRequest<T, S>>),
|
Service(String, BoxedHttpService<FramedRequest<T, S>>),
|
||||||
}
|
}
|
||||||
|
@ -7,18 +7,19 @@ pub(crate) type BoxedHttpService<Req> = Box<
|
|||||||
Request = Req,
|
Request = Req,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
Future = Box<Future<Item = (), Error = Error>>,
|
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||||
>,
|
>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||||
NewService<
|
NewService<
|
||||||
|
Config = (),
|
||||||
Request = Req,
|
Request = Req,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
Service = BoxedHttpService<Req>,
|
Service = BoxedHttpService<Req>,
|
||||||
Future = Box<Future<Item = BoxedHttpService<Req>, Error = ()>>,
|
Future = Box<dyn Future<Item = BoxedHttpService<Req>, Error = ()>>,
|
||||||
>,
|
>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
@ -29,7 +30,7 @@ where
|
|||||||
T: NewService<Response = (), Error = Error>,
|
T: NewService<Response = (), Error = Error>,
|
||||||
T::Response: 'static,
|
T::Response: 'static,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
pub fn new(service: T) -> Self {
|
pub fn new(service: T) -> Self {
|
||||||
@ -39,18 +40,19 @@ where
|
|||||||
|
|
||||||
impl<T> NewService for HttpNewService<T>
|
impl<T> NewService for HttpNewService<T>
|
||||||
where
|
where
|
||||||
T: NewService<Response = (), Error = Error>,
|
T: NewService<Config = (), Response = (), Error = Error>,
|
||||||
T::Request: 'static,
|
T::Request: 'static,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
|
||||||
<T::Service as Service>::Future: 'static,
|
<T::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
|
type Config = ();
|
||||||
type Request = T::Request;
|
type Request = T::Request;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Service = BoxedHttpService<T::Request>;
|
type Service = BoxedHttpService<T::Request>;
|
||||||
type Future = Box<Future<Item = Self::Service, Error = ()>>;
|
type Future = Box<dyn Future<Item = Self::Service, Error = ()>>;
|
||||||
|
|
||||||
fn new_service(&self, _: &()) -> Self::Future {
|
fn new_service(&self, _: &()) -> Self::Future {
|
||||||
Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| {
|
Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| {
|
||||||
@ -68,7 +70,7 @@ impl<T> Service for HttpServiceWrapper<T>
|
|||||||
where
|
where
|
||||||
T: Service<
|
T: Service<
|
||||||
Response = (),
|
Response = (),
|
||||||
Future = Box<Future<Item = (), Error = Error>>,
|
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
>,
|
>,
|
||||||
T::Request: 'static,
|
T::Request: 'static,
|
||||||
@ -76,7 +78,7 @@ where
|
|||||||
type Request = T::Request;
|
type Request = T::Request;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Box<Future<Item = (), Error = Error>>;
|
type Future = Box<dyn Future<Item = (), Error = Error>>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.poll_ready()
|
self.service.poll_ready()
|
||||||
|
@ -106,6 +106,7 @@ where
|
|||||||
R::Future: 'static,
|
R::Future: 'static,
|
||||||
R::Error: fmt::Display,
|
R::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
type Config = ();
|
||||||
type Request = FramedRequest<Io, S>;
|
type Request = FramedRequest<Io, S>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -139,7 +140,7 @@ where
|
|||||||
type Request = FramedRequest<Io, S>;
|
type Request = FramedRequest<Io, S>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Box<Future<Item = (), Error = Error>>;
|
type Future = Box<dyn Future<Item = (), Error = Error>>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
|
@ -12,22 +12,23 @@ use futures::{Async, Future, IntoFuture, Poll, Sink};
|
|||||||
|
|
||||||
/// Service that verifies incoming request if it is valid websocket
|
/// Service that verifies incoming request if it is valid websocket
|
||||||
/// upgrade request. In case of error returns `HandshakeError`
|
/// upgrade request. In case of error returns `HandshakeError`
|
||||||
pub struct VerifyWebSockets<T> {
|
pub struct VerifyWebSockets<T, C> {
|
||||||
_t: PhantomData<T>,
|
_t: PhantomData<(T, C)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Default for VerifyWebSockets<T> {
|
impl<T, C> Default for VerifyWebSockets<T, C> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
VerifyWebSockets { _t: PhantomData }
|
VerifyWebSockets { _t: PhantomData }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
impl<T, C> NewService for VerifyWebSockets<T, C> {
|
||||||
|
type Config = C;
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = (Request, Framed<T, Codec>);
|
type Response = (Request, Framed<T, Codec>);
|
||||||
type Error = (HandshakeError, Framed<T, Codec>);
|
type Error = (HandshakeError, Framed<T, Codec>);
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Service = VerifyWebSockets<T>;
|
type Service = VerifyWebSockets<T, C>;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &C) -> Self::Future {
|
fn new_service(&self, _: &C) -> Self::Future {
|
||||||
@ -35,7 +36,7 @@ impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Service for VerifyWebSockets<T> {
|
impl<T, C> Service for VerifyWebSockets<T, C> {
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = (Request, Framed<T, Codec>);
|
type Response = (Request, Framed<T, Codec>);
|
||||||
type Error = (HandshakeError, Framed<T, Codec>);
|
type Error = (HandshakeError, Framed<T, Codec>);
|
||||||
@ -54,9 +55,9 @@ impl<T> Service for VerifyWebSockets<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Send http/1 error response
|
/// Send http/1 error response
|
||||||
pub struct SendError<T, R, E>(PhantomData<(T, R, E)>);
|
pub struct SendError<T, R, E, C>(PhantomData<(T, R, E, C)>);
|
||||||
|
|
||||||
impl<T, R, E> Default for SendError<T, R, E>
|
impl<T, R, E, C> Default for SendError<T, R, E, C>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
E: ResponseError,
|
E: ResponseError,
|
||||||
@ -66,17 +67,18 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, R, E, C> NewService<C> for SendError<T, R, E>
|
impl<T, R, E, C> NewService for SendError<T, R, E, C>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
R: 'static,
|
R: 'static,
|
||||||
E: ResponseError + 'static,
|
E: ResponseError + 'static,
|
||||||
{
|
{
|
||||||
|
type Config = C;
|
||||||
type Request = Result<R, (E, Framed<T, Codec>)>;
|
type Request = Result<R, (E, Framed<T, Codec>)>;
|
||||||
type Response = R;
|
type Response = R;
|
||||||
type Error = (E, Framed<T, Codec>);
|
type Error = (E, Framed<T, Codec>);
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Service = SendError<T, R, E>;
|
type Service = SendError<T, R, E, C>;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &C) -> Self::Future {
|
fn new_service(&self, _: &C) -> Self::Future {
|
||||||
@ -84,7 +86,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, R, E> Service for SendError<T, R, E>
|
impl<T, R, E, C> Service for SendError<T, R, E, C>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
R: 'static,
|
R: 'static,
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_http::{body, ws, Error, HttpService, Response};
|
use actix_http::{body, http::StatusCode, ws, Error, HttpService, Response};
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_service::{IntoNewService, NewService};
|
use actix_service::{IntoNewService, NewService};
|
||||||
use actix_utils::framed::FramedTransport;
|
use actix_utils::framed::FramedTransport;
|
||||||
@ -99,6 +99,11 @@ fn test_service() {
|
|||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// non ws request
|
||||||
|
let res = srv.block_on(srv.get("/index.html").send()).unwrap();
|
||||||
|
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
// not found
|
||||||
assert!(srv.ws_at("/test").is_err());
|
assert!(srv.ws_at("/test").is_err());
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
|
@ -1,5 +1,119 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.6] - 2019-07-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Replace `ClonableService` with local copy
|
||||||
|
|
||||||
|
* Upgrade `rand` dependency version to 0.7
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.5] - 2019-06-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add `on-connect` callback, `HttpServiceBuilder::on_connect()` #946
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use `encoding_rs` crate instead of unmaintained `encoding` crate
|
||||||
|
|
||||||
|
* Add `Copy` and `Clone` impls for `ws::Codec`
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.4] - 2019-06-16
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Do not compress NoContent (204) responses #918
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.3] - 2019-06-02
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Debug impl for ResponseBuilder
|
||||||
|
|
||||||
|
* From SizedStream and BodyStream for Body
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* SizedStream uses u64
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.2] - 2019-05-29
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Parse incoming stream before closing stream on disconnect #868
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.1] - 2019-05-25
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Handle socket read disconnect
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Update actix-service to 0.4
|
||||||
|
|
||||||
|
* Expect and upgrade services accept `ServerConfig` config.
|
||||||
|
|
||||||
|
### Deleted
|
||||||
|
|
||||||
|
* `OneRequest` service
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.5] - 2019-05-04
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Clean up response extensions in response pool #817
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.4] - 2019-04-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to render h1 request headers in `Camel-Case`
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Read until eof for http/1.0 responses #771
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.3] - 2019-04-23
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix http client pool management
|
||||||
|
|
||||||
|
* Fix http client wait queue management #794
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.2] - 2019-04-23
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix BorrowMutError panic in client connector #793
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-04-19
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Cookie::max_age() accepts value in seconds
|
||||||
|
|
||||||
|
* Cookie::max_age_time() accepts value in time::Duration
|
||||||
|
|
||||||
|
* Allow to specify server address for client connector
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0] - 2019-04-16
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http"
|
name = "actix-http"
|
||||||
version = "0.1.0"
|
version = "0.2.5"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix http primitives"
|
description = "Actix http primitives"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -44,23 +44,23 @@ fail = ["failure"]
|
|||||||
secure-cookies = ["ring"]
|
secure-cookies = ["ring"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "0.3.6"
|
actix-service = "0.4.1"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-connect = "0.1.4"
|
actix-connect = "0.2.1"
|
||||||
actix-utils = "0.3.5"
|
actix-utils = "0.4.4"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.1"
|
||||||
actix-threadpool = "0.1.0"
|
actix-threadpool = "0.1.1"
|
||||||
|
|
||||||
base64 = "0.10"
|
base64 = "0.10"
|
||||||
bitflags = "1.0"
|
bitflags = "1.0"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
byteorder = "1.2"
|
byteorder = "1.2"
|
||||||
copyless = "0.1.2"
|
copyless = "0.1.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
either = "1.5.2"
|
either = "1.5.2"
|
||||||
encoding = "0.2"
|
encoding_rs = "0.8"
|
||||||
futures = "0.1"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.2.2"
|
hashbrown = "0.5.0"
|
||||||
h2 = "0.1.16"
|
h2 = "0.1.16"
|
||||||
http = "0.1.17"
|
http = "0.1.17"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
@ -70,18 +70,18 @@ language-tags = "0.2"
|
|||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
percent-encoding = "1.0"
|
percent-encoding = "1.0"
|
||||||
rand = "0.6"
|
rand = "0.7"
|
||||||
regex = "1.0"
|
regex = "1.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
sha1 = "0.6"
|
sha1 = "0.6"
|
||||||
slab = "0.4"
|
slab = "0.4"
|
||||||
serde_urlencoded = "0.5.5"
|
serde_urlencoded = "0.5.5"
|
||||||
time = "0.1"
|
time = "0.1.42"
|
||||||
tokio-tcp = "0.1.3"
|
tokio-tcp = "0.1.3"
|
||||||
tokio-timer = "0.2.8"
|
tokio-timer = "0.2.8"
|
||||||
tokio-current-thread = "0.1"
|
tokio-current-thread = "0.1"
|
||||||
trust-dns-resolver = { version="0.11.0", default-features = false }
|
trust-dns-resolver = { version="0.11.1", default-features = false }
|
||||||
|
|
||||||
# for secure cookie
|
# for secure cookie
|
||||||
ring = { version = "0.14.6", optional = true }
|
ring = { version = "0.14.6", optional = true }
|
||||||
@ -93,12 +93,13 @@ flate2 = { version="1.0.7", optional = true, default-features = false }
|
|||||||
# optional deps
|
# optional deps
|
||||||
failure = { version = "0.1.5", optional = true }
|
failure = { version = "0.1.5", optional = true }
|
||||||
openssl = { version="0.10", optional = true }
|
openssl = { version="0.10", optional = true }
|
||||||
|
chrono = "0.4.6"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
openssl = { version="0.10" }
|
openssl = { version="0.10" }
|
||||||
|
@ -234,6 +234,25 @@ impl From<BytesMut> for Body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<S> From<SizedStream<S>> for Body
|
||||||
|
where
|
||||||
|
S: Stream<Item = Bytes, Error = Error> + 'static,
|
||||||
|
{
|
||||||
|
fn from(s: SizedStream<S>) -> Body {
|
||||||
|
Body::from_message(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S, E> From<BodyStream<S, E>> for Body
|
||||||
|
where
|
||||||
|
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||||
|
E: Into<Error> + 'static,
|
||||||
|
{
|
||||||
|
fn from(s: BodyStream<S, E>) -> Body {
|
||||||
|
Body::from_message(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl MessageBody for Bytes {
|
impl MessageBody for Bytes {
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len())
|
BodySize::Sized(self.len())
|
||||||
@ -366,7 +385,7 @@ where
|
|||||||
/// Type represent streaming body. This body implementation should be used
|
/// Type represent streaming body. This body implementation should be used
|
||||||
/// if total size of stream is known. Data get sent as is without using transfer encoding.
|
/// if total size of stream is known. Data get sent as is without using transfer encoding.
|
||||||
pub struct SizedStream<S> {
|
pub struct SizedStream<S> {
|
||||||
size: usize,
|
size: u64,
|
||||||
stream: S,
|
stream: S,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -374,7 +393,7 @@ impl<S> SizedStream<S>
|
|||||||
where
|
where
|
||||||
S: Stream<Item = Bytes, Error = Error>,
|
S: Stream<Item = Bytes, Error = Error>,
|
||||||
{
|
{
|
||||||
pub fn new(size: usize, stream: S) -> Self {
|
pub fn new(size: u64, stream: S) -> Self {
|
||||||
SizedStream { size, stream }
|
SizedStream { size, stream }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -384,7 +403,7 @@ where
|
|||||||
S: Stream<Item = Bytes, Error = Error>,
|
S: Stream<Item = Bytes, Error = Error>,
|
||||||
{
|
{
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.size)
|
BodySize::Sized64(self.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
use actix_server_config::ServerConfig as SrvConfig;
|
use actix_server_config::ServerConfig as SrvConfig;
|
||||||
@ -10,6 +11,7 @@ use crate::config::{KeepAlive, ServiceConfig};
|
|||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::h1::{Codec, ExpectHandler, H1Service, UpgradeHandler};
|
use crate::h1::{Codec, ExpectHandler, H1Service, UpgradeHandler};
|
||||||
use crate::h2::H2Service;
|
use crate::h2::H2Service;
|
||||||
|
use crate::helpers::{Data, DataFactory};
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
use crate::service::HttpService;
|
use crate::service::HttpService;
|
||||||
@ -24,12 +26,13 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
|
|||||||
client_disconnect: u64,
|
client_disconnect: u64,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, S)>,
|
_t: PhantomData<(T, S)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>>
|
impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -41,6 +44,7 @@ where
|
|||||||
client_disconnect: 0,
|
client_disconnect: 0,
|
||||||
expect: ExpectHandler,
|
expect: ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -48,13 +52,17 @@ where
|
|||||||
|
|
||||||
impl<T, S, X, U> HttpServiceBuilder<T, S, X, U>
|
impl<T, S, X, U> HttpServiceBuilder<T, S, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
U: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -101,7 +109,7 @@ where
|
|||||||
pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U>
|
pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U>
|
||||||
where
|
where
|
||||||
F: IntoNewService<X1>,
|
F: IntoNewService<X1>,
|
||||||
X1: NewService<Request = Request, Response = Request>,
|
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X1::Error: Into<Error>,
|
X1::Error: Into<Error>,
|
||||||
X1::InitError: fmt::Debug,
|
X1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -111,6 +119,7 @@ where
|
|||||||
client_disconnect: self.client_disconnect,
|
client_disconnect: self.client_disconnect,
|
||||||
expect: expect.into_new_service(),
|
expect: expect.into_new_service(),
|
||||||
upgrade: self.upgrade,
|
upgrade: self.upgrade,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -122,7 +131,11 @@ where
|
|||||||
pub fn upgrade<F, U1>(self, upgrade: F) -> HttpServiceBuilder<T, S, X, U1>
|
pub fn upgrade<F, U1>(self, upgrade: F) -> HttpServiceBuilder<T, S, X, U1>
|
||||||
where
|
where
|
||||||
F: IntoNewService<U1>,
|
F: IntoNewService<U1>,
|
||||||
U1: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
U1: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U1::Error: fmt::Display,
|
U1::Error: fmt::Display,
|
||||||
U1::InitError: fmt::Debug,
|
U1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -132,15 +145,29 @@ where
|
|||||||
client_disconnect: self.client_disconnect,
|
client_disconnect: self.client_disconnect,
|
||||||
expect: self.expect,
|
expect: self.expect,
|
||||||
upgrade: Some(upgrade.into_new_service()),
|
upgrade: Some(upgrade.into_new_service()),
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on-connect callback.
|
||||||
|
///
|
||||||
|
/// It get called once per connection and result of the call
|
||||||
|
/// get stored to the request's extensions.
|
||||||
|
pub fn on_connect<F, I>(mut self, f: F) -> Self
|
||||||
|
where
|
||||||
|
F: Fn(&T) -> I + 'static,
|
||||||
|
I: Clone + 'static,
|
||||||
|
{
|
||||||
|
self.on_connect = Some(Rc::new(move |io| Box::new(Data(f(io)))));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Finish service configuration and create *http service* for HTTP/1 protocol.
|
/// Finish service configuration and create *http service* for HTTP/1 protocol.
|
||||||
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
F: IntoNewService<S, SrvConfig>,
|
F: IntoNewService<S>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -153,13 +180,14 @@ where
|
|||||||
H1Service::with_config(cfg, service.into_new_service())
|
H1Service::with_config(cfg, service.into_new_service())
|
||||||
.expect(self.expect)
|
.expect(self.expect)
|
||||||
.upgrade(self.upgrade)
|
.upgrade(self.upgrade)
|
||||||
|
.on_connect(self.on_connect)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Finish service configuration and create *http service* for HTTP/2 protocol.
|
/// Finish service configuration and create *http service* for HTTP/2 protocol.
|
||||||
pub fn h2<F, P, B>(self, service: F) -> H2Service<T, P, S, B>
|
pub fn h2<F, P, B>(self, service: F) -> H2Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
F: IntoNewService<S, SrvConfig>,
|
F: IntoNewService<S>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -177,7 +205,7 @@ where
|
|||||||
pub fn finish<F, P, B>(self, service: F) -> HttpService<T, P, S, B, X, U>
|
pub fn finish<F, P, B>(self, service: F) -> HttpService<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
F: IntoNewService<S, SrvConfig>,
|
F: IntoNewService<S>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -191,5 +219,6 @@ where
|
|||||||
HttpService::with_config(cfg, service.into_new_service())
|
HttpService::with_config(cfg, service.into_new_service())
|
||||||
.expect(self.expect)
|
.expect(self.expect)
|
||||||
.upgrade(self.upgrade)
|
.upgrade(self.upgrade)
|
||||||
|
.on_connect(self.on_connect)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -94,7 +94,8 @@ where
|
|||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
type Io = T;
|
type Io = T;
|
||||||
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
type Future =
|
||||||
|
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||||
|
|
||||||
fn protocol(&self) -> Protocol {
|
fn protocol(&self) -> Protocol {
|
||||||
match self.io {
|
match self.io {
|
||||||
@ -169,7 +170,8 @@ where
|
|||||||
B: AsyncRead + AsyncWrite + 'static,
|
B: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
type Io = EitherIo<A, B>;
|
type Io = EitherIo<A, B>;
|
||||||
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
type Future =
|
||||||
|
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||||
|
|
||||||
fn protocol(&self) -> Protocol {
|
fn protocol(&self) -> Protocol {
|
||||||
match self {
|
match self {
|
||||||
|
@ -14,6 +14,7 @@ use tokio_tcp::TcpStream;
|
|||||||
use super::connection::Connection;
|
use super::connection::Connection;
|
||||||
use super::error::ConnectError;
|
use super::error::ConnectError;
|
||||||
use super::pool::{ConnectionPool, Protocol};
|
use super::pool::{ConnectionPool, Protocol};
|
||||||
|
use super::Connect;
|
||||||
|
|
||||||
#[cfg(feature = "ssl")]
|
#[cfg(feature = "ssl")]
|
||||||
use openssl::ssl::SslConnector;
|
use openssl::ssl::SslConnector;
|
||||||
@ -46,6 +47,7 @@ pub struct Connector<T, U> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Connector<(), ()> {
|
impl Connector<(), ()> {
|
||||||
|
#[allow(clippy::new_ret_no_self)]
|
||||||
pub fn new() -> Connector<
|
pub fn new() -> Connector<
|
||||||
impl Service<
|
impl Service<
|
||||||
Request = TcpConnect<Uri>,
|
Request = TcpConnect<Uri>,
|
||||||
@ -113,7 +115,8 @@ where
|
|||||||
Request = TcpConnect<Uri>,
|
Request = TcpConnect<Uri>,
|
||||||
Response = TcpConnection<Uri, U>,
|
Response = TcpConnection<Uri, U>,
|
||||||
Error = actix_connect::ConnectError,
|
Error = actix_connect::ConnectError,
|
||||||
> + Clone,
|
> + Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
/// Connection timeout, i.e. max time to connect to remote host including dns name resolution.
|
/// Connection timeout, i.e. max time to connect to remote host including dns name resolution.
|
||||||
/// Set to 1 second by default.
|
/// Set to 1 second by default.
|
||||||
@ -177,15 +180,17 @@ where
|
|||||||
/// its combinator chain.
|
/// its combinator chain.
|
||||||
pub fn finish(
|
pub fn finish(
|
||||||
self,
|
self,
|
||||||
) -> impl Service<Request = Uri, Response = impl Connection, Error = ConnectError> + Clone
|
) -> impl Service<Request = Connect, Response = impl Connection, Error = ConnectError>
|
||||||
{
|
+ Clone {
|
||||||
#[cfg(not(feature = "ssl"))]
|
#[cfg(not(feature = "ssl"))]
|
||||||
{
|
{
|
||||||
let connector = TimeoutService::new(
|
let connector = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
apply_fn(self.connector, |msg: Uri, srv| srv.call(msg.into()))
|
apply_fn(self.connector, |msg: Connect, srv| {
|
||||||
.map_err(ConnectError::from)
|
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
})
|
||||||
|
.map_err(ConnectError::from)
|
||||||
|
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||||
)
|
)
|
||||||
.map_err(|e| match e {
|
.map_err(|e| match e {
|
||||||
TimeoutError::Service(e) => e,
|
TimeoutError::Service(e) => e,
|
||||||
@ -209,26 +214,28 @@ where
|
|||||||
|
|
||||||
let ssl_service = TimeoutService::new(
|
let ssl_service = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
apply_fn(self.connector.clone(), |msg: Uri, srv| srv.call(msg.into()))
|
apply_fn(self.connector.clone(), |msg: Connect, srv| {
|
||||||
.map_err(ConnectError::from)
|
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||||
.and_then(
|
})
|
||||||
OpensslConnector::service(self.ssl)
|
.map_err(ConnectError::from)
|
||||||
.map_err(ConnectError::from)
|
.and_then(
|
||||||
.map(|stream| {
|
OpensslConnector::service(self.ssl)
|
||||||
let sock = stream.into_parts().0;
|
.map_err(ConnectError::from)
|
||||||
let h2 = sock
|
.map(|stream| {
|
||||||
.get_ref()
|
let sock = stream.into_parts().0;
|
||||||
.ssl()
|
let h2 = sock
|
||||||
.selected_alpn_protocol()
|
.get_ref()
|
||||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
.ssl()
|
||||||
.unwrap_or(false);
|
.selected_alpn_protocol()
|
||||||
if h2 {
|
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||||
(sock, Protocol::Http2)
|
.unwrap_or(false);
|
||||||
} else {
|
if h2 {
|
||||||
(sock, Protocol::Http1)
|
(sock, Protocol::Http2)
|
||||||
}
|
} else {
|
||||||
}),
|
(sock, Protocol::Http1)
|
||||||
),
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.map_err(|e| match e {
|
.map_err(|e| match e {
|
||||||
TimeoutError::Service(e) => e,
|
TimeoutError::Service(e) => e,
|
||||||
@ -237,9 +244,11 @@ where
|
|||||||
|
|
||||||
let tcp_service = TimeoutService::new(
|
let tcp_service = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
apply_fn(self.connector.clone(), |msg: Uri, srv| srv.call(msg.into()))
|
apply_fn(self.connector.clone(), |msg: Connect, srv| {
|
||||||
.map_err(ConnectError::from)
|
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||||
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
})
|
||||||
|
.map_err(ConnectError::from)
|
||||||
|
.map(|stream| (stream.into_parts().0, Protocol::Http1)),
|
||||||
)
|
)
|
||||||
.map_err(|e| match e {
|
.map_err(|e| match e {
|
||||||
TimeoutError::Service(e) => e,
|
TimeoutError::Service(e) => e,
|
||||||
@ -264,15 +273,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
|
||||||
#[deprecated(since = "0.1.0-alpha4", note = "please use `.finish()` method")]
|
|
||||||
pub fn service(
|
|
||||||
self,
|
|
||||||
) -> impl Service<Request = Uri, Response = impl Connection, Error = ConnectError> + Clone
|
|
||||||
{
|
|
||||||
self.finish()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "ssl"))]
|
#[cfg(not(feature = "ssl"))]
|
||||||
@ -286,7 +286,9 @@ mod connect_impl {
|
|||||||
pub(crate) struct InnerConnector<T, Io>
|
pub(crate) struct InnerConnector<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
pub(crate) tcp_pool: ConnectionPool<T, Io>,
|
||||||
}
|
}
|
||||||
@ -294,8 +296,9 @@ mod connect_impl {
|
|||||||
impl<T, Io> Clone for InnerConnector<T, Io>
|
impl<T, Io> Clone for InnerConnector<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
InnerConnector {
|
InnerConnector {
|
||||||
@ -307,9 +310,11 @@ mod connect_impl {
|
|||||||
impl<T, Io> Service for InnerConnector<T, Io>
|
impl<T, Io> Service for InnerConnector<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
type Request = Uri;
|
type Request = Connect;
|
||||||
type Response = IoConnection<Io>;
|
type Response = IoConnection<Io>;
|
||||||
type Error = ConnectError;
|
type Error = ConnectError;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
@ -321,8 +326,8 @@ mod connect_impl {
|
|||||||
self.tcp_pool.poll_ready()
|
self.tcp_pool.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Uri) -> Self::Future {
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
match req.scheme_str() {
|
match req.uri.scheme_str() {
|
||||||
Some("https") | Some("wss") => {
|
Some("https") | Some("wss") => {
|
||||||
Either::B(err(ConnectError::SslIsNotSupported))
|
Either::B(err(ConnectError::SslIsNotSupported))
|
||||||
}
|
}
|
||||||
@ -346,8 +351,8 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>,
|
||||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>,
|
||||||
{
|
{
|
||||||
pub(crate) tcp_pool: ConnectionPool<T1, Io1>,
|
pub(crate) tcp_pool: ConnectionPool<T1, Io1>,
|
||||||
pub(crate) ssl_pool: ConnectionPool<T2, Io2>,
|
pub(crate) ssl_pool: ConnectionPool<T2, Io2>,
|
||||||
@ -357,10 +362,12 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
+ Clone,
|
+ Clone
|
||||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>
|
+ 'static,
|
||||||
+ Clone,
|
T2: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
InnerConnector {
|
InnerConnector {
|
||||||
@ -374,10 +381,14 @@ mod connect_impl {
|
|||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T1: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T1: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
T2: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
+ 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 Response = EitherConnection<Io1, Io2>;
|
||||||
type Error = ConnectError;
|
type Error = ConnectError;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
@ -392,8 +403,8 @@ mod connect_impl {
|
|||||||
self.tcp_pool.poll_ready()
|
self.tcp_pool.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Uri) -> Self::Future {
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
match req.scheme_str() {
|
match req.uri.scheme_str() {
|
||||||
Some("https") | Some("wss") => {
|
Some("https") | Some("wss") => {
|
||||||
Either::B(Either::B(InnerConnectorResponseB {
|
Either::B(Either::B(InnerConnectorResponseB {
|
||||||
fut: self.ssl_pool.call(req),
|
fut: self.ssl_pool.call(req),
|
||||||
@ -411,7 +422,9 @@ mod connect_impl {
|
|||||||
pub(crate) struct InnerConnectorResponseA<T, Io1, Io2>
|
pub(crate) struct InnerConnectorResponseA<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
fut: <ConnectionPool<T, Io1> as Service>::Future,
|
||||||
_t: PhantomData<Io2>,
|
_t: PhantomData<Io2>,
|
||||||
@ -419,7 +432,9 @@ mod connect_impl {
|
|||||||
|
|
||||||
impl<T, Io1, Io2> Future for InnerConnectorResponseA<T, Io1, Io2>
|
impl<T, Io1, Io2> Future for InnerConnectorResponseA<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
T: Service<Request = Uri, Response = (Io1, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io1, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
@ -437,7 +452,9 @@ mod connect_impl {
|
|||||||
pub(crate) struct InnerConnectorResponseB<T, Io1, Io2>
|
pub(crate) struct InnerConnectorResponseB<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
fut: <ConnectionPool<T, Io2> as Service>::Future,
|
||||||
_t: PhantomData<Io1>,
|
_t: PhantomData<Io1>,
|
||||||
@ -445,7 +462,9 @@ mod connect_impl {
|
|||||||
|
|
||||||
impl<T, Io1, Io2> Future for InnerConnectorResponseB<T, Io1, Io2>
|
impl<T, Io1, Io2> Future for InnerConnectorResponseB<T, Io1, Io2>
|
||||||
where
|
where
|
||||||
T: Service<Request = Uri, Response = (Io2, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io2, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
Io1: AsyncRead + AsyncWrite + 'static,
|
Io1: AsyncRead + AsyncWrite + 'static,
|
||||||
Io2: AsyncRead + AsyncWrite + 'static,
|
Io2: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
|
@ -274,7 +274,7 @@ impl<Io: ConnectionLifetime> Stream for PlStream<Io> {
|
|||||||
Ok(Async::Ready(Some(chunk)))
|
Ok(Async::Ready(Some(chunk)))
|
||||||
} else {
|
} else {
|
||||||
let framed = self.framed.take().unwrap();
|
let framed = self.framed.take().unwrap();
|
||||||
let force_close = framed.get_codec().keepalive();
|
let force_close = !framed.get_codec().keepalive();
|
||||||
release_connection(framed, force_close);
|
release_connection(framed, force_close);
|
||||||
Ok(Async::Ready(None))
|
Ok(Async::Ready(None))
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
//! Http client api
|
//! Http client api
|
||||||
|
use http::Uri;
|
||||||
|
|
||||||
mod connection;
|
mod connection;
|
||||||
mod connector;
|
mod connector;
|
||||||
mod error;
|
mod error;
|
||||||
@ -10,3 +12,9 @@ pub use self::connection::Connection;
|
|||||||
pub use self::connector::Connector;
|
pub use self::connector::Connector;
|
||||||
pub use self::error::{ConnectError, InvalidUrl, SendRequestError};
|
pub use self::error::{ConnectError, InvalidUrl, SendRequestError};
|
||||||
pub use self::pool::Protocol;
|
pub use self::pool::Protocol;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Connect {
|
||||||
|
pub uri: Uri,
|
||||||
|
pub addr: Option<std::net::SocketAddr>,
|
||||||
|
}
|
||||||
|
@ -13,13 +13,14 @@ use futures::unsync::oneshot;
|
|||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
use h2::client::{handshake, Handshake};
|
use h2::client::{handshake, Handshake};
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
use http::uri::{Authority, Uri};
|
use http::uri::Authority;
|
||||||
use indexmap::IndexSet;
|
use indexmap::IndexSet;
|
||||||
use slab::Slab;
|
use slab::Slab;
|
||||||
use tokio_timer::{sleep, Delay};
|
use tokio_timer::{sleep, Delay};
|
||||||
|
|
||||||
use super::connection::{ConnectionType, IoConnection};
|
use super::connection::{ConnectionType, IoConnection};
|
||||||
use super::error::ConnectError;
|
use super::error::ConnectError;
|
||||||
|
use super::Connect;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq)]
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
/// Protocol version
|
/// Protocol version
|
||||||
@ -48,7 +49,9 @@ pub(crate) struct ConnectionPool<T, Io: AsyncRead + AsyncWrite + 'static>(
|
|||||||
impl<T, Io> ConnectionPool<T, Io>
|
impl<T, Io> ConnectionPool<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
connector: T,
|
connector: T,
|
||||||
@ -68,7 +71,7 @@ where
|
|||||||
waiters: Slab::new(),
|
waiters: Slab::new(),
|
||||||
waiters_queue: IndexSet::new(),
|
waiters_queue: IndexSet::new(),
|
||||||
available: HashMap::new(),
|
available: HashMap::new(),
|
||||||
task: AtomicTask::new(),
|
task: None,
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -87,9 +90,11 @@ where
|
|||||||
impl<T, Io> Service for ConnectionPool<T, Io>
|
impl<T, Io> Service for ConnectionPool<T, Io>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite + 'static,
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
T: Service<Request = Uri, Response = (Io, Protocol), Error = ConnectError>,
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>
|
||||||
|
+ Clone
|
||||||
|
+ 'static,
|
||||||
{
|
{
|
||||||
type Request = Uri;
|
type Request = Connect;
|
||||||
type Response = IoConnection<Io>;
|
type Response = IoConnection<Io>;
|
||||||
type Error = ConnectError;
|
type Error = ConnectError;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
@ -101,8 +106,8 @@ where
|
|||||||
self.0.poll_ready()
|
self.0.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Uri) -> Self::Future {
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
let key = if let Some(authority) = req.authority_part() {
|
let key = if let Some(authority) = req.uri.authority_part() {
|
||||||
authority.clone().into()
|
authority.clone().into()
|
||||||
} else {
|
} else {
|
||||||
return Either::A(err(ConnectError::Unresolverd));
|
return Either::A(err(ConnectError::Unresolverd));
|
||||||
@ -112,31 +117,41 @@ where
|
|||||||
match self.1.as_ref().borrow_mut().acquire(&key) {
|
match self.1.as_ref().borrow_mut().acquire(&key) {
|
||||||
Acquire::Acquired(io, created) => {
|
Acquire::Acquired(io, created) => {
|
||||||
// use existing connection
|
// use existing connection
|
||||||
Either::A(ok(IoConnection::new(
|
return Either::A(ok(IoConnection::new(
|
||||||
io,
|
io,
|
||||||
created,
|
created,
|
||||||
Some(Acquired(key, Some(self.1.clone()))),
|
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 => {
|
Acquire::Available => {
|
||||||
// open new connection
|
// open new connection
|
||||||
Either::B(Either::B(OpenConnection::new(
|
return Either::B(Either::B(OpenConnection::new(
|
||||||
key,
|
key,
|
||||||
self.1.clone(),
|
self.1.clone(),
|
||||||
self.0.call(req),
|
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(
|
Ok(Async::Ready(IoConnection::new(
|
||||||
ConnectionType::H2(snd),
|
ConnectionType::H2(snd),
|
||||||
Instant::now(),
|
Instant::now(),
|
||||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
@ -255,12 +270,11 @@ where
|
|||||||
match self.fut.poll() {
|
match self.fut.poll() {
|
||||||
Err(err) => Err(err),
|
Err(err) => Err(err),
|
||||||
Ok(Async::Ready((io, proto))) => {
|
Ok(Async::Ready((io, proto))) => {
|
||||||
let _ = self.inner.take();
|
|
||||||
if proto == Protocol::Http1 {
|
if proto == Protocol::Http1 {
|
||||||
Ok(Async::Ready(IoConnection::new(
|
Ok(Async::Ready(IoConnection::new(
|
||||||
ConnectionType::H1(io),
|
ConnectionType::H1(io),
|
||||||
Instant::now(),
|
Instant::now(),
|
||||||
Some(Acquired(self.key.clone(), self.inner.clone())),
|
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||||
)))
|
)))
|
||||||
} else {
|
} else {
|
||||||
self.h2 = Some(handshake(io));
|
self.h2 = Some(handshake(io));
|
||||||
@ -278,7 +292,6 @@ enum Acquire<T> {
|
|||||||
NotAvailable,
|
NotAvailable,
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[derive(Debug)]
|
|
||||||
struct AvailableConnection<Io> {
|
struct AvailableConnection<Io> {
|
||||||
io: ConnectionType<Io>,
|
io: ConnectionType<Io>,
|
||||||
used: Instant,
|
used: Instant,
|
||||||
@ -292,9 +305,12 @@ pub(crate) struct Inner<Io> {
|
|||||||
limit: usize,
|
limit: usize,
|
||||||
acquired: usize,
|
acquired: usize,
|
||||||
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
||||||
waiters: Slab<(Uri, oneshot::Sender<Result<IoConnection<Io>, ConnectError>>)>,
|
waiters: Slab<(
|
||||||
|
Connect,
|
||||||
|
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||||
|
)>,
|
||||||
waiters_queue: IndexSet<(Key, usize)>,
|
waiters_queue: IndexSet<(Key, usize)>,
|
||||||
task: AtomicTask,
|
task: Option<AtomicTask>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io> Inner<Io> {
|
impl<Io> Inner<Io> {
|
||||||
@ -310,18 +326,6 @@ impl<Io> Inner<Io> {
|
|||||||
self.waiters.remove(token);
|
self.waiters.remove(token);
|
||||||
self.waiters_queue.remove(&(key.clone(), token));
|
self.waiters_queue.remove(&(key.clone(), token));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
|
||||||
self.acquired -= 1;
|
|
||||||
self.available
|
|
||||||
.entry(key.clone())
|
|
||||||
.or_insert_with(VecDeque::new)
|
|
||||||
.push_back(AvailableConnection {
|
|
||||||
io,
|
|
||||||
created,
|
|
||||||
used: Instant::now(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Io> Inner<Io>
|
impl<Io> Inner<Io>
|
||||||
@ -331,19 +335,21 @@ where
|
|||||||
/// connection is not available, wait
|
/// connection is not available, wait
|
||||||
fn wait_for(
|
fn wait_for(
|
||||||
&mut self,
|
&mut self,
|
||||||
connect: Uri,
|
connect: Connect,
|
||||||
) -> (
|
) -> (
|
||||||
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
oneshot::Receiver<Result<IoConnection<Io>, ConnectError>>,
|
||||||
usize,
|
usize,
|
||||||
|
bool,
|
||||||
) {
|
) {
|
||||||
let (tx, rx) = oneshot::channel();
|
let (tx, rx) = oneshot::channel();
|
||||||
|
|
||||||
let key: Key = connect.authority_part().unwrap().clone().into();
|
let key: Key = connect.uri.authority_part().unwrap().clone().into();
|
||||||
let entry = self.waiters.vacant_entry();
|
let entry = self.waiters.vacant_entry();
|
||||||
let token = entry.key();
|
let token = entry.key();
|
||||||
entry.insert((connect, tx));
|
entry.insert((connect, tx));
|
||||||
assert!(!self.waiters_queue.insert((key, token)));
|
assert!(self.waiters_queue.insert((key, token)));
|
||||||
(rx, token)
|
|
||||||
|
(rx, token, self.task.is_some())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn acquire(&mut self, key: &Key) -> Acquire<Io> {
|
fn acquire(&mut self, key: &Key) -> Acquire<Io> {
|
||||||
@ -396,6 +402,19 @@ where
|
|||||||
Acquire::Available
|
Acquire::Available
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn release_conn(&mut self, key: &Key, io: ConnectionType<Io>, created: Instant) {
|
||||||
|
self.acquired -= 1;
|
||||||
|
self.available
|
||||||
|
.entry(key.clone())
|
||||||
|
.or_insert_with(VecDeque::new)
|
||||||
|
.push_back(AvailableConnection {
|
||||||
|
io,
|
||||||
|
created,
|
||||||
|
used: Instant::now(),
|
||||||
|
});
|
||||||
|
self.check_availibility();
|
||||||
|
}
|
||||||
|
|
||||||
fn release_close(&mut self, io: ConnectionType<Io>) {
|
fn release_close(&mut self, io: ConnectionType<Io>) {
|
||||||
self.acquired -= 1;
|
self.acquired -= 1;
|
||||||
if let Some(timeout) = self.disconnect_timeout {
|
if let Some(timeout) = self.disconnect_timeout {
|
||||||
@ -403,11 +422,14 @@ where
|
|||||||
tokio_current_thread::spawn(CloseConnection::new(io, timeout))
|
tokio_current_thread::spawn(CloseConnection::new(io, timeout))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.check_availibility();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_availibility(&self) {
|
fn check_availibility(&self) {
|
||||||
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
||||||
self.task.notify()
|
if let Some(t) = self.task.as_ref() {
|
||||||
|
t.notify()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -447,6 +469,147 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ConnectorPoolSupport<T, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
connector: T,
|
||||||
|
inner: Rc<RefCell<Inner<Io>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, Io> Future for ConnectorPoolSupport<T, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
T: Service<Request = Connect, Response = (Io, Protocol), Error = ConnectError>,
|
||||||
|
T::Future: 'static,
|
||||||
|
{
|
||||||
|
type Item = ();
|
||||||
|
type Error = ();
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
let mut inner = self.inner.as_ref().borrow_mut();
|
||||||
|
inner.task.as_ref().unwrap().register();
|
||||||
|
|
||||||
|
// check waiters
|
||||||
|
loop {
|
||||||
|
let (key, token) = {
|
||||||
|
if let Some((key, token)) = inner.waiters_queue.get_index(0) {
|
||||||
|
(key.clone(), *token)
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match inner.acquire(&key) {
|
||||||
|
Acquire::NotAvailable => break,
|
||||||
|
Acquire::Acquired(io, created) => {
|
||||||
|
let (_, tx) = inner.waiters.remove(token);
|
||||||
|
if let Err(conn) = tx.send(Ok(IoConnection::new(
|
||||||
|
io,
|
||||||
|
created,
|
||||||
|
Some(Acquired(key.clone(), Some(self.inner.clone()))),
|
||||||
|
))) {
|
||||||
|
let (io, created) = conn.unwrap().into_inner();
|
||||||
|
inner.release_conn(&key, io, created);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Acquire::Available => {
|
||||||
|
let (connect, tx) = inner.waiters.remove(token);
|
||||||
|
OpenWaitingConnection::spawn(
|
||||||
|
key.clone(),
|
||||||
|
tx,
|
||||||
|
self.inner.clone(),
|
||||||
|
self.connector.call(connect),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = inner.waiters_queue.swap_remove_index(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Async::NotReady)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
fut: F,
|
||||||
|
key: Key,
|
||||||
|
h2: Option<Handshake<Io, Bytes>>,
|
||||||
|
rx: Option<oneshot::Sender<Result<IoConnection<Io>, ConnectError>>>,
|
||||||
|
inner: Option<Rc<RefCell<Inner<Io>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, Io> OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
F: Future<Item = (Io, Protocol), Error = ConnectError> + 'static,
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
fn spawn(
|
||||||
|
key: Key,
|
||||||
|
rx: oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||||
|
inner: Rc<RefCell<Inner<Io>>>,
|
||||||
|
fut: F,
|
||||||
|
) {
|
||||||
|
tokio_current_thread::spawn(OpenWaitingConnection {
|
||||||
|
key,
|
||||||
|
fut,
|
||||||
|
h2: None,
|
||||||
|
rx: Some(rx),
|
||||||
|
inner: Some(inner),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, Io> Drop for OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
Io: AsyncRead + AsyncWrite + 'static,
|
||||||
|
{
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(inner) = self.inner.take() {
|
||||||
|
let mut inner = inner.as_ref().borrow_mut();
|
||||||
|
inner.release();
|
||||||
|
inner.check_availibility();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, Io> Future for OpenWaitingConnection<F, Io>
|
||||||
|
where
|
||||||
|
F: Future<Item = (Io, Protocol), Error = ConnectError>,
|
||||||
|
Io: AsyncRead + AsyncWrite,
|
||||||
|
{
|
||||||
|
type Item = ();
|
||||||
|
type Error = ();
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
match self.fut.poll() {
|
||||||
|
Err(err) => {
|
||||||
|
let _ = self.inner.take();
|
||||||
|
if let Some(rx) = self.rx.take() {
|
||||||
|
let _ = rx.send(Err(err));
|
||||||
|
}
|
||||||
|
Err(())
|
||||||
|
}
|
||||||
|
Ok(Async::Ready((io, proto))) => {
|
||||||
|
if proto == Protocol::Http1 {
|
||||||
|
let rx = self.rx.take().unwrap();
|
||||||
|
let _ = rx.send(Ok(IoConnection::new(
|
||||||
|
ConnectionType::H1(io),
|
||||||
|
Instant::now(),
|
||||||
|
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||||
|
)));
|
||||||
|
Ok(Async::Ready(()))
|
||||||
|
} else {
|
||||||
|
self.h2 = Some(handshake(io));
|
||||||
|
self.poll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) struct Acquired<T>(Key, Option<Rc<RefCell<Inner<T>>>>);
|
pub(crate) struct Acquired<T>(Key, Option<Rc<RefCell<Inner<T>>>>);
|
||||||
|
|
||||||
impl<T> Acquired<T>
|
impl<T> Acquired<T>
|
||||||
|
42
actix-http/src/cloneable.rs
Normal file
42
actix-http/src/cloneable.rs
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
use std::cell::UnsafeCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use actix_service::Service;
|
||||||
|
use futures::Poll;
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
/// Service that allows to turn non-clone service to a service with `Clone` impl
|
||||||
|
pub(crate) struct CloneableService<T>(Rc<UnsafeCell<T>>);
|
||||||
|
|
||||||
|
impl<T> CloneableService<T> {
|
||||||
|
pub(crate) fn new(service: T) -> Self
|
||||||
|
where
|
||||||
|
T: Service,
|
||||||
|
{
|
||||||
|
Self(Rc::new(UnsafeCell::new(service)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Clone for CloneableService<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Service for CloneableService<T>
|
||||||
|
where
|
||||||
|
T: Service,
|
||||||
|
{
|
||||||
|
type Request = T::Request;
|
||||||
|
type Response = T::Response;
|
||||||
|
type Error = T::Error;
|
||||||
|
type Future = T::Future;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
|
unsafe { &mut *self.0.as_ref().get() }.poll_ready()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: T::Request) -> Self::Future {
|
||||||
|
unsafe { &mut *self.0.as_ref().get() }.call(req)
|
||||||
|
}
|
||||||
|
}
|
@ -158,7 +158,8 @@ impl ServiceConfig {
|
|||||||
self.0.timer.now()
|
self.0.timer.now()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn set_date(&self, dst: &mut BytesMut) {
|
#[doc(hidden)]
|
||||||
|
pub fn set_date(&self, dst: &mut BytesMut) {
|
||||||
let mut buf: [u8; 39] = [0; 39];
|
let mut buf: [u8; 39] = [0; 39];
|
||||||
buf[..6].copy_from_slice(b"date: ");
|
buf[..6].copy_from_slice(b"date: ");
|
||||||
buf[6..35].copy_from_slice(&self.0.timer.date().bytes);
|
buf[6..35].copy_from_slice(&self.0.timer.date().bytes);
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
|
|
||||||
use time::{Duration, Tm};
|
use chrono::Duration;
|
||||||
|
use time::Tm;
|
||||||
|
|
||||||
use super::{Cookie, SameSite};
|
use super::{Cookie, SameSite};
|
||||||
|
|
||||||
@ -16,7 +17,6 @@ use super::{Cookie, SameSite};
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let cookie: Cookie = Cookie::build("name", "value")
|
/// let cookie: Cookie = Cookie::build("name", "value")
|
||||||
@ -24,7 +24,7 @@ use super::{Cookie, SameSite};
|
|||||||
/// .path("/")
|
/// .path("/")
|
||||||
/// .secure(true)
|
/// .secure(true)
|
||||||
/// .http_only(true)
|
/// .http_only(true)
|
||||||
/// .max_age(Duration::days(1))
|
/// .max_age(84600)
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
@ -79,6 +79,26 @@ impl CookieBuilder {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets the `max_age` field in seconds in the cookie being built.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_http::cookie::Cookie;
|
||||||
|
///
|
||||||
|
/// # fn main() {
|
||||||
|
/// let c = Cookie::build("foo", "bar")
|
||||||
|
/// .max_age(1800)
|
||||||
|
/// .finish();
|
||||||
|
///
|
||||||
|
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
#[inline]
|
||||||
|
pub fn max_age(self, seconds: i64) -> CookieBuilder {
|
||||||
|
self.max_age_time(Duration::seconds(seconds))
|
||||||
|
}
|
||||||
|
|
||||||
/// Sets the `max_age` field in the cookie being built.
|
/// Sets the `max_age` field in the cookie being built.
|
||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
@ -88,14 +108,14 @@ impl CookieBuilder {
|
|||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let c = Cookie::build("foo", "bar")
|
/// let c = Cookie::build("foo", "bar")
|
||||||
/// .max_age(time::Duration::minutes(30))
|
/// .max_age_time(time::Duration::minutes(30))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
///
|
///
|
||||||
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
|
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn max_age(mut self, value: Duration) -> CookieBuilder {
|
pub fn max_age_time(mut self, value: Duration) -> CookieBuilder {
|
||||||
self.cookie.set_max_age(value);
|
self.cookie.set_max_age(value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@ -200,7 +220,7 @@ impl CookieBuilder {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let c = Cookie::build("foo", "bar")
|
/// let c = Cookie::build("foo", "bar")
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::mem::replace;
|
use std::mem::replace;
|
||||||
|
|
||||||
use time::{self, Duration};
|
use chrono::Duration;
|
||||||
|
|
||||||
use super::delta::DeltaCookie;
|
use super::delta::DeltaCookie;
|
||||||
use super::Cookie;
|
use super::Cookie;
|
||||||
@ -188,7 +188,7 @@ impl CookieJar {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::{CookieJar, Cookie};
|
/// use actix_http::cookie::{CookieJar, Cookie};
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut jar = CookieJar::new();
|
/// let mut jar = CookieJar::new();
|
||||||
@ -241,7 +241,7 @@ impl CookieJar {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::{CookieJar, Cookie};
|
/// use actix_http::cookie::{CookieJar, Cookie};
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut jar = CookieJar::new();
|
/// let mut jar = CookieJar::new();
|
||||||
@ -537,8 +537,8 @@ mod test {
|
|||||||
#[test]
|
#[test]
|
||||||
#[cfg(feature = "secure-cookies")]
|
#[cfg(feature = "secure-cookies")]
|
||||||
fn delta() {
|
fn delta() {
|
||||||
|
use chrono::Duration;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
let mut c = CookieJar::new();
|
let mut c = CookieJar::new();
|
||||||
|
|
||||||
|
@ -65,8 +65,9 @@ use std::borrow::Cow;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use chrono::Duration;
|
||||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||||
use time::{Duration, Tm};
|
use time::Tm;
|
||||||
|
|
||||||
pub use self::builder::CookieBuilder;
|
pub use self::builder::CookieBuilder;
|
||||||
pub use self::draft::*;
|
pub use self::draft::*;
|
||||||
@ -103,6 +104,7 @@ impl CookieStr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::ptr_arg)]
|
||||||
fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> {
|
fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> {
|
||||||
match *self {
|
match *self {
|
||||||
CookieStr::Indexed(i, j) => match *string {
|
CookieStr::Indexed(i, j) => match *string {
|
||||||
@ -624,7 +626,7 @@ impl<'c> Cookie<'c> {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut c = Cookie::new("name", "value");
|
/// let mut c = Cookie::new("name", "value");
|
||||||
@ -703,7 +705,7 @@ impl<'c> Cookie<'c> {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::cookie::Cookie;
|
/// use actix_http::cookie::Cookie;
|
||||||
/// use time::Duration;
|
/// use chrono::Duration;
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let mut c = Cookie::new("foo", "bar");
|
/// let mut c = Cookie::new("foo", "bar");
|
||||||
@ -977,7 +979,7 @@ impl<'a, 'b> PartialEq<Cookie<'b>> for Cookie<'a> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{Cookie, SameSite};
|
use super::{Cookie, SameSite};
|
||||||
use time::{strptime, Duration};
|
use time::strptime;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn format() {
|
fn format() {
|
||||||
@ -987,9 +989,7 @@ mod tests {
|
|||||||
let cookie = Cookie::build("foo", "bar").http_only(true).finish();
|
let cookie = Cookie::build("foo", "bar").http_only(true).finish();
|
||||||
assert_eq!(&cookie.to_string(), "foo=bar; HttpOnly");
|
assert_eq!(&cookie.to_string(), "foo=bar; HttpOnly");
|
||||||
|
|
||||||
let cookie = Cookie::build("foo", "bar")
|
let cookie = Cookie::build("foo", "bar").max_age(10).finish();
|
||||||
.max_age(Duration::seconds(10))
|
|
||||||
.finish();
|
|
||||||
assert_eq!(&cookie.to_string(), "foo=bar; Max-Age=10");
|
assert_eq!(&cookie.to_string(), "foo=bar; Max-Age=10");
|
||||||
|
|
||||||
let cookie = Cookie::build("foo", "bar").secure(true).finish();
|
let cookie = Cookie::build("foo", "bar").secure(true).finish();
|
||||||
|
@ -5,8 +5,8 @@ use std::error::Error;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::str::Utf8Error;
|
use std::str::Utf8Error;
|
||||||
|
|
||||||
|
use chrono::Duration;
|
||||||
use percent_encoding::percent_decode;
|
use percent_encoding::percent_decode;
|
||||||
use time::{self, Duration};
|
|
||||||
|
|
||||||
use super::{Cookie, CookieStr, SameSite};
|
use super::{Cookie, CookieStr, SameSite};
|
||||||
|
|
||||||
@ -220,7 +220,8 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{Cookie, SameSite};
|
use super::{Cookie, SameSite};
|
||||||
use time::{strptime, Duration};
|
use chrono::Duration;
|
||||||
|
use time::strptime;
|
||||||
|
|
||||||
macro_rules! assert_eq_parse {
|
macro_rules! assert_eq_parse {
|
||||||
($string:expr, $expected:expr) => {
|
($string:expr, $expected:expr) => {
|
||||||
@ -418,9 +419,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn do_not_panic_on_large_max_ages() {
|
fn do_not_panic_on_large_max_ages() {
|
||||||
let max_seconds = Duration::max_value().num_seconds();
|
let max_seconds = Duration::max_value().num_seconds();
|
||||||
let expected = Cookie::build("foo", "bar")
|
let expected = Cookie::build("foo", "bar").max_age(max_seconds).finish();
|
||||||
.max_age(Duration::seconds(max_seconds))
|
|
||||||
.finish();
|
|
||||||
assert_eq_parse!(format!(" foo=bar; Max-Age={:?}", max_seconds + 1), expected);
|
assert_eq_parse!(format!(" foo=bar; Max-Age={:?}", max_seconds + 1), expected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ use super::private::KEY_LEN as PRIVATE_KEY_LEN;
|
|||||||
use super::signed::KEY_LEN as SIGNED_KEY_LEN;
|
use super::signed::KEY_LEN as SIGNED_KEY_LEN;
|
||||||
|
|
||||||
static HKDF_DIGEST: &'static Algorithm = &SHA256;
|
static HKDF_DIGEST: &'static Algorithm = &SHA256;
|
||||||
const KEYS_INFO: &'static str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
|
const KEYS_INFO: &str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
|
||||||
|
|
||||||
/// A cryptographic master key for use with `Signed` and/or `Private` jars.
|
/// A cryptographic master key for use with `Signed` and/or `Private` jars.
|
||||||
///
|
///
|
||||||
|
@ -33,6 +33,7 @@ impl<B: MessageBody> Encoder<B> {
|
|||||||
) -> ResponseBody<Encoder<B>> {
|
) -> ResponseBody<Encoder<B>> {
|
||||||
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
||||||
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|
||||||
|
|| head.status == StatusCode::NO_CONTENT
|
||||||
|| encoding == ContentEncoding::Identity
|
|| encoding == ContentEncoding::Identity
|
||||||
|| encoding == ContentEncoding::Auto);
|
|| encoding == ContentEncoding::Auto);
|
||||||
|
|
||||||
|
@ -137,7 +137,7 @@ impl<E: ResponseError> ResponseError for TimeoutError<E> {
|
|||||||
#[display(fmt = "UnknownError")]
|
#[display(fmt = "UnknownError")]
|
||||||
struct UnitError;
|
struct UnitError;
|
||||||
|
|
||||||
/// `InternalServerError` for `JsonError`
|
/// `InternalServerError` for `UnitError`
|
||||||
impl ResponseError for UnitError {}
|
impl ResponseError for UnitError {}
|
||||||
|
|
||||||
/// `InternalServerError` for `JsonError`
|
/// `InternalServerError` for `JsonError`
|
||||||
@ -150,11 +150,11 @@ impl ResponseError for FormError {}
|
|||||||
impl ResponseError for TimerError {}
|
impl ResponseError for TimerError {}
|
||||||
|
|
||||||
#[cfg(feature = "ssl")]
|
#[cfg(feature = "ssl")]
|
||||||
/// `InternalServerError` for `SslError`
|
/// `InternalServerError` for `openssl::ssl::Error`
|
||||||
impl ResponseError for openssl::ssl::Error {}
|
impl ResponseError for openssl::ssl::Error {}
|
||||||
|
|
||||||
#[cfg(feature = "ssl")]
|
#[cfg(feature = "ssl")]
|
||||||
/// `InternalServerError` for `SslError`
|
/// `InternalServerError` for `openssl::ssl::HandshakeError`
|
||||||
impl ResponseError for openssl::ssl::HandshakeError<tokio_tcp::TcpStream> {}
|
impl ResponseError for openssl::ssl::HandshakeError<tokio_tcp::TcpStream> {}
|
||||||
|
|
||||||
/// Return `BAD_REQUEST` for `de::value::Error`
|
/// Return `BAD_REQUEST` for `de::value::Error`
|
||||||
|
@ -31,7 +31,7 @@ const AVERAGE_HEADER_SIZE: usize = 30;
|
|||||||
|
|
||||||
/// HTTP/1 Codec
|
/// HTTP/1 Codec
|
||||||
pub struct Codec {
|
pub struct Codec {
|
||||||
pub(crate) config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
decoder: decoder::MessageDecoder<Request>,
|
decoder: decoder::MessageDecoder<Request>,
|
||||||
payload: Option<PayloadDecoder>,
|
payload: Option<PayloadDecoder>,
|
||||||
version: Version,
|
version: Version,
|
||||||
@ -104,6 +104,11 @@ impl Codec {
|
|||||||
MessageType::Payload
|
MessageType::Payload
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn config(&self) -> &ServiceConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Decoder for Codec {
|
impl Decoder for Codec {
|
||||||
|
@ -300,7 +300,13 @@ impl MessageType for ResponseHead {
|
|||||||
error!("MAX_BUFFER_SIZE unprocessed data reached, closing");
|
error!("MAX_BUFFER_SIZE unprocessed data reached, closing");
|
||||||
return Err(ParseError::TooLarge);
|
return Err(ParseError::TooLarge);
|
||||||
} else {
|
} else {
|
||||||
PayloadType::None
|
// for HTTP/1.0 read to eof and close connection
|
||||||
|
if msg.version == Version::HTTP_10 {
|
||||||
|
msg.set_connection_type(ConnectionType::Close);
|
||||||
|
PayloadType::Payload(PayloadDecoder::eof())
|
||||||
|
} else {
|
||||||
|
PayloadType::None
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Some((msg, decoder)))
|
Ok(Some((msg, decoder)))
|
||||||
@ -331,7 +337,7 @@ impl HeaderIndex {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
/// Http payload item
|
/// Http payload item
|
||||||
pub enum PayloadItem {
|
pub enum PayloadItem {
|
||||||
Chunk(Bytes),
|
Chunk(Bytes),
|
||||||
@ -1191,4 +1197,16 @@ mod tests {
|
|||||||
let msg = pl.decode(&mut buf).unwrap().unwrap();
|
let msg = pl.decode(&mut buf).unwrap().unwrap();
|
||||||
assert!(msg.eof());
|
assert!(msg.eof());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_response_http10_read_until_eof() {
|
||||||
|
let mut buf = BytesMut::from(&"HTTP/1.0 200 Ok\r\n\r\ntest data"[..]);
|
||||||
|
|
||||||
|
let mut reader = MessageDecoder::<ResponseHead>::default();
|
||||||
|
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
|
||||||
|
let mut pl = pl.unwrap();
|
||||||
|
|
||||||
|
let chunk = pl.decode(&mut buf).unwrap().unwrap();
|
||||||
|
assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"test data")));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,6 @@ use std::{fmt, io, net};
|
|||||||
use actix_codec::{Decoder, Encoder, Framed, FramedParts};
|
use actix_codec::{Decoder, Encoder, Framed, FramedParts};
|
||||||
use actix_server_config::IoStream;
|
use actix_server_config::IoStream;
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{BufMut, BytesMut};
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
@ -13,9 +12,12 @@ use log::{error, trace};
|
|||||||
use tokio_timer::Delay;
|
use tokio_timer::Delay;
|
||||||
|
|
||||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::ServiceConfig;
|
use crate::config::ServiceConfig;
|
||||||
use crate::error::{DispatchError, Error};
|
use crate::error::{DispatchError, Error};
|
||||||
use crate::error::{ParseError, PayloadError};
|
use crate::error::{ParseError, PayloadError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
|
use crate::httpmessage::HttpMessage;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
|
|
||||||
@ -81,6 +83,7 @@ where
|
|||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
flags: Flags,
|
flags: Flags,
|
||||||
peer_addr: Option<net::SocketAddr>,
|
peer_addr: Option<net::SocketAddr>,
|
||||||
error: Option<DispatchError>,
|
error: Option<DispatchError>,
|
||||||
@ -174,12 +177,13 @@ where
|
|||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
/// Create http/1 dispatcher.
|
/// Create http/1 dispatcher.
|
||||||
pub fn new(
|
pub(crate) fn new(
|
||||||
stream: T,
|
stream: T,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Dispatcher::with_timeout(
|
Dispatcher::with_timeout(
|
||||||
stream,
|
stream,
|
||||||
@ -190,11 +194,12 @@ where
|
|||||||
service,
|
service,
|
||||||
expect,
|
expect,
|
||||||
upgrade,
|
upgrade,
|
||||||
|
on_connect,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create http/1 dispatcher with slow request timeout.
|
/// Create http/1 dispatcher with slow request timeout.
|
||||||
pub fn with_timeout(
|
pub(crate) fn with_timeout(
|
||||||
io: T,
|
io: T,
|
||||||
codec: Codec,
|
codec: Codec,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
@ -203,6 +208,7 @@ where
|
|||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let keepalive = config.keep_alive_enabled();
|
let keepalive = config.keep_alive_enabled();
|
||||||
let flags = if keepalive {
|
let flags = if keepalive {
|
||||||
@ -234,6 +240,7 @@ where
|
|||||||
service,
|
service,
|
||||||
expect,
|
expect,
|
||||||
upgrade,
|
upgrade,
|
||||||
|
on_connect,
|
||||||
flags,
|
flags,
|
||||||
ka_expire,
|
ka_expire,
|
||||||
ka_timer,
|
ka_timer,
|
||||||
@ -495,6 +502,11 @@ where
|
|||||||
let pl = self.codec.message_type();
|
let pl = self.codec.message_type();
|
||||||
req.head_mut().peer_addr = self.peer_addr;
|
req.head_mut().peer_addr = self.peer_addr;
|
||||||
|
|
||||||
|
// on_connect data
|
||||||
|
if let Some(ref on_connect) = self.on_connect {
|
||||||
|
on_connect.set(&mut req.extensions_mut());
|
||||||
|
}
|
||||||
|
|
||||||
if pl == MessageType::Stream && self.upgrade.is_some() {
|
if pl == MessageType::Stream && self.upgrade.is_some() {
|
||||||
self.messages.push_back(DispatcherMessage::Upgrade(req));
|
self.messages.push_back(DispatcherMessage::Upgrade(req));
|
||||||
break;
|
break;
|
||||||
@ -567,7 +579,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
if updated && self.ka_timer.is_some() {
|
if updated && self.ka_timer.is_some() {
|
||||||
if let Some(expire) = self.codec.config.keep_alive_expire() {
|
if let Some(expire) = self.codec.config().keep_alive_expire() {
|
||||||
self.ka_expire = expire;
|
self.ka_expire = expire;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -579,10 +591,13 @@ where
|
|||||||
if self.ka_timer.is_none() {
|
if self.ka_timer.is_none() {
|
||||||
// shutdown timeout
|
// shutdown timeout
|
||||||
if self.flags.contains(Flags::SHUTDOWN) {
|
if self.flags.contains(Flags::SHUTDOWN) {
|
||||||
if let Some(interval) = self.codec.config.client_disconnect_timer() {
|
if let Some(interval) = self.codec.config().client_disconnect_timer() {
|
||||||
self.ka_timer = Some(Delay::new(interval));
|
self.ka_timer = Some(Delay::new(interval));
|
||||||
} else {
|
} else {
|
||||||
self.flags.insert(Flags::READ_DISCONNECT);
|
self.flags.insert(Flags::READ_DISCONNECT);
|
||||||
|
if let Some(mut payload) = self.payload.take() {
|
||||||
|
payload.set_error(PayloadError::Incomplete(None));
|
||||||
|
}
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -607,7 +622,7 @@ where
|
|||||||
|
|
||||||
// start shutdown timer
|
// start shutdown timer
|
||||||
if let Some(deadline) =
|
if let Some(deadline) =
|
||||||
self.codec.config.client_disconnect_timer()
|
self.codec.config().client_disconnect_timer()
|
||||||
{
|
{
|
||||||
if let Some(timer) = self.ka_timer.as_mut() {
|
if let Some(timer) = self.ka_timer.as_mut() {
|
||||||
timer.reset(deadline);
|
timer.reset(deadline);
|
||||||
@ -632,7 +647,8 @@ where
|
|||||||
self.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
|
self.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
|
||||||
self.state = State::None;
|
self.state = State::None;
|
||||||
}
|
}
|
||||||
} else if let Some(deadline) = self.codec.config.keep_alive_expire()
|
} else if let Some(deadline) =
|
||||||
|
self.codec.config().keep_alive_expire()
|
||||||
{
|
{
|
||||||
if let Some(timer) = self.ka_timer.as_mut() {
|
if let Some(timer) = self.ka_timer.as_mut() {
|
||||||
timer.reset(deadline);
|
timer.reset(deadline);
|
||||||
@ -689,15 +705,21 @@ where
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// read socket into a buf
|
// read socket into a buf
|
||||||
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
let should_disconnect =
|
||||||
if let Some(true) =
|
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||||
read_available(&mut inner.io, &mut inner.read_buf)?
|
read_available(&mut inner.io, &mut inner.read_buf)?
|
||||||
{
|
} else {
|
||||||
inner.flags.insert(Flags::READ_DISCONNECT)
|
None
|
||||||
}
|
};
|
||||||
}
|
|
||||||
|
|
||||||
inner.poll_request()?;
|
inner.poll_request()?;
|
||||||
|
if let Some(true) = should_disconnect {
|
||||||
|
inner.flags.insert(Flags::READ_DISCONNECT);
|
||||||
|
if let Some(mut payload) = inner.payload.take() {
|
||||||
|
payload.feed_eof();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if inner.write_buf.remaining_mut() < LW_BUFFER_SIZE {
|
if inner.write_buf.remaining_mut() < LW_BUFFER_SIZE {
|
||||||
inner.write_buf.reserve(HW_BUFFER_SIZE);
|
inner.write_buf.reserve(HW_BUFFER_SIZE);
|
||||||
@ -841,6 +863,7 @@ mod tests {
|
|||||||
),
|
),
|
||||||
CloneableService::new(ExpectHandler),
|
CloneableService::new(ExpectHandler),
|
||||||
None,
|
None,
|
||||||
|
None,
|
||||||
);
|
);
|
||||||
assert!(h1.poll().is_err());
|
assert!(h1.poll().is_err());
|
||||||
|
|
||||||
|
@ -43,6 +43,10 @@ pub(crate) trait MessageType: Sized {
|
|||||||
|
|
||||||
fn headers(&self) -> &HeaderMap;
|
fn headers(&self) -> &HeaderMap;
|
||||||
|
|
||||||
|
fn camel_case(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
fn chunked(&self) -> bool;
|
fn chunked(&self) -> bool;
|
||||||
|
|
||||||
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()>;
|
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()>;
|
||||||
@ -57,6 +61,7 @@ pub(crate) trait MessageType: Sized {
|
|||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
let chunked = self.chunked();
|
let chunked = self.chunked();
|
||||||
let mut skip_len = length != BodySize::Stream;
|
let mut skip_len = length != BodySize::Stream;
|
||||||
|
let camel_case = self.camel_case();
|
||||||
|
|
||||||
// Content length
|
// Content length
|
||||||
if let Some(status) = self.status() {
|
if let Some(status) = self.status() {
|
||||||
@ -74,18 +79,30 @@ pub(crate) trait MessageType: Sized {
|
|||||||
match length {
|
match length {
|
||||||
BodySize::Stream => {
|
BodySize::Stream => {
|
||||||
if chunked {
|
if chunked {
|
||||||
dst.put_slice(b"\r\ntransfer-encoding: chunked\r\n")
|
if camel_case {
|
||||||
|
dst.put_slice(b"\r\nTransfer-Encoding: chunked\r\n")
|
||||||
|
} else {
|
||||||
|
dst.put_slice(b"\r\ntransfer-encoding: chunked\r\n")
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
skip_len = false;
|
skip_len = false;
|
||||||
dst.put_slice(b"\r\n");
|
dst.put_slice(b"\r\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
BodySize::Empty => {
|
BodySize::Empty => {
|
||||||
dst.put_slice(b"\r\ncontent-length: 0\r\n");
|
if camel_case {
|
||||||
|
dst.put_slice(b"\r\nContent-Length: 0\r\n");
|
||||||
|
} else {
|
||||||
|
dst.put_slice(b"\r\ncontent-length: 0\r\n");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
BodySize::Sized(len) => helpers::write_content_length(len, dst),
|
BodySize::Sized(len) => helpers::write_content_length(len, dst),
|
||||||
BodySize::Sized64(len) => {
|
BodySize::Sized64(len) => {
|
||||||
dst.put_slice(b"\r\ncontent-length: ");
|
if camel_case {
|
||||||
|
dst.put_slice(b"\r\nContent-Length: ");
|
||||||
|
} else {
|
||||||
|
dst.put_slice(b"\r\ncontent-length: ");
|
||||||
|
}
|
||||||
write!(dst.writer(), "{}\r\n", len)?;
|
write!(dst.writer(), "{}\r\n", len)?;
|
||||||
}
|
}
|
||||||
BodySize::None => dst.put_slice(b"\r\n"),
|
BodySize::None => dst.put_slice(b"\r\n"),
|
||||||
@ -95,10 +112,18 @@ pub(crate) trait MessageType: Sized {
|
|||||||
match ctype {
|
match ctype {
|
||||||
ConnectionType::Upgrade => dst.put_slice(b"connection: upgrade\r\n"),
|
ConnectionType::Upgrade => dst.put_slice(b"connection: upgrade\r\n"),
|
||||||
ConnectionType::KeepAlive if version < Version::HTTP_11 => {
|
ConnectionType::KeepAlive if version < Version::HTTP_11 => {
|
||||||
dst.put_slice(b"connection: keep-alive\r\n")
|
if camel_case {
|
||||||
|
dst.put_slice(b"Connection: keep-alive\r\n")
|
||||||
|
} else {
|
||||||
|
dst.put_slice(b"connection: keep-alive\r\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ConnectionType::Close if version >= Version::HTTP_11 => {
|
ConnectionType::Close if version >= Version::HTTP_11 => {
|
||||||
dst.put_slice(b"connection: close\r\n")
|
if camel_case {
|
||||||
|
dst.put_slice(b"Connection: close\r\n")
|
||||||
|
} else {
|
||||||
|
dst.put_slice(b"connection: close\r\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
@ -133,7 +158,12 @@ pub(crate) trait MessageType: Sized {
|
|||||||
buf = &mut *(dst.bytes_mut() as *mut _);
|
buf = &mut *(dst.bytes_mut() as *mut _);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
buf[pos..pos + k.len()].copy_from_slice(k);
|
// use upper Camel-Case
|
||||||
|
if camel_case {
|
||||||
|
write_camel_case(k, &mut buf[pos..pos + k.len()]);
|
||||||
|
} else {
|
||||||
|
buf[pos..pos + k.len()].copy_from_slice(k);
|
||||||
|
}
|
||||||
pos += k.len();
|
pos += k.len();
|
||||||
buf[pos..pos + 2].copy_from_slice(b": ");
|
buf[pos..pos + 2].copy_from_slice(b": ");
|
||||||
pos += 2;
|
pos += 2;
|
||||||
@ -158,7 +188,12 @@ pub(crate) trait MessageType: Sized {
|
|||||||
buf = &mut *(dst.bytes_mut() as *mut _);
|
buf = &mut *(dst.bytes_mut() as *mut _);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
buf[pos..pos + k.len()].copy_from_slice(k);
|
// use upper Camel-Case
|
||||||
|
if camel_case {
|
||||||
|
write_camel_case(k, &mut buf[pos..pos + k.len()]);
|
||||||
|
} else {
|
||||||
|
buf[pos..pos + k.len()].copy_from_slice(k);
|
||||||
|
}
|
||||||
pos += k.len();
|
pos += k.len();
|
||||||
buf[pos..pos + 2].copy_from_slice(b": ");
|
buf[pos..pos + 2].copy_from_slice(b": ");
|
||||||
pos += 2;
|
pos += 2;
|
||||||
@ -221,6 +256,10 @@ impl MessageType for RequestHead {
|
|||||||
self.chunked()
|
self.chunked()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn camel_case(&self) -> bool {
|
||||||
|
RequestHead::camel_case_headers(self)
|
||||||
|
}
|
||||||
|
|
||||||
fn headers(&self) -> &HeaderMap {
|
fn headers(&self) -> &HeaderMap {
|
||||||
&self.headers
|
&self.headers
|
||||||
}
|
}
|
||||||
@ -418,11 +457,41 @@ impl<'a> io::Write for Writer<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn write_camel_case(value: &[u8], buffer: &mut [u8]) {
|
||||||
|
let mut index = 0;
|
||||||
|
let key = value;
|
||||||
|
let mut key_iter = key.iter();
|
||||||
|
|
||||||
|
if let Some(c) = key_iter.next() {
|
||||||
|
if *c >= b'a' && *c <= b'z' {
|
||||||
|
buffer[index] = *c ^ b' ';
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while let Some(c) = key_iter.next() {
|
||||||
|
buffer[index] = *c;
|
||||||
|
index += 1;
|
||||||
|
if *c == b'-' {
|
||||||
|
if let Some(c) = key_iter.next() {
|
||||||
|
if *c >= b'a' && *c <= b'z' {
|
||||||
|
buffer[index] = *c ^ b' ';
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::http::header::{HeaderValue, CONTENT_TYPE};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_chunked_te() {
|
fn test_chunked_te() {
|
||||||
let mut bytes = BytesMut::new();
|
let mut bytes = BytesMut::new();
|
||||||
@ -436,4 +505,77 @@ mod tests {
|
|||||||
Bytes::from_static(b"4\r\ntest\r\n0\r\n\r\n")
|
Bytes::from_static(b"4\r\ntest\r\n0\r\n\r\n")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_camel_case() {
|
||||||
|
let mut bytes = BytesMut::with_capacity(2048);
|
||||||
|
let mut head = RequestHead::default();
|
||||||
|
head.set_camel_case_headers(true);
|
||||||
|
head.headers.insert(DATE, HeaderValue::from_static("date"));
|
||||||
|
head.headers
|
||||||
|
.insert(CONTENT_TYPE, HeaderValue::from_static("plain/text"));
|
||||||
|
|
||||||
|
let _ = head.encode_headers(
|
||||||
|
&mut bytes,
|
||||||
|
Version::HTTP_11,
|
||||||
|
BodySize::Empty,
|
||||||
|
ConnectionType::Close,
|
||||||
|
&ServiceConfig::default(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bytes.take().freeze(),
|
||||||
|
Bytes::from_static(b"\r\nContent-Length: 0\r\nConnection: close\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
let _ = head.encode_headers(
|
||||||
|
&mut bytes,
|
||||||
|
Version::HTTP_11,
|
||||||
|
BodySize::Stream,
|
||||||
|
ConnectionType::KeepAlive,
|
||||||
|
&ServiceConfig::default(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bytes.take().freeze(),
|
||||||
|
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
let _ = head.encode_headers(
|
||||||
|
&mut bytes,
|
||||||
|
Version::HTTP_11,
|
||||||
|
BodySize::Sized64(100),
|
||||||
|
ConnectionType::KeepAlive,
|
||||||
|
&ServiceConfig::default(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bytes.take().freeze(),
|
||||||
|
Bytes::from_static(b"\r\nContent-Length: 100\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
head.headers
|
||||||
|
.append(CONTENT_TYPE, HeaderValue::from_static("xml"));
|
||||||
|
let _ = head.encode_headers(
|
||||||
|
&mut bytes,
|
||||||
|
Version::HTTP_11,
|
||||||
|
BodySize::Stream,
|
||||||
|
ConnectionType::KeepAlive,
|
||||||
|
&ServiceConfig::default(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bytes.take().freeze(),
|
||||||
|
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: xml\r\nContent-Type: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
head.set_camel_case_headers(false);
|
||||||
|
let _ = head.encode_headers(
|
||||||
|
&mut bytes,
|
||||||
|
Version::HTTP_11,
|
||||||
|
BodySize::Stream,
|
||||||
|
ConnectionType::KeepAlive,
|
||||||
|
&ServiceConfig::default(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bytes.take().freeze(),
|
||||||
|
Bytes::from_static(b"\r\ntransfer-encoding: chunked\r\ndate: date\r\ncontent-type: xml\r\ncontent-type: plain/text\r\n\r\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{NewService, Service};
|
use actix_service::{NewService, Service};
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{Async, Poll};
|
use futures::{Async, Poll};
|
||||||
@ -8,6 +9,7 @@ use crate::request::Request;
|
|||||||
pub struct ExpectHandler;
|
pub struct ExpectHandler;
|
||||||
|
|
||||||
impl NewService for ExpectHandler {
|
impl NewService for ExpectHandler {
|
||||||
|
type Config = ServerConfig;
|
||||||
type Request = Request;
|
type Request = Request;
|
||||||
type Response = Request;
|
type Response = Request;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -15,7 +17,7 @@ impl NewService for ExpectHandler {
|
|||||||
type InitError = Error;
|
type InitError = Error;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &()) -> Self::Future {
|
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||||
ok(ExpectHandler)
|
ok(ExpectHandler)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,16 +1,18 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
use crate::body::MessageBody;
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::{KeepAlive, ServiceConfig};
|
use crate::config::{KeepAlive, ServiceConfig};
|
||||||
use crate::error::{DispatchError, Error, ParseError};
|
use crate::error::{DispatchError, Error, ParseError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
|
|
||||||
@ -24,19 +26,20 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
|
|||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B> H1Service<T, P, S, B>
|
impl<T, P, S, B> H1Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance with default config.
|
/// Create new `HttpService` instance with default config.
|
||||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||||
|
|
||||||
H1Service {
|
H1Service {
|
||||||
@ -44,20 +47,19 @@ where
|
|||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: ExpectHandler,
|
expect: ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create new `HttpService` instance with config.
|
/// Create new `HttpService` instance with config.
|
||||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||||
cfg: ServiceConfig,
|
|
||||||
service: F,
|
|
||||||
) -> Self {
|
|
||||||
H1Service {
|
H1Service {
|
||||||
cfg,
|
cfg,
|
||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: ExpectHandler,
|
expect: ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -65,7 +67,7 @@ where
|
|||||||
|
|
||||||
impl<T, P, S, B, X, U> H1Service<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> H1Service<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
@ -82,6 +84,7 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
upgrade: self.upgrade,
|
upgrade: self.upgrade,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -97,26 +100,41 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
expect: self.expect,
|
expect: self.expect,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on connect callback.
|
||||||
|
pub(crate) fn on_connect(
|
||||||
|
mut self,
|
||||||
|
f: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
|
self.on_connect = f;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for H1Service<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> NewService for H1Service<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
U: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = Io<T, P>;
|
type Request = Io<T, P>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -127,10 +145,11 @@ where
|
|||||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||||
H1ServiceResponse {
|
H1ServiceResponse {
|
||||||
fut: self.srv.new_service(cfg).into_future(),
|
fut: self.srv.new_service(cfg).into_future(),
|
||||||
fut_ex: Some(self.expect.new_service(&())),
|
fut_ex: Some(self.expect.new_service(cfg)),
|
||||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||||
expect: None,
|
expect: None,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: self.on_connect.clone(),
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -140,7 +159,7 @@ where
|
|||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct H1ServiceResponse<T, P, S, B, X, U>
|
pub struct H1ServiceResponse<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Request = Request, Response = Request>,
|
||||||
@ -155,6 +174,7 @@ where
|
|||||||
fut_upg: Option<U::Future>,
|
fut_upg: Option<U::Future>,
|
||||||
expect: Option<X::Service>,
|
expect: Option<X::Service>,
|
||||||
upgrade: Option<U::Service>,
|
upgrade: Option<U::Service>,
|
||||||
|
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
cfg: Option<ServiceConfig>,
|
cfg: Option<ServiceConfig>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
@ -162,7 +182,7 @@ where
|
|||||||
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
@ -203,6 +223,7 @@ where
|
|||||||
service,
|
service,
|
||||||
self.expect.take().unwrap(),
|
self.expect.take().unwrap(),
|
||||||
self.upgrade.take(),
|
self.upgrade.take(),
|
||||||
|
self.on_connect.clone(),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -212,6 +233,7 @@ pub struct H1ServiceHandler<T, P, S, B, X, U> {
|
|||||||
srv: CloneableService<S>,
|
srv: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
@ -232,12 +254,14 @@ where
|
|||||||
srv: S,
|
srv: S,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
) -> H1ServiceHandler<T, P, S, B, X, U> {
|
) -> H1ServiceHandler<T, P, S, B, X, U> {
|
||||||
H1ServiceHandler {
|
H1ServiceHandler {
|
||||||
srv: CloneableService::new(srv),
|
srv: CloneableService::new(srv),
|
||||||
expect: CloneableService::new(expect),
|
expect: CloneableService::new(expect),
|
||||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
upgrade: upgrade.map(CloneableService::new),
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -290,12 +314,21 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
|
let io = req.into_parts().0;
|
||||||
|
|
||||||
|
let on_connect = if let Some(ref on_connect) = self.on_connect {
|
||||||
|
Some(on_connect(&io))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
Dispatcher::new(
|
Dispatcher::new(
|
||||||
req.into_parts().0,
|
io,
|
||||||
self.cfg.clone(),
|
self.cfg.clone(),
|
||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
self.expect.clone(),
|
self.expect.clone(),
|
||||||
self.upgrade.clone(),
|
self.upgrade.clone(),
|
||||||
|
on_connect,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -320,10 +353,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P> NewService<SrvConfig> for OneRequest<T, P>
|
impl<T, P> NewService for OneRequest<T, P>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = Io<T, P>;
|
type Request = Io<T, P>;
|
||||||
type Response = (Request, Framed<T, Codec>);
|
type Response = (Request, Framed<T, Codec>);
|
||||||
type Error = ParseError;
|
type Error = ParseError;
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{NewService, Service};
|
use actix_service::{NewService, Service};
|
||||||
use futures::future::FutureResult;
|
use futures::future::FutureResult;
|
||||||
use futures::{Async, Poll};
|
use futures::{Async, Poll};
|
||||||
@ -12,6 +13,7 @@ use crate::request::Request;
|
|||||||
pub struct UpgradeHandler<T>(PhantomData<T>);
|
pub struct UpgradeHandler<T>(PhantomData<T>);
|
||||||
|
|
||||||
impl<T> NewService for UpgradeHandler<T> {
|
impl<T> NewService for UpgradeHandler<T> {
|
||||||
|
type Config = ServerConfig;
|
||||||
type Request = (Request, Framed<T, Codec>);
|
type Request = (Request, Framed<T, Codec>);
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
@ -19,7 +21,7 @@ impl<T> NewService for UpgradeHandler<T> {
|
|||||||
type InitError = Error;
|
type InitError = Error;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self, _: &()) -> Self::Future {
|
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||||
unimplemented!()
|
unimplemented!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ use std::{fmt, mem, net};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_server_config::IoStream;
|
use actix_server_config::IoStream;
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
|
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
|
||||||
@ -20,8 +19,10 @@ use log::{debug, error, trace};
|
|||||||
use tokio_timer::Delay;
|
use tokio_timer::Delay;
|
||||||
|
|
||||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::ServiceConfig;
|
use crate::config::ServiceConfig;
|
||||||
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
|
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
use crate::message::ResponseHead;
|
use crate::message::ResponseHead;
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
@ -33,6 +34,7 @@ const CHUNK_SIZE: usize = 16_384;
|
|||||||
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> {
|
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> {
|
||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
connection: Connection<T, Bytes>,
|
connection: Connection<T, Bytes>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
peer_addr: Option<net::SocketAddr>,
|
peer_addr: Option<net::SocketAddr>,
|
||||||
ka_expire: Instant,
|
ka_expire: Instant,
|
||||||
@ -49,9 +51,10 @@ where
|
|||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
pub fn new(
|
pub(crate) fn new(
|
||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
connection: Connection<T, Bytes>,
|
connection: Connection<T, Bytes>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
timeout: Option<Delay>,
|
timeout: Option<Delay>,
|
||||||
peer_addr: Option<net::SocketAddr>,
|
peer_addr: Option<net::SocketAddr>,
|
||||||
@ -77,6 +80,7 @@ where
|
|||||||
config,
|
config,
|
||||||
peer_addr,
|
peer_addr,
|
||||||
connection,
|
connection,
|
||||||
|
on_connect,
|
||||||
ka_expire,
|
ka_expire,
|
||||||
ka_timer,
|
ka_timer,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
|
@ -1,11 +1,10 @@
|
|||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::{io, net};
|
use std::{io, net, rc};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||||
@ -14,8 +13,10 @@ use h2::RecvStream;
|
|||||||
use log::error;
|
use log::error;
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
use crate::body::MessageBody;
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::{KeepAlive, ServiceConfig};
|
use crate::config::{KeepAlive, ServiceConfig};
|
||||||
use crate::error::{DispatchError, Error, ParseError, ResponseError};
|
use crate::error::{DispatchError, Error, ParseError, ResponseError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
@ -26,50 +27,60 @@ use super::dispatcher::Dispatcher;
|
|||||||
pub struct H2Service<T, P, S, B> {
|
pub struct H2Service<T, P, S, B> {
|
||||||
srv: S,
|
srv: S,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B> H2Service<T, P, S, B>
|
impl<T, P, S, B> H2Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance.
|
/// Create new `HttpService` instance.
|
||||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||||
|
|
||||||
H2Service {
|
H2Service {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect: None,
|
||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create new `HttpService` instance with config.
|
/// Create new `HttpService` instance with config.
|
||||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||||
cfg: ServiceConfig,
|
|
||||||
service: F,
|
|
||||||
) -> Self {
|
|
||||||
H2Service {
|
H2Service {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect: None,
|
||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on connect callback.
|
||||||
|
pub(crate) fn on_connect(
|
||||||
|
mut self,
|
||||||
|
f: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
|
self.on_connect = f;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B> NewService<SrvConfig> for H2Service<T, P, S, B>
|
impl<T, P, S, B> NewService for H2Service<T, P, S, B>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = Io<T, P>;
|
type Request = Io<T, P>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -81,22 +92,24 @@ where
|
|||||||
H2ServiceResponse {
|
H2ServiceResponse {
|
||||||
fut: self.srv.new_service(cfg).into_future(),
|
fut: self.srv.new_service(cfg).into_future(),
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
|
on_connect: self.on_connect.clone(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>, B> {
|
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
||||||
fut: <S::Future as IntoFuture>::Future,
|
fut: <S::Future as IntoFuture>::Future,
|
||||||
cfg: Option<ServiceConfig>,
|
cfg: Option<ServiceConfig>,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B>
|
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
@ -109,6 +122,7 @@ where
|
|||||||
let service = try_ready!(self.fut.poll());
|
let service = try_ready!(self.fut.poll());
|
||||||
Ok(Async::Ready(H2ServiceHandler::new(
|
Ok(Async::Ready(H2ServiceHandler::new(
|
||||||
self.cfg.take().unwrap(),
|
self.cfg.take().unwrap(),
|
||||||
|
self.on_connect.clone(),
|
||||||
service,
|
service,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
@ -118,6 +132,7 @@ where
|
|||||||
pub struct H2ServiceHandler<T, P, S, B> {
|
pub struct H2ServiceHandler<T, P, S, B> {
|
||||||
srv: CloneableService<S>,
|
srv: CloneableService<S>,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -129,9 +144,14 @@ where
|
|||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
fn new(cfg: ServiceConfig, srv: S) -> H2ServiceHandler<T, P, S, B> {
|
fn new(
|
||||||
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
srv: S,
|
||||||
|
) -> H2ServiceHandler<T, P, S, B> {
|
||||||
H2ServiceHandler {
|
H2ServiceHandler {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect,
|
||||||
srv: CloneableService::new(srv),
|
srv: CloneableService::new(srv),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -163,11 +183,18 @@ where
|
|||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
let io = req.into_parts().0;
|
let io = req.into_parts().0;
|
||||||
let peer_addr = io.peer_addr();
|
let peer_addr = io.peer_addr();
|
||||||
|
let on_connect = if let Some(ref on_connect) = self.on_connect {
|
||||||
|
Some(on_connect(&io))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
H2ServiceHandlerResponse {
|
H2ServiceHandlerResponse {
|
||||||
state: State::Handshake(
|
state: State::Handshake(
|
||||||
Some(self.srv.clone()),
|
Some(self.srv.clone()),
|
||||||
Some(self.cfg.clone()),
|
Some(self.cfg.clone()),
|
||||||
peer_addr,
|
peer_addr,
|
||||||
|
on_connect,
|
||||||
server::handshake(io),
|
server::handshake(io),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@ -183,6 +210,7 @@ where
|
|||||||
Option<CloneableService<S>>,
|
Option<CloneableService<S>>,
|
||||||
Option<ServiceConfig>,
|
Option<ServiceConfig>,
|
||||||
Option<net::SocketAddr>,
|
Option<net::SocketAddr>,
|
||||||
|
Option<Box<dyn DataFactory>>,
|
||||||
Handshake<T, Bytes>,
|
Handshake<T, Bytes>,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@ -218,15 +246,17 @@ where
|
|||||||
ref mut srv,
|
ref mut srv,
|
||||||
ref mut config,
|
ref mut config,
|
||||||
ref peer_addr,
|
ref peer_addr,
|
||||||
|
ref mut on_connect,
|
||||||
ref mut handshake,
|
ref mut handshake,
|
||||||
) => match handshake.poll() {
|
) => match handshake.poll() {
|
||||||
Ok(Async::Ready(conn)) => {
|
Ok(Async::Ready(conn)) => {
|
||||||
self.state = State::Incoming(Dispatcher::new(
|
self.state = State::Incoming(Dispatcher::new(
|
||||||
srv.take().unwrap(),
|
srv.take().unwrap(),
|
||||||
conn,
|
conn,
|
||||||
|
on_connect.take(),
|
||||||
config.take().unwrap(),
|
config.take().unwrap(),
|
||||||
None,
|
None,
|
||||||
peer_addr.clone(),
|
*peer_addr,
|
||||||
));
|
));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
|
@ -70,6 +70,7 @@ impl<'a> From<&'a str> for DispositionType {
|
|||||||
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub enum DispositionParam {
|
pub enum DispositionParam {
|
||||||
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
||||||
/// the form.
|
/// the form.
|
||||||
@ -719,8 +720,10 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert_eq!(a, b);
|
assert_eq!(a, b);
|
||||||
|
|
||||||
let a =
|
let a = HeaderValue::from_str(
|
||||||
HeaderValue::from_str("form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"").unwrap();
|
"form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::FormData,
|
disposition: DispositionType::FormData,
|
||||||
|
@ -3,6 +3,8 @@ use std::{io, mem, ptr, slice};
|
|||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{BufMut, BytesMut};
|
||||||
use http::Version;
|
use http::Version;
|
||||||
|
|
||||||
|
use crate::extensions::Extensions;
|
||||||
|
|
||||||
const DEC_DIGITS_LUT: &[u8] = b"0001020304050607080910111213141516171819\
|
const DEC_DIGITS_LUT: &[u8] = b"0001020304050607080910111213141516171819\
|
||||||
2021222324252627282930313233343536373839\
|
2021222324252627282930313233343536373839\
|
||||||
4041424344454647484950515253545556575859\
|
4041424344454647484950515253545556575859\
|
||||||
@ -180,6 +182,18 @@ impl<'a> io::Write for Writer<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) trait DataFactory {
|
||||||
|
fn set(&self, ext: &mut Extensions);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Data<T>(pub(crate) T);
|
||||||
|
|
||||||
|
impl<T: Clone + 'static> DataFactory for Data<T> {
|
||||||
|
fn set(&self, ext: &mut Extensions) {
|
||||||
|
ext.insert(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
@ -61,6 +61,7 @@ impl Response {
|
|||||||
STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
|
STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
|
||||||
STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
|
STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
|
||||||
STATIC_RESP!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
|
STATIC_RESP!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
STATIC_RESP!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
|
||||||
STATIC_RESP!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
|
STATIC_RESP!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
STATIC_RESP!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
|
STATIC_RESP!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
|
||||||
|
@ -1,9 +1,7 @@
|
|||||||
use std::cell::{Ref, RefMut};
|
use std::cell::{Ref, RefMut};
|
||||||
use std::str;
|
use std::str;
|
||||||
|
|
||||||
use encoding::all::UTF_8;
|
use encoding_rs::{Encoding, UTF_8};
|
||||||
use encoding::label::encoding_from_whatwg_label;
|
|
||||||
use encoding::EncodingRef;
|
|
||||||
use http::header;
|
use http::header;
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
|
|
||||||
@ -59,10 +57,12 @@ pub trait HttpMessage: Sized {
|
|||||||
/// Get content type encoding
|
/// Get content type encoding
|
||||||
///
|
///
|
||||||
/// UTF-8 is used by default, If request charset is not set.
|
/// UTF-8 is used by default, If request charset is not set.
|
||||||
fn encoding(&self) -> Result<EncodingRef, ContentTypeError> {
|
fn encoding(&self) -> Result<&'static Encoding, ContentTypeError> {
|
||||||
if let Some(mime_type) = self.mime_type()? {
|
if let Some(mime_type) = self.mime_type()? {
|
||||||
if let Some(charset) = mime_type.get_param("charset") {
|
if let Some(charset) = mime_type.get_param("charset") {
|
||||||
if let Some(enc) = encoding_from_whatwg_label(charset.as_str()) {
|
if let Some(enc) =
|
||||||
|
Encoding::for_label_no_replacement(charset.as_str().as_bytes())
|
||||||
|
{
|
||||||
Ok(enc)
|
Ok(enc)
|
||||||
} else {
|
} else {
|
||||||
Err(ContentTypeError::UnknownEncoding)
|
Err(ContentTypeError::UnknownEncoding)
|
||||||
@ -166,8 +166,7 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use encoding::all::ISO_8859_2;
|
use encoding_rs::ISO_8859_2;
|
||||||
use encoding::Encoding;
|
|
||||||
use mime;
|
use mime;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -223,7 +222,7 @@ mod tests {
|
|||||||
"application/json; charset=ISO-8859-2",
|
"application/json; charset=ISO-8859-2",
|
||||||
)
|
)
|
||||||
.finish();
|
.finish();
|
||||||
assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name());
|
assert_eq!(ISO_8859_2, req.encoding().unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
//! Basic http primitives for actix-net framework.
|
//! Basic http primitives for actix-net framework.
|
||||||
#![allow(
|
#![allow(
|
||||||
clippy::type_complexity,
|
clippy::type_complexity,
|
||||||
|
clippy::too_many_arguments,
|
||||||
clippy::new_without_default,
|
clippy::new_without_default,
|
||||||
clippy::borrow_interior_mutable_const
|
clippy::borrow_interior_mutable_const,
|
||||||
|
clippy::write_with_newline
|
||||||
)]
|
)]
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
@ -11,6 +13,7 @@ extern crate log;
|
|||||||
pub mod body;
|
pub mod body;
|
||||||
mod builder;
|
mod builder;
|
||||||
pub mod client;
|
pub mod client;
|
||||||
|
mod cloneable;
|
||||||
mod config;
|
mod config;
|
||||||
pub mod encoding;
|
pub mod encoding;
|
||||||
mod extensions;
|
mod extensions;
|
||||||
|
@ -27,6 +27,7 @@ bitflags! {
|
|||||||
const UPGRADE = 0b0000_0100;
|
const UPGRADE = 0b0000_0100;
|
||||||
const EXPECT = 0b0000_1000;
|
const EXPECT = 0b0000_1000;
|
||||||
const NO_CHUNKING = 0b0001_0000;
|
const NO_CHUNKING = 0b0001_0000;
|
||||||
|
const CAMEL_CASE = 0b0010_0000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,6 +98,23 @@ impl RequestHead {
|
|||||||
&mut self.headers
|
&mut self.headers
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Is to uppercase headers with Camel-Case.
|
||||||
|
/// Befault is `false`
|
||||||
|
#[inline]
|
||||||
|
pub fn camel_case_headers(&self) -> bool {
|
||||||
|
self.flags.contains(Flags::CAMEL_CASE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set `true` to send headers which are uppercased with Camel-Case.
|
||||||
|
#[inline]
|
||||||
|
pub fn set_camel_case_headers(&mut self, val: bool) {
|
||||||
|
if val {
|
||||||
|
self.flags.insert(Flags::CAMEL_CASE);
|
||||||
|
} else {
|
||||||
|
self.flags.remove(Flags::CAMEL_CASE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
/// Set connection type of the message
|
/// Set connection type of the message
|
||||||
pub fn set_connection_type(&mut self, ctype: ConnectionType) {
|
pub fn set_connection_type(&mut self, ctype: ConnectionType) {
|
||||||
@ -367,6 +385,7 @@ impl Drop for BoxedResponseHead {
|
|||||||
pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
|
pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
#[allow(clippy::vec_box)]
|
||||||
/// Request's objects pool
|
/// Request's objects pool
|
||||||
pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>);
|
pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>);
|
||||||
|
|
||||||
@ -431,6 +450,7 @@ impl BoxedResponsePool {
|
|||||||
fn release(&self, msg: Box<ResponseHead>) {
|
fn release(&self, msg: Box<ResponseHead>) {
|
||||||
let v = &mut self.0.borrow_mut();
|
let v = &mut self.0.borrow_mut();
|
||||||
if v.len() < 128 {
|
if v.len() < 128 {
|
||||||
|
msg.extensions.borrow_mut().clear();
|
||||||
v.push(msg);
|
v.push(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -178,3 +178,28 @@ impl<P> fmt::Debug for Request<P> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use http::HttpTryFrom;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_basics() {
|
||||||
|
let msg = Message::new();
|
||||||
|
let mut req = Request::from(msg);
|
||||||
|
req.headers_mut().insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
header::HeaderValue::from_static("text/plain"),
|
||||||
|
);
|
||||||
|
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
||||||
|
|
||||||
|
*req.uri_mut() = Uri::try_from("/index.html?q=1").unwrap();
|
||||||
|
assert_eq!(req.uri().path(), "/index.html");
|
||||||
|
assert_eq!(req.uri().query(), Some("q=1"));
|
||||||
|
|
||||||
|
let s = format!("{:?}", req);
|
||||||
|
println!("T: {:?}", s);
|
||||||
|
assert!(s.contains("Request HTTP/1.1 GET:/index.html"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -764,6 +764,25 @@ impl IntoFuture for ResponseBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ResponseBuilder {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
let head = self.head.as_ref().unwrap();
|
||||||
|
|
||||||
|
let res = writeln!(
|
||||||
|
f,
|
||||||
|
"\nResponseBuilder {:?} {}{}",
|
||||||
|
head.version,
|
||||||
|
head.status,
|
||||||
|
head.reason.unwrap_or(""),
|
||||||
|
);
|
||||||
|
let _ = writeln!(f, " headers:");
|
||||||
|
for (key, val) in head.headers.iter() {
|
||||||
|
let _ = writeln!(f, " {:?}: {:?}", key, val);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Helper converters
|
/// Helper converters
|
||||||
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
||||||
fn from(res: Result<I, E>) -> Self {
|
fn from(res: Result<I, E>) -> Self {
|
||||||
@ -860,7 +879,7 @@ mod tests {
|
|||||||
.domain("www.rust-lang.org")
|
.domain("www.rust-lang.org")
|
||||||
.path("/test")
|
.path("/test")
|
||||||
.http_only(true)
|
.http_only(true)
|
||||||
.max_age(time::Duration::days(1))
|
.max_age_time(time::Duration::days(1))
|
||||||
.finish(),
|
.finish(),
|
||||||
)
|
)
|
||||||
.del_cookie(&cookies[1])
|
.del_cookie(&cookies[1])
|
||||||
|
@ -1,20 +1,21 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::{fmt, io, net};
|
use std::{fmt, io, net, rc};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_server_config::{
|
use actix_server_config::{
|
||||||
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
|
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
|
||||||
};
|
};
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||||
use h2::server::{self, Handshake};
|
use h2::server::{self, Handshake};
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
use crate::body::MessageBody;
|
||||||
use crate::builder::HttpServiceBuilder;
|
use crate::builder::HttpServiceBuilder;
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::{KeepAlive, ServiceConfig};
|
use crate::config::{KeepAlive, ServiceConfig};
|
||||||
use crate::error::{DispatchError, Error};
|
use crate::error::{DispatchError, Error};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
use crate::{h1, h2::Dispatcher};
|
use crate::{h1, h2::Dispatcher};
|
||||||
@ -25,12 +26,13 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
|
|||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, B> HttpService<T, (), S, B>
|
impl<T, S, B> HttpService<T, (), S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -45,7 +47,7 @@ where
|
|||||||
|
|
||||||
impl<T, P, S, B> HttpService<T, P, S, B>
|
impl<T, P, S, B> HttpService<T, P, S, B>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -53,7 +55,7 @@ where
|
|||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance.
|
/// Create new `HttpService` instance.
|
||||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||||
|
|
||||||
HttpService {
|
HttpService {
|
||||||
@ -61,12 +63,13 @@ where
|
|||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: h1::ExpectHandler,
|
expect: h1::ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create new `HttpService` instance with config.
|
/// Create new `HttpService` instance with config.
|
||||||
pub(crate) fn with_config<F: IntoNewService<S, SrvConfig>>(
|
pub(crate) fn with_config<F: IntoNewService<S>>(
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
service: F,
|
service: F,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
@ -75,6 +78,7 @@ where
|
|||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: h1::ExpectHandler,
|
expect: h1::ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -82,7 +86,7 @@ where
|
|||||||
|
|
||||||
impl<T, P, S, B, X, U> HttpService<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> HttpService<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -95,7 +99,7 @@ where
|
|||||||
/// request will be forwarded to main service.
|
/// request will be forwarded to main service.
|
||||||
pub fn expect<X1>(self, expect: X1) -> HttpService<T, P, S, B, X1, U>
|
pub fn expect<X1>(self, expect: X1) -> HttpService<T, P, S, B, X1, U>
|
||||||
where
|
where
|
||||||
X1: NewService<Request = Request, Response = Request>,
|
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X1::Error: Into<Error>,
|
X1::Error: Into<Error>,
|
||||||
X1::InitError: fmt::Debug,
|
X1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -104,6 +108,7 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
upgrade: self.upgrade,
|
upgrade: self.upgrade,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -114,7 +119,11 @@ where
|
|||||||
/// and this service get called with original request and framed object.
|
/// and this service get called with original request and framed object.
|
||||||
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, P, S, B, X, U1>
|
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, P, S, B, X, U1>
|
||||||
where
|
where
|
||||||
U1: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
U1: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, h1::Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U1::Error: fmt::Display,
|
U1::Error: fmt::Display,
|
||||||
U1::InitError: fmt::Debug,
|
U1::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
@ -123,27 +132,42 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
expect: self.expect,
|
expect: self.expect,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on connect callback.
|
||||||
|
pub(crate) fn on_connect(
|
||||||
|
mut self,
|
||||||
|
f: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
|
self.on_connect = f;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for HttpService<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> NewService for HttpService<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Config = SrvConfig, Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
<S::Service as Service>::Future: 'static,
|
<S::Service as Service>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
X: NewService<Request = Request, Response = Request>,
|
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
U: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
U: NewService<
|
||||||
|
Config = SrvConfig,
|
||||||
|
Request = (Request, Framed<T, h1::Codec>),
|
||||||
|
Response = (),
|
||||||
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
|
type Config = SrvConfig;
|
||||||
type Request = ServerIo<T, P>;
|
type Request = ServerIo<T, P>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -154,10 +178,11 @@ where
|
|||||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||||
HttpServiceResponse {
|
HttpServiceResponse {
|
||||||
fut: self.srv.new_service(cfg).into_future(),
|
fut: self.srv.new_service(cfg).into_future(),
|
||||||
fut_ex: Some(self.expect.new_service(&())),
|
fut_ex: Some(self.expect.new_service(cfg)),
|
||||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||||
expect: None,
|
expect: None,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: self.on_connect.clone(),
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -165,19 +190,13 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct HttpServiceResponse<
|
pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewService> {
|
||||||
T,
|
|
||||||
P,
|
|
||||||
S: NewService<SrvConfig>,
|
|
||||||
B,
|
|
||||||
X: NewService,
|
|
||||||
U: NewService,
|
|
||||||
> {
|
|
||||||
fut: S::Future,
|
fut: S::Future,
|
||||||
fut_ex: Option<X::Future>,
|
fut_ex: Option<X::Future>,
|
||||||
fut_upg: Option<U::Future>,
|
fut_upg: Option<U::Future>,
|
||||||
expect: Option<X::Service>,
|
expect: Option<X::Service>,
|
||||||
upgrade: Option<U::Service>,
|
upgrade: Option<U::Service>,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
cfg: Option<ServiceConfig>,
|
cfg: Option<ServiceConfig>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
@ -185,7 +204,7 @@ pub struct HttpServiceResponse<
|
|||||||
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: IoStream,
|
T: IoStream,
|
||||||
S: NewService<SrvConfig, Request = Request>,
|
S: NewService<Request = Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
@ -227,6 +246,7 @@ where
|
|||||||
service,
|
service,
|
||||||
self.expect.take().unwrap(),
|
self.expect.take().unwrap(),
|
||||||
self.upgrade.take(),
|
self.upgrade.take(),
|
||||||
|
self.on_connect.clone(),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -237,6 +257,7 @@ pub struct HttpServiceHandler<T, P, S, B, X, U> {
|
|||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B, X)>,
|
_t: PhantomData<(T, P, B, X)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -257,12 +278,14 @@ where
|
|||||||
srv: S,
|
srv: S,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
) -> HttpServiceHandler<T, P, S, B, X, U> {
|
) -> HttpServiceHandler<T, P, S, B, X, U> {
|
||||||
HttpServiceHandler {
|
HttpServiceHandler {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect,
|
||||||
srv: CloneableService::new(srv),
|
srv: CloneableService::new(srv),
|
||||||
expect: CloneableService::new(expect),
|
expect: CloneableService::new(expect),
|
||||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
upgrade: upgrade.map(CloneableService::new),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -317,6 +340,13 @@ where
|
|||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
let (io, _, proto) = req.into_parts();
|
let (io, _, proto) = req.into_parts();
|
||||||
|
|
||||||
|
let on_connect = if let Some(ref on_connect) = self.on_connect {
|
||||||
|
Some(on_connect(&io))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
match proto {
|
match proto {
|
||||||
Protocol::Http2 => {
|
Protocol::Http2 => {
|
||||||
let peer_addr = io.peer_addr();
|
let peer_addr = io.peer_addr();
|
||||||
@ -330,6 +360,7 @@ where
|
|||||||
self.cfg.clone(),
|
self.cfg.clone(),
|
||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
peer_addr,
|
peer_addr,
|
||||||
|
on_connect,
|
||||||
))),
|
))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -340,6 +371,7 @@ where
|
|||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
self.expect.clone(),
|
self.expect.clone(),
|
||||||
self.upgrade.clone(),
|
self.upgrade.clone(),
|
||||||
|
on_connect,
|
||||||
)),
|
)),
|
||||||
},
|
},
|
||||||
_ => HttpServiceHandlerResponse {
|
_ => HttpServiceHandlerResponse {
|
||||||
@ -350,6 +382,7 @@ where
|
|||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
self.expect.clone(),
|
self.expect.clone(),
|
||||||
self.upgrade.clone(),
|
self.upgrade.clone(),
|
||||||
|
on_connect,
|
||||||
))),
|
))),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -378,6 +411,7 @@ where
|
|||||||
CloneableService<S>,
|
CloneableService<S>,
|
||||||
CloneableService<X>,
|
CloneableService<X>,
|
||||||
Option<CloneableService<U>>,
|
Option<CloneableService<U>>,
|
||||||
|
Option<Box<dyn DataFactory>>,
|
||||||
)>,
|
)>,
|
||||||
),
|
),
|
||||||
Handshake(
|
Handshake(
|
||||||
@ -386,6 +420,7 @@ where
|
|||||||
ServiceConfig,
|
ServiceConfig,
|
||||||
CloneableService<S>,
|
CloneableService<S>,
|
||||||
Option<net::SocketAddr>,
|
Option<net::SocketAddr>,
|
||||||
|
Option<Box<dyn DataFactory>>,
|
||||||
)>,
|
)>,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@ -446,7 +481,8 @@ where
|
|||||||
} else {
|
} else {
|
||||||
panic!()
|
panic!()
|
||||||
}
|
}
|
||||||
let (io, buf, cfg, srv, expect, upgrade) = data.take().unwrap();
|
let (io, buf, cfg, srv, expect, upgrade, on_connect) =
|
||||||
|
data.take().unwrap();
|
||||||
if buf[..14] == HTTP2_PREFACE[..] {
|
if buf[..14] == HTTP2_PREFACE[..] {
|
||||||
let peer_addr = io.peer_addr();
|
let peer_addr = io.peer_addr();
|
||||||
let io = Io {
|
let io = Io {
|
||||||
@ -458,6 +494,7 @@ where
|
|||||||
cfg,
|
cfg,
|
||||||
srv,
|
srv,
|
||||||
peer_addr,
|
peer_addr,
|
||||||
|
on_connect,
|
||||||
)));
|
)));
|
||||||
} else {
|
} else {
|
||||||
self.state = State::H1(h1::Dispatcher::with_timeout(
|
self.state = State::H1(h1::Dispatcher::with_timeout(
|
||||||
@ -469,6 +506,7 @@ where
|
|||||||
srv,
|
srv,
|
||||||
expect,
|
expect,
|
||||||
upgrade,
|
upgrade,
|
||||||
|
on_connect,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
self.poll()
|
self.poll()
|
||||||
@ -486,8 +524,10 @@ where
|
|||||||
} else {
|
} else {
|
||||||
panic!()
|
panic!()
|
||||||
};
|
};
|
||||||
let (_, cfg, srv, peer_addr) = data.take().unwrap();
|
let (_, cfg, srv, peer_addr, on_connect) = data.take().unwrap();
|
||||||
self.state = State::H2(Dispatcher::new(srv, conn, cfg, None, peer_addr));
|
self.state = State::H2(Dispatcher::new(
|
||||||
|
srv, conn, on_connect, cfg, None, peer_addr,
|
||||||
|
));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -37,7 +37,7 @@ pub enum Frame {
|
|||||||
Close(Option<CloseReason>),
|
Close(Option<CloseReason>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Copy, Clone)]
|
||||||
/// WebSockets protocol codec
|
/// WebSockets protocol codec
|
||||||
pub struct Codec {
|
pub struct Codec {
|
||||||
max_size: usize,
|
max_size: usize,
|
||||||
|
@ -47,10 +47,7 @@ impl Into<u8> for OpCode {
|
|||||||
Ping => 9,
|
Ping => 9,
|
||||||
Pong => 10,
|
Pong => 10,
|
||||||
Bad => {
|
Bad => {
|
||||||
debug_assert!(
|
log::error!("Attempted to convert invalid opcode to u8. This is a bug.");
|
||||||
false,
|
|
||||||
"Attempted to convert invalid opcode to u8. This is a bug."
|
|
||||||
);
|
|
||||||
8 // if this somehow happens, a close frame will help us tear down quickly
|
8 // if this somehow happens, a close frame will help us tear down quickly
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -59,9 +59,7 @@ fn test_connection_close() {
|
|||||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
});
|
});
|
||||||
println!("REQ: {:?}", srv.get("/").force_close());
|
|
||||||
let response = srv.block_on(srv.get("/").force_close().send()).unwrap();
|
let response = srv.block_on(srv.get("/").force_close().send()).unwrap();
|
||||||
println!("RES: {:?}", response);
|
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,13 +5,13 @@ use std::{net, thread};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_server_config::ServerConfig;
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{fn_cfg_factory, fn_service, NewService};
|
use actix_service::{new_service_cfg, service_fn, NewService};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::future::{self, ok, Future};
|
use futures::future::{self, ok, Future};
|
||||||
use futures::stream::{once, Stream};
|
use futures::stream::{once, Stream};
|
||||||
|
use regex::Regex;
|
||||||
use tokio_timer::sleep;
|
use tokio_timer::sleep;
|
||||||
|
|
||||||
use actix_http::body::Body;
|
|
||||||
use actix_http::error::PayloadError;
|
use actix_http::error::PayloadError;
|
||||||
use actix_http::{
|
use actix_http::{
|
||||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
||||||
@ -163,7 +163,7 @@ fn test_h2_body() -> std::io::Result<()> {
|
|||||||
fn test_expect_continue() {
|
fn test_expect_continue() {
|
||||||
let srv = TestServer::new(|| {
|
let srv = TestServer::new(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.expect(fn_service(|req: Request| {
|
.expect(service_fn(|req: Request| {
|
||||||
if req.head().uri.query() == Some("yes=") {
|
if req.head().uri.query() == Some("yes=") {
|
||||||
Ok(req)
|
Ok(req)
|
||||||
} else {
|
} else {
|
||||||
@ -190,7 +190,7 @@ fn test_expect_continue() {
|
|||||||
fn test_expect_continue_h1() {
|
fn test_expect_continue_h1() {
|
||||||
let srv = TestServer::new(|| {
|
let srv = TestServer::new(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.expect(fn_service(|req: Request| {
|
.expect(service_fn(|req: Request| {
|
||||||
sleep(Duration::from_millis(20)).then(move |_| {
|
sleep(Duration::from_millis(20)).then(move |_| {
|
||||||
if req.head().uri.query() == Some("yes=") {
|
if req.head().uri.query() == Some("yes=") {
|
||||||
Ok(req)
|
Ok(req)
|
||||||
@ -215,6 +215,54 @@ fn test_expect_continue_h1() {
|
|||||||
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
|
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_chunked_payload() {
|
||||||
|
let chunk_sizes = vec![32768, 32, 32768];
|
||||||
|
let total_size: usize = chunk_sizes.iter().sum();
|
||||||
|
|
||||||
|
let srv = TestServer::new(|| {
|
||||||
|
HttpService::build().h1(|mut request: Request| {
|
||||||
|
request
|
||||||
|
.take_payload()
|
||||||
|
.map_err(|e| panic!(format!("Error reading payload: {}", e)))
|
||||||
|
.fold(0usize, |acc, chunk| future::ok::<_, ()>(acc + chunk.len()))
|
||||||
|
.map(|req_size| Response::Ok().body(format!("size={}", req_size)))
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let returned_size = {
|
||||||
|
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
|
||||||
|
let _ = stream
|
||||||
|
.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n");
|
||||||
|
|
||||||
|
for chunk_size in chunk_sizes.iter() {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
let random_bytes: Vec<u8> =
|
||||||
|
(0..*chunk_size).map(|_| rand::random::<u8>()).collect();
|
||||||
|
|
||||||
|
bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes());
|
||||||
|
bytes.extend(&random_bytes[..]);
|
||||||
|
bytes.extend(b"\r\n");
|
||||||
|
let _ = stream.write_all(&bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = stream.write_all(b"0\r\n\r\n");
|
||||||
|
stream.shutdown(net::Shutdown::Write).unwrap();
|
||||||
|
|
||||||
|
let mut data = String::new();
|
||||||
|
let _ = stream.read_to_string(&mut data);
|
||||||
|
|
||||||
|
let re = Regex::new(r"size=(\d+)").unwrap();
|
||||||
|
let size: usize = match re.captures(&data) {
|
||||||
|
Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
|
||||||
|
None => panic!(format!("Failed to find size in HTTP Response: {}", data)),
|
||||||
|
};
|
||||||
|
size
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(returned_size, total_size);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_slow_request() {
|
fn test_slow_request() {
|
||||||
let srv = TestServer::new(|| {
|
let srv = TestServer::new(|| {
|
||||||
@ -775,8 +823,7 @@ fn test_h1_body_length() {
|
|||||||
HttpService::build().h1(|_| {
|
HttpService::build().h1(|_| {
|
||||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
||||||
.body(Body::from_message(body::SizedStream::new(STR.len(), body))),
|
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@ -801,9 +848,10 @@ fn test_h2_body_length() {
|
|||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| {
|
.h2(|_| {
|
||||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(Response::Ok().body(Body::from_message(
|
ok::<_, ()>(
|
||||||
body::SizedStream::new(STR.len(), body),
|
Response::Ok()
|
||||||
)))
|
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
.map_err(|_| ()),
|
.map_err(|_| ()),
|
||||||
)
|
)
|
||||||
@ -912,7 +960,7 @@ fn test_h1_body_chunked_implicit() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_h1_response_http_error_handling() {
|
fn test_h1_response_http_error_handling() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
HttpService::build().h1(fn_cfg_factory(|_: &ServerConfig| {
|
HttpService::build().h1(new_service_cfg(|_: &ServerConfig| {
|
||||||
Ok::<_, ()>(|_| {
|
Ok::<_, ()>(|_| {
|
||||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
@ -943,7 +991,7 @@ fn test_h2_response_http_error_handling() {
|
|||||||
.map_err(|e| println!("Openssl error: {}", e))
|
.map_err(|e| println!("Openssl error: {}", e))
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(fn_cfg_factory(|_: &ServerConfig| {
|
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||||
Ok::<_, ()>(|_| {
|
Ok::<_, ()>(|_| {
|
||||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
|
5
actix-identity/CHANGES.md
Normal file
5
actix-identity/CHANGES.md
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-06-xx
|
||||||
|
|
||||||
|
* Move identity middleware to separate crate
|
30
actix-identity/Cargo.toml
Normal file
30
actix-identity/Cargo.toml
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-identity"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
|
description = "Identity service for actix web framework."
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["http", "web", "framework", "async", "futures"]
|
||||||
|
homepage = "https://actix.rs"
|
||||||
|
repository = "https://github.com/actix/actix-web.git"
|
||||||
|
documentation = "https://docs.rs/actix-identity/"
|
||||||
|
license = "MIT/Apache-2.0"
|
||||||
|
edition = "2018"
|
||||||
|
workspace = ".."
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "actix_identity"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-web = { version = "1.0.0", default-features = false, features = ["secure-cookies"] }
|
||||||
|
actix-service = "0.4.0"
|
||||||
|
futures = "0.1.25"
|
||||||
|
serde = "1.0"
|
||||||
|
serde_json = "1.0"
|
||||||
|
time = "0.1.42"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
actix-rt = "0.2.2"
|
||||||
|
actix-http = "0.2.3"
|
||||||
|
bytes = "0.4"
|
1
actix-identity/LICENSE-APACHE
Symbolic link
1
actix-identity/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-identity/LICENSE-MIT
Symbolic link
1
actix-identity/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
9
actix-identity/README.md
Normal file
9
actix-identity/README.md
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [User Guide](https://actix.rs/docs/)
|
||||||
|
* [API Documentation](https://docs.rs/actix-identity/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
|
||||||
|
* Minimum supported Rust version: 1.34 or later
|
1056
actix-identity/src/lib.rs
Normal file
1056
actix-identity/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,7 +1,31 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## [0.1.0-alpha.1] - 2019-04-xx
|
## [0.1.3] - 2019-06-06
|
||||||
|
|
||||||
|
* Fix ring dependency from actix-web default features for #741.
|
||||||
|
|
||||||
|
## [0.1.2] - 2019-06-02
|
||||||
|
|
||||||
|
* Fix boundary parsing #876
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-05-25
|
||||||
|
|
||||||
|
* Fix disconnect handling #834
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-05-18
|
||||||
|
|
||||||
|
* Release
|
||||||
|
|
||||||
|
## [0.1.0-beta.4] - 2019-05-12
|
||||||
|
|
||||||
|
* Handle cancellation of uploads #736
|
||||||
|
|
||||||
|
* Upgrade to actix-web 1.0.0-beta.4
|
||||||
|
|
||||||
|
## [0.1.0-beta.1] - 2019-04-21
|
||||||
|
|
||||||
* Do not support nested multipart
|
* Do not support nested multipart
|
||||||
|
|
||||||
* Split multipart support to separate crate
|
* Split multipart support to separate crate
|
||||||
|
|
||||||
|
* Optimize multipart handling #634, #769
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-multipart"
|
name = "actix-multipart"
|
||||||
version = "0.1.0-alpha.1"
|
version = "0.1.3"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Multipart support for actix web framework."
|
description = "Multipart support for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -18,10 +18,10 @@ name = "actix_multipart"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-alpha.3"
|
actix-web = { version = "1.0.0", default-features = false }
|
||||||
actix-service = "0.3.4"
|
actix-service = "0.4.1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
@ -31,4 +31,4 @@ twoway = "0.2"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-http = "0.1.0-alpha.3"
|
actix-http = "0.2.4"
|
1
actix-multipart/LICENSE-APACHE
Symbolic link
1
actix-multipart/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-multipart/LICENSE-MIT
Symbolic link
1
actix-multipart/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -1 +1,8 @@
|
|||||||
# Multipart support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-multipart) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Multipart support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-multipart) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [API Documentation](https://docs.rs/actix-multipart/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-multipart](https://crates.io/crates/actix-multipart)
|
||||||
|
* Minimum supported Rust version: 1.33 or later
|
||||||
|
@ -28,6 +28,9 @@ pub enum MultipartError {
|
|||||||
/// Payload error
|
/// Payload error
|
||||||
#[display(fmt = "{}", _0)]
|
#[display(fmt = "{}", _0)]
|
||||||
Payload(PayloadError),
|
Payload(PayloadError),
|
||||||
|
/// Not consumed
|
||||||
|
#[display(fmt = "Multipart stream is not consumed")]
|
||||||
|
NotConsumed,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `MultipartError`
|
/// Return `BadRequest` for `MultipartError`
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
//! Multipart payload support
|
//! Multipart payload support
|
||||||
use std::cell::{RefCell, UnsafeCell};
|
use std::cell::{Cell, RefCell, UnsafeCell};
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::{cmp, fmt};
|
use std::{cmp, fmt};
|
||||||
@ -116,6 +116,8 @@ impl Stream for Multipart {
|
|||||||
payload.poll_stream()?;
|
payload.poll_stream()?;
|
||||||
}
|
}
|
||||||
inner.poll(&self.safety)
|
inner.poll(&self.safety)
|
||||||
|
} else if !self.safety.is_clean() {
|
||||||
|
Err(MultipartError::NotConsumed)
|
||||||
} else {
|
} else {
|
||||||
Ok(Async::NotReady)
|
Ok(Async::NotReady)
|
||||||
}
|
}
|
||||||
@ -126,7 +128,7 @@ impl InnerMultipart {
|
|||||||
fn read_headers(
|
fn read_headers(
|
||||||
payload: &mut PayloadBuffer,
|
payload: &mut PayloadBuffer,
|
||||||
) -> Result<Option<HeaderMap>, MultipartError> {
|
) -> Result<Option<HeaderMap>, MultipartError> {
|
||||||
match payload.read_until(b"\r\n\r\n") {
|
match payload.read_until(b"\r\n\r\n")? {
|
||||||
None => {
|
None => {
|
||||||
if payload.eof {
|
if payload.eof {
|
||||||
Err(MultipartError::Incomplete)
|
Err(MultipartError::Incomplete)
|
||||||
@ -165,10 +167,10 @@ impl InnerMultipart {
|
|||||||
boundary: &str,
|
boundary: &str,
|
||||||
) -> Result<Option<bool>, MultipartError> {
|
) -> Result<Option<bool>, MultipartError> {
|
||||||
// TODO: need to read epilogue
|
// TODO: need to read epilogue
|
||||||
match payload.readline() {
|
match payload.readline()? {
|
||||||
None => {
|
None => {
|
||||||
if payload.eof {
|
if payload.eof {
|
||||||
Err(MultipartError::Incomplete)
|
Ok(Some(true))
|
||||||
} else {
|
} else {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
@ -198,11 +200,10 @@ impl InnerMultipart {
|
|||||||
) -> Result<Option<bool>, MultipartError> {
|
) -> Result<Option<bool>, MultipartError> {
|
||||||
let mut eof = false;
|
let mut eof = false;
|
||||||
loop {
|
loop {
|
||||||
match payload.readline() {
|
match payload.readline()? {
|
||||||
Some(chunk) => {
|
Some(chunk) => {
|
||||||
if chunk.is_empty() {
|
if chunk.is_empty() {
|
||||||
//ValueError("Could not find starting boundary %r"
|
return Err(MultipartError::Boundary);
|
||||||
//% (self._boundary))
|
|
||||||
}
|
}
|
||||||
if chunk.len() < boundary.len() {
|
if chunk.len() < boundary.len() {
|
||||||
continue;
|
continue;
|
||||||
@ -416,6 +417,8 @@ impl Stream for Field {
|
|||||||
}
|
}
|
||||||
|
|
||||||
inner.poll(&self.safety)
|
inner.poll(&self.safety)
|
||||||
|
} else if !self.safety.is_clean() {
|
||||||
|
return Err(MultipartError::NotConsumed);
|
||||||
} else {
|
} else {
|
||||||
Ok(Async::NotReady)
|
Ok(Async::NotReady)
|
||||||
}
|
}
|
||||||
@ -478,7 +481,7 @@ impl InnerField {
|
|||||||
if *size == 0 {
|
if *size == 0 {
|
||||||
Ok(Async::Ready(None))
|
Ok(Async::Ready(None))
|
||||||
} else {
|
} else {
|
||||||
match payload.read_max(*size) {
|
match payload.read_max(*size)? {
|
||||||
Some(mut chunk) => {
|
Some(mut chunk) => {
|
||||||
let len = cmp::min(chunk.len() as u64, *size);
|
let len = cmp::min(chunk.len() as u64, *size);
|
||||||
*size -= len;
|
*size -= len;
|
||||||
@ -505,47 +508,74 @@ impl InnerField {
|
|||||||
payload: &mut PayloadBuffer,
|
payload: &mut PayloadBuffer,
|
||||||
boundary: &str,
|
boundary: &str,
|
||||||
) -> Poll<Option<Bytes>, MultipartError> {
|
) -> Poll<Option<Bytes>, MultipartError> {
|
||||||
match payload.read_until(b"\r") {
|
let mut pos = 0;
|
||||||
None => {
|
|
||||||
if payload.eof {
|
let len = payload.buf.len();
|
||||||
Err(MultipartError::Incomplete)
|
if len == 0 {
|
||||||
|
return if payload.eof {
|
||||||
|
Err(MultipartError::Incomplete)
|
||||||
|
} else {
|
||||||
|
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 {
|
} else {
|
||||||
Ok(Async::NotReady)
|
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||||
|
// found boundary
|
||||||
|
return Ok(Async::Ready(None));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(mut chunk) => {
|
}
|
||||||
if chunk.len() == 1 {
|
|
||||||
payload.unprocessed(chunk);
|
loop {
|
||||||
match payload.read_exact(boundary.len() + 4) {
|
return if let Some(idx) = twoway::find_bytes(&payload.buf[pos..], b"\r") {
|
||||||
None => {
|
let cur = pos + idx;
|
||||||
if payload.eof {
|
|
||||||
Err(MultipartError::Incomplete)
|
// check if we have enough data for boundary detection
|
||||||
} else {
|
if cur + 4 > len {
|
||||||
Ok(Async::NotReady)
|
if cur > 0 {
|
||||||
}
|
Ok(Async::Ready(Some(payload.buf.split_to(cur).freeze())))
|
||||||
}
|
} else {
|
||||||
Some(mut chunk) => {
|
Ok(Async::NotReady)
|
||||||
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)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let to = chunk.len() - 1;
|
// check boundary
|
||||||
let ch = chunk.split_to(to);
|
if (&payload.buf[cur..cur + 2] == b"\r\n"
|
||||||
payload.unprocessed(chunk);
|
&& &payload.buf[cur + 2..cur + 4] == b"--")
|
||||||
Ok(Async::Ready(Some(ch)))
|
|| (&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 {
|
||||||
|
Ok(Async::Ready(Some(payload.buf.take().freeze())))
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -555,26 +585,27 @@ impl InnerField {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let result = if let Some(payload) = self.payload.as_ref().unwrap().get_mut(s) {
|
let result = if let Some(payload) = self.payload.as_ref().unwrap().get_mut(s) {
|
||||||
let res = if let Some(ref mut len) = self.length {
|
if !self.eof {
|
||||||
InnerField::read_len(payload, len)?
|
let res = if let Some(ref mut len) = self.length {
|
||||||
} else {
|
InnerField::read_len(payload, len)?
|
||||||
InnerField::read_stream(payload, &self.boundary)?
|
} else {
|
||||||
};
|
InnerField::read_stream(payload, &self.boundary)?
|
||||||
|
};
|
||||||
|
|
||||||
match res {
|
match res {
|
||||||
Async::NotReady => Async::NotReady,
|
Async::NotReady => return Ok(Async::NotReady),
|
||||||
Async::Ready(Some(bytes)) => Async::Ready(Some(bytes)),
|
Async::Ready(Some(bytes)) => return Ok(Async::Ready(Some(bytes))),
|
||||||
Async::Ready(None) => {
|
Async::Ready(None) => self.eof = true,
|
||||||
self.eof = true;
|
}
|
||||||
match payload.readline() {
|
}
|
||||||
None => Async::Ready(None),
|
|
||||||
Some(line) => {
|
match payload.readline()? {
|
||||||
if line.as_ref() != b"\r\n" {
|
None => Async::Ready(None),
|
||||||
log::warn!("multipart field did not read all the data or it is malformed");
|
Some(line) => {
|
||||||
}
|
if line.as_ref() != b"\r\n" {
|
||||||
Async::Ready(None)
|
log::warn!("multipart field did not read all the data or it is malformed");
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
Async::Ready(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -630,6 +661,7 @@ struct Safety {
|
|||||||
task: Option<Task>,
|
task: Option<Task>,
|
||||||
level: usize,
|
level: usize,
|
||||||
payload: Rc<PhantomData<bool>>,
|
payload: Rc<PhantomData<bool>>,
|
||||||
|
clean: Rc<Cell<bool>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Safety {
|
impl Safety {
|
||||||
@ -638,12 +670,17 @@ impl Safety {
|
|||||||
Safety {
|
Safety {
|
||||||
task: None,
|
task: None,
|
||||||
level: Rc::strong_count(&payload),
|
level: Rc::strong_count(&payload),
|
||||||
|
clean: Rc::new(Cell::new(true)),
|
||||||
payload,
|
payload,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn current(&self) -> bool {
|
fn current(&self) -> bool {
|
||||||
Rc::strong_count(&self.payload) == self.level
|
Rc::strong_count(&self.payload) == self.level && self.clean.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_clean(&self) -> bool {
|
||||||
|
self.clean.get()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -653,6 +690,7 @@ impl Clone for Safety {
|
|||||||
Safety {
|
Safety {
|
||||||
task: Some(current_task()),
|
task: Some(current_task()),
|
||||||
level: Rc::strong_count(&payload),
|
level: Rc::strong_count(&payload),
|
||||||
|
clean: self.clean.clone(),
|
||||||
payload,
|
payload,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -662,7 +700,7 @@ impl Drop for Safety {
|
|||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// parent task is dead
|
// parent task is dead
|
||||||
if Rc::strong_count(&self.payload) != self.level {
|
if Rc::strong_count(&self.payload) != self.level {
|
||||||
panic!("Safety get dropped but it is not from top-most task");
|
self.clean.set(true);
|
||||||
}
|
}
|
||||||
if let Some(task) = self.task.take() {
|
if let Some(task) = self.task.take() {
|
||||||
task.notify()
|
task.notify()
|
||||||
@ -704,7 +742,7 @@ impl PayloadBuffer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Read exact number of bytes
|
/// Read exact number of bytes
|
||||||
#[inline]
|
#[cfg(test)]
|
||||||
fn read_exact(&mut self, size: usize) -> Option<Bytes> {
|
fn read_exact(&mut self, size: usize) -> Option<Bytes> {
|
||||||
if size <= self.buf.len() {
|
if size <= self.buf.len() {
|
||||||
Some(self.buf.split_to(size).freeze())
|
Some(self.buf.split_to(size).freeze())
|
||||||
@ -713,23 +751,31 @@ impl PayloadBuffer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_max(&mut self, size: u64) -> Option<Bytes> {
|
fn read_max(&mut self, size: u64) -> Result<Option<Bytes>, MultipartError> {
|
||||||
if !self.buf.is_empty() {
|
if !self.buf.is_empty() {
|
||||||
let size = std::cmp::min(self.buf.len() as u64, size) as usize;
|
let size = std::cmp::min(self.buf.len() as u64, size) as usize;
|
||||||
Some(self.buf.split_to(size).freeze())
|
Ok(Some(self.buf.split_to(size).freeze()))
|
||||||
|
} else if self.eof {
|
||||||
|
Err(MultipartError::Incomplete)
|
||||||
} else {
|
} else {
|
||||||
None
|
Ok(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read until specified ending
|
/// Read until specified ending
|
||||||
pub fn read_until(&mut self, line: &[u8]) -> Option<Bytes> {
|
pub fn read_until(&mut self, line: &[u8]) -> Result<Option<Bytes>, MultipartError> {
|
||||||
twoway::find_bytes(&self.buf, line)
|
let res = twoway::find_bytes(&self.buf, line)
|
||||||
.map(|idx| self.buf.split_to(idx + line.len()).freeze())
|
.map(|idx| self.buf.split_to(idx + line.len()).freeze());
|
||||||
|
|
||||||
|
if res.is_none() && self.eof {
|
||||||
|
Err(MultipartError::Incomplete)
|
||||||
|
} else {
|
||||||
|
Ok(res)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read bytes until new line delimiter
|
/// Read bytes until new line delimiter
|
||||||
pub fn readline(&mut self) -> Option<Bytes> {
|
pub fn readline(&mut self) -> Result<Option<Bytes>, MultipartError> {
|
||||||
self.read_until(b"\n")
|
self.read_until(b"\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -875,6 +921,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]
|
#[test]
|
||||||
fn test_basic() {
|
fn test_basic() {
|
||||||
run_on(|| {
|
run_on(|| {
|
||||||
@ -883,7 +1001,7 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(payload.buf.len(), 0);
|
assert_eq!(payload.buf.len(), 0);
|
||||||
payload.poll_stream().unwrap();
|
payload.poll_stream().unwrap();
|
||||||
assert_eq!(None, payload.read_max(1));
|
assert_eq!(None, payload.read_max(1).unwrap());
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -893,14 +1011,14 @@ mod tests {
|
|||||||
let (mut sender, payload) = Payload::create(false);
|
let (mut sender, payload) = Payload::create(false);
|
||||||
let mut payload = PayloadBuffer::new(payload);
|
let mut payload = PayloadBuffer::new(payload);
|
||||||
|
|
||||||
assert_eq!(None, payload.read_max(4));
|
assert_eq!(None, payload.read_max(4).unwrap());
|
||||||
sender.feed_data(Bytes::from("data"));
|
sender.feed_data(Bytes::from("data"));
|
||||||
sender.feed_eof();
|
sender.feed_eof();
|
||||||
payload.poll_stream().unwrap();
|
payload.poll_stream().unwrap();
|
||||||
|
|
||||||
assert_eq!(Some(Bytes::from("data")), payload.read_max(4));
|
assert_eq!(Some(Bytes::from("data")), payload.read_max(4).unwrap());
|
||||||
assert_eq!(payload.buf.len(), 0);
|
assert_eq!(payload.buf.len(), 0);
|
||||||
assert_eq!(None, payload.read_max(1));
|
assert!(payload.read_max(1).is_err());
|
||||||
assert!(payload.eof);
|
assert!(payload.eof);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -910,7 +1028,7 @@ mod tests {
|
|||||||
run_on(|| {
|
run_on(|| {
|
||||||
let (mut sender, payload) = Payload::create(false);
|
let (mut sender, payload) = Payload::create(false);
|
||||||
let mut payload = PayloadBuffer::new(payload);
|
let mut payload = PayloadBuffer::new(payload);
|
||||||
assert_eq!(None, payload.read_max(1));
|
assert_eq!(None, payload.read_max(1).unwrap());
|
||||||
sender.set_error(PayloadError::Incomplete(None));
|
sender.set_error(PayloadError::Incomplete(None));
|
||||||
payload.poll_stream().err().unwrap();
|
payload.poll_stream().err().unwrap();
|
||||||
})
|
})
|
||||||
@ -927,10 +1045,10 @@ mod tests {
|
|||||||
payload.poll_stream().unwrap();
|
payload.poll_stream().unwrap();
|
||||||
assert_eq!(payload.buf.len(), 10);
|
assert_eq!(payload.buf.len(), 10);
|
||||||
|
|
||||||
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5));
|
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5).unwrap());
|
||||||
assert_eq!(payload.buf.len(), 5);
|
assert_eq!(payload.buf.len(), 5);
|
||||||
|
|
||||||
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5));
|
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap());
|
||||||
assert_eq!(payload.buf.len(), 0);
|
assert_eq!(payload.buf.len(), 0);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -961,16 +1079,22 @@ mod tests {
|
|||||||
let (mut sender, payload) = Payload::create(false);
|
let (mut sender, payload) = Payload::create(false);
|
||||||
let mut payload = PayloadBuffer::new(payload);
|
let mut payload = PayloadBuffer::new(payload);
|
||||||
|
|
||||||
assert_eq!(None, payload.read_until(b"ne"));
|
assert_eq!(None, payload.read_until(b"ne").unwrap());
|
||||||
|
|
||||||
sender.feed_data(Bytes::from("line1"));
|
sender.feed_data(Bytes::from("line1"));
|
||||||
sender.feed_data(Bytes::from("line2"));
|
sender.feed_data(Bytes::from("line2"));
|
||||||
payload.poll_stream().unwrap();
|
payload.poll_stream().unwrap();
|
||||||
|
|
||||||
assert_eq!(Some(Bytes::from("line")), payload.read_until(b"ne"));
|
assert_eq!(
|
||||||
|
Some(Bytes::from("line")),
|
||||||
|
payload.read_until(b"ne").unwrap()
|
||||||
|
);
|
||||||
assert_eq!(payload.buf.len(), 6);
|
assert_eq!(payload.buf.len(), 6);
|
||||||
|
|
||||||
assert_eq!(Some(Bytes::from("1line2")), payload.read_until(b"2"));
|
assert_eq!(
|
||||||
|
Some(Bytes::from("1line2")),
|
||||||
|
payload.read_until(b"2").unwrap()
|
||||||
|
);
|
||||||
assert_eq!(payload.buf.len(), 0);
|
assert_eq!(payload.buf.len(), 0);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,34 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-07-08
|
||||||
|
|
||||||
|
* Enhanced ``actix-session`` to facilitate state changes. Use ``Session.renew()``
|
||||||
|
at successful login to cycle a session (new key/cookie but keeps state).
|
||||||
|
Use ``Session.purge()`` at logout to invalid a session cookie (and remove
|
||||||
|
from redis cache, if applicable).
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-06-03
|
||||||
|
|
||||||
|
* Fix optional cookie session support
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-05-18
|
||||||
|
|
||||||
|
* Use actix-web 1.0.0-rc
|
||||||
|
|
||||||
|
## [0.1.0-beta.4] - 2019-05-12
|
||||||
|
|
||||||
|
* Use actix-web 1.0.0-beta.4
|
||||||
|
|
||||||
|
## [0.1.0-beta.2] - 2019-04-28
|
||||||
|
|
||||||
|
* Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest
|
||||||
|
|
||||||
|
## [0.1.0-beta.1] - 2019-04-20
|
||||||
|
|
||||||
|
* Update actix-web to beta.1
|
||||||
|
|
||||||
|
* `CookieSession::max_age()` accepts value in seconds
|
||||||
|
|
||||||
## [0.1.0-alpha.6] - 2019-04-14
|
## [0.1.0-alpha.6] - 2019-04-14
|
||||||
|
|
||||||
* Update actix-web alpha.6
|
* Update actix-web alpha.6
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-session"
|
name = "actix-session"
|
||||||
version = "0.1.0-alpha.6"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Session for actix web framework."
|
description = "Session for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -24,15 +24,15 @@ default = ["cookie-session"]
|
|||||||
cookie-session = ["actix-web/secure-cookies"]
|
cookie-session = ["actix-web/secure-cookies"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-alpha.6"
|
actix-web = "1.0.0"
|
||||||
actix-service = "0.3.4"
|
actix-service = "0.4.1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.2.0"
|
hashbrown = "0.5.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
time = "0.1"
|
time = "0.1.42"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
|
1
actix-session/LICENSE-APACHE
Symbolic link
1
actix-session/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-session/LICENSE-MIT
Symbolic link
1
actix-session/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -1 +1,9 @@
|
|||||||
# Session for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-session) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
# Session for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-session) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [User Guide](https://actix.rs/docs/)
|
||||||
|
* [API Documentation](https://docs.rs/actix-session/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-session](https://crates.io/crates/actix-session)
|
||||||
|
* Minimum supported Rust version: 1.34 or later
|
||||||
|
@ -27,9 +27,8 @@ use derive_more::{Display, From};
|
|||||||
use futures::future::{ok, Future, FutureResult};
|
use futures::future::{ok, Future, FutureResult};
|
||||||
use futures::Poll;
|
use futures::Poll;
|
||||||
use serde_json::error::Error as JsonError;
|
use serde_json::error::Error as JsonError;
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
use crate::Session;
|
use crate::{Session, SessionStatus};
|
||||||
|
|
||||||
/// Errors that can occur during handling cookie session
|
/// Errors that can occur during handling cookie session
|
||||||
#[derive(Debug, From, Display)]
|
#[derive(Debug, From, Display)]
|
||||||
@ -57,7 +56,7 @@ struct CookieSessionInner {
|
|||||||
domain: Option<String>,
|
domain: Option<String>,
|
||||||
secure: bool,
|
secure: bool,
|
||||||
http_only: bool,
|
http_only: bool,
|
||||||
max_age: Option<Duration>,
|
max_age: Option<time::Duration>,
|
||||||
same_site: Option<SameSite>,
|
same_site: Option<SameSite>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -120,7 +119,20 @@ impl CookieSessionInner {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load(&self, req: &ServiceRequest) -> HashMap<String, String> {
|
/// invalidates session cookie
|
||||||
|
fn remove_cookie<B>(&self, res: &mut ServiceResponse<B>) -> Result<(), Error> {
|
||||||
|
let mut cookie = Cookie::named(self.name.clone());
|
||||||
|
cookie.set_value("");
|
||||||
|
cookie.set_max_age(time::Duration::seconds(0));
|
||||||
|
cookie.set_expires(time::now() - time::Duration::days(365));
|
||||||
|
|
||||||
|
let val = HeaderValue::from_str(&cookie.to_string())?;
|
||||||
|
res.headers_mut().append(SET_COOKIE, val);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(&self, req: &ServiceRequest) -> (bool, HashMap<String, String>) {
|
||||||
if let Ok(cookies) = req.cookies() {
|
if let Ok(cookies) = req.cookies() {
|
||||||
for cookie in cookies.iter() {
|
for cookie in cookies.iter() {
|
||||||
if cookie.name() == self.name {
|
if cookie.name() == self.name {
|
||||||
@ -135,13 +147,13 @@ impl CookieSessionInner {
|
|||||||
};
|
};
|
||||||
if let Some(cookie) = cookie_opt {
|
if let Some(cookie) = cookie_opt {
|
||||||
if let Ok(val) = serde_json::from_str(cookie.value()) {
|
if let Ok(val) = serde_json::from_str(cookie.value()) {
|
||||||
return val;
|
return (false, val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
HashMap::new()
|
(true, HashMap::new())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -250,7 +262,12 @@ impl CookieSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the `max-age` field in the session cookie being built.
|
/// Sets the `max-age` field in the session cookie being built.
|
||||||
pub fn max_age(mut self, value: Duration) -> CookieSession {
|
pub fn max_age(self, seconds: i64) -> CookieSession {
|
||||||
|
self.max_age_time(time::Duration::seconds(seconds))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the `max-age` field in the session cookie being built.
|
||||||
|
pub fn max_age_time(mut self, value: time::Duration) -> CookieSession {
|
||||||
Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
|
Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@ -292,22 +309,43 @@ where
|
|||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
type Error = S::Error;
|
||||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.poll_ready()
|
self.service.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// On first request, a new session cookie is returned in response, regardless
|
||||||
|
/// of whether any session state is set. With subsequent requests, if the
|
||||||
|
/// session state changes, then set-cookie is returned in response. As
|
||||||
|
/// a user logs out, call session.purge() to set SessionStatus accordingly
|
||||||
|
/// and this will trigger removal of the session cookie in the response.
|
||||||
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
||||||
let inner = self.inner.clone();
|
let inner = self.inner.clone();
|
||||||
let state = self.inner.load(&req);
|
let (is_new, state) = self.inner.load(&req);
|
||||||
Session::set_session(state.into_iter(), &mut req);
|
Session::set_session(state.into_iter(), &mut req);
|
||||||
|
|
||||||
Box::new(self.service.call(req).map(move |mut res| {
|
Box::new(self.service.call(req).map(move |mut res| {
|
||||||
if let Some(state) = Session::get_changes(&mut res) {
|
match Session::get_changes(&mut res) {
|
||||||
res.checked_expr(|res| inner.set_cookie(res, state))
|
(SessionStatus::Changed, Some(state))
|
||||||
} else {
|
| (SessionStatus::Renewed, Some(state)) => {
|
||||||
res
|
res.checked_expr(|res| inner.set_cookie(res, state))
|
||||||
|
}
|
||||||
|
(SessionStatus::Unchanged, _) =>
|
||||||
|
// set a new session cookie upon first request (new client)
|
||||||
|
{
|
||||||
|
if is_new {
|
||||||
|
let state: HashMap<String, String> = HashMap::new();
|
||||||
|
res.checked_expr(|res| inner.set_cookie(res, state.into_iter()))
|
||||||
|
} else {
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(SessionStatus::Purged, _) => {
|
||||||
|
inner.remove_cookie(&mut res);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
_ => res,
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@ -317,6 +355,7 @@ where
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use actix_web::{test, web, App};
|
use actix_web::{test, web, App};
|
||||||
|
use bytes::Bytes;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cookie_session() {
|
fn cookie_session() {
|
||||||
@ -338,6 +377,26 @@ mod tests {
|
|||||||
.is_some());
|
.is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn private_cookie() {
|
||||||
|
let mut app = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(CookieSession::private(&[0; 32]).secure(false))
|
||||||
|
.service(web::resource("/").to(|ses: Session| {
|
||||||
|
let _ = ses.set("counter", 100);
|
||||||
|
"test"
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
let request = test::TestRequest::get().to_request();
|
||||||
|
let response = test::block_on(app.call(request)).unwrap();
|
||||||
|
assert!(response
|
||||||
|
.response()
|
||||||
|
.cookies()
|
||||||
|
.find(|c| c.name() == "actix-session")
|
||||||
|
.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cookie_session_extractor() {
|
fn cookie_session_extractor() {
|
||||||
let mut app = test::init_service(
|
let mut app = test::init_service(
|
||||||
@ -357,4 +416,44 @@ mod tests {
|
|||||||
.find(|c| c.name() == "actix-session")
|
.find(|c| c.name() == "actix-session")
|
||||||
.is_some());
|
.is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn basics() {
|
||||||
|
let mut app = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(
|
||||||
|
CookieSession::signed(&[0; 32])
|
||||||
|
.path("/test/")
|
||||||
|
.name("actix-test")
|
||||||
|
.domain("localhost")
|
||||||
|
.http_only(true)
|
||||||
|
.same_site(SameSite::Lax)
|
||||||
|
.max_age(100),
|
||||||
|
)
|
||||||
|
.service(web::resource("/").to(|ses: Session| {
|
||||||
|
let _ = ses.set("counter", 100);
|
||||||
|
"test"
|
||||||
|
}))
|
||||||
|
.service(web::resource("/test/").to(|ses: Session| {
|
||||||
|
let val: usize = ses.get("counter").unwrap().unwrap();
|
||||||
|
format!("counter: {}", val)
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
let request = test::TestRequest::get().to_request();
|
||||||
|
let response = test::block_on(app.call(request)).unwrap();
|
||||||
|
let cookie = response
|
||||||
|
.response()
|
||||||
|
.cookies()
|
||||||
|
.find(|c| c.name() == "actix-test")
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
assert_eq!(cookie.path().unwrap(), "/test/");
|
||||||
|
|
||||||
|
let request = test::TestRequest::with_uri("/test/")
|
||||||
|
.cookie(cookie)
|
||||||
|
.to_request();
|
||||||
|
let body = test::read_response(&mut app, request);
|
||||||
|
assert_eq!(body, Bytes::from_static(b"counter: 100"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -52,7 +52,9 @@ use serde::de::DeserializeOwned;
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json;
|
use serde_json;
|
||||||
|
|
||||||
|
#[cfg(feature = "cookie-session")]
|
||||||
mod cookie;
|
mod cookie;
|
||||||
|
#[cfg(feature = "cookie-session")]
|
||||||
pub use crate::cookie::CookieSession;
|
pub use crate::cookie::CookieSession;
|
||||||
|
|
||||||
/// The high-level interface you use to modify session data.
|
/// The high-level interface you use to modify session data.
|
||||||
@ -79,10 +81,40 @@ pub use crate::cookie::CookieSession;
|
|||||||
/// ```
|
/// ```
|
||||||
pub struct Session(Rc<RefCell<SessionInner>>);
|
pub struct Session(Rc<RefCell<SessionInner>>);
|
||||||
|
|
||||||
|
/// Helper trait that allows to get session
|
||||||
|
pub trait UserSession {
|
||||||
|
fn get_session(&mut self) -> Session;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserSession for HttpRequest {
|
||||||
|
fn get_session(&mut self) -> Session {
|
||||||
|
Session::get_session(&mut *self.extensions_mut())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserSession for ServiceRequest {
|
||||||
|
fn get_session(&mut self) -> Session {
|
||||||
|
Session::get_session(&mut *self.extensions_mut())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(PartialEq, Clone, Debug)]
|
||||||
|
pub enum SessionStatus {
|
||||||
|
Changed,
|
||||||
|
Purged,
|
||||||
|
Renewed,
|
||||||
|
Unchanged,
|
||||||
|
}
|
||||||
|
impl Default for SessionStatus {
|
||||||
|
fn default() -> SessionStatus {
|
||||||
|
SessionStatus::Unchanged
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct SessionInner {
|
struct SessionInner {
|
||||||
state: HashMap<String, String>,
|
state: HashMap<String, String>,
|
||||||
changed: bool,
|
pub status: SessionStatus,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Session {
|
impl Session {
|
||||||
@ -98,25 +130,46 @@ impl Session {
|
|||||||
/// Set a `value` from the session.
|
/// Set a `value` from the session.
|
||||||
pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
|
pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
|
||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
inner.changed = true;
|
if inner.status != SessionStatus::Purged {
|
||||||
inner
|
inner.status = SessionStatus::Changed;
|
||||||
.state
|
inner
|
||||||
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
.state
|
||||||
|
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove value from the session.
|
/// Remove value from the session.
|
||||||
pub fn remove(&self, key: &str) {
|
pub fn remove(&self, key: &str) {
|
||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
inner.changed = true;
|
if inner.status != SessionStatus::Purged {
|
||||||
inner.state.remove(key);
|
inner.status = SessionStatus::Changed;
|
||||||
|
inner.state.remove(key);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Clear the session.
|
/// Clear the session.
|
||||||
pub fn clear(&self) {
|
pub fn clear(&self) {
|
||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
inner.changed = true;
|
if inner.status != SessionStatus::Purged {
|
||||||
inner.state.clear()
|
inner.status = SessionStatus::Changed;
|
||||||
|
inner.state.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes session, both client and server side.
|
||||||
|
pub fn purge(&self) {
|
||||||
|
let mut inner = self.0.borrow_mut();
|
||||||
|
inner.status = SessionStatus::Purged;
|
||||||
|
inner.state.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renews the session key, assigning existing session state to new key.
|
||||||
|
pub fn renew(&self) {
|
||||||
|
let mut inner = self.0.borrow_mut();
|
||||||
|
if inner.status != SessionStatus::Purged {
|
||||||
|
inner.status = SessionStatus::Renewed;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_session(
|
pub fn set_session(
|
||||||
@ -130,7 +183,10 @@ impl Session {
|
|||||||
|
|
||||||
pub fn get_changes<B>(
|
pub fn get_changes<B>(
|
||||||
res: &mut ServiceResponse<B>,
|
res: &mut ServiceResponse<B>,
|
||||||
) -> Option<impl Iterator<Item = (String, String)>> {
|
) -> (
|
||||||
|
SessionStatus,
|
||||||
|
Option<impl Iterator<Item = (String, String)>>,
|
||||||
|
) {
|
||||||
if let Some(s_impl) = res
|
if let Some(s_impl) = res
|
||||||
.request()
|
.request()
|
||||||
.extensions()
|
.extensions()
|
||||||
@ -138,9 +194,9 @@ impl Session {
|
|||||||
{
|
{
|
||||||
let state =
|
let state =
|
||||||
std::mem::replace(&mut s_impl.borrow_mut().state, HashMap::new());
|
std::mem::replace(&mut s_impl.borrow_mut().state, HashMap::new());
|
||||||
Some(state.into_iter())
|
(s_impl.borrow().status.clone(), Some(state.into_iter()))
|
||||||
} else {
|
} else {
|
||||||
None
|
(SessionStatus::Unchanged, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -205,7 +261,40 @@ mod tests {
|
|||||||
session.remove("key");
|
session.remove("key");
|
||||||
|
|
||||||
let mut res = req.into_response(HttpResponse::Ok().finish());
|
let mut res = req.into_response(HttpResponse::Ok().finish());
|
||||||
let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
|
let (_status, state) = Session::get_changes(&mut res);
|
||||||
|
let changes: Vec<_> = state.unwrap().collect();
|
||||||
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_session() {
|
||||||
|
let mut req = test::TestRequest::default().to_srv_request();
|
||||||
|
|
||||||
|
Session::set_session(
|
||||||
|
vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
|
||||||
|
&mut req,
|
||||||
|
);
|
||||||
|
|
||||||
|
let session = req.get_session();
|
||||||
|
let res = session.get::<String>("key").unwrap();
|
||||||
|
assert_eq!(res, Some("value".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn purge_session() {
|
||||||
|
let mut req = test::TestRequest::default().to_srv_request();
|
||||||
|
let session = Session::get_session(&mut *req.extensions_mut());
|
||||||
|
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
|
||||||
|
session.purge();
|
||||||
|
assert_eq!(session.0.borrow().status, SessionStatus::Purged);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renew_session() {
|
||||||
|
let mut req = test::TestRequest::default().to_srv_request();
|
||||||
|
let session = Session::get_session(&mut *req.extensions_mut());
|
||||||
|
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
|
||||||
|
session.renew();
|
||||||
|
assert_eq!(session.0.borrow().status, SessionStatus::Renewed);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,13 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-06-28
|
||||||
|
|
||||||
|
* Allow to use custom ws codec with `WebsocketContext` #925
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-05-29
|
||||||
|
|
||||||
|
* Update actix-http and actix-web
|
||||||
|
|
||||||
## [0.1.0-alpha.3] - 2019-04-02
|
## [0.1.0-alpha.3] - 2019-04-02
|
||||||
|
|
||||||
* Update actix-http and actix-web
|
* Update actix-http and actix-web
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web-actors"
|
name = "actix-web-actors"
|
||||||
version = "1.0.0-alpha.3"
|
version = "1.0.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix actors support for actix web framework."
|
description = "Actix actors support for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -18,13 +18,13 @@ name = "actix_web_actors"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.8.0"
|
actix = "0.8.3"
|
||||||
actix-web = "1.0.0-alpha.5"
|
actix-web = "1.0.3"
|
||||||
actix-http = "0.1.0-alpha.5"
|
actix-http = "0.2.5"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
|
1
actix-web-actors/LICENSE-APACHE
Symbolic link
1
actix-web-actors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-web-actors/LICENSE-MIT
Symbolic link
1
actix-web-actors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -1 +1,8 @@
|
|||||||
Actix actors support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-web-actors) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
Actix actors support for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-web-actors) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [API Documentation](https://docs.rs/actix-web-actors/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-web-actors](https://crates.io/crates/actix-web-actors)
|
||||||
|
* Minimum supported Rust version: 1.33 or later
|
||||||
|
@ -177,9 +177,30 @@ where
|
|||||||
inner: ContextParts::new(mb.sender_producer()),
|
inner: ContextParts::new(mb.sender_producer()),
|
||||||
messages: VecDeque::new(),
|
messages: VecDeque::new(),
|
||||||
};
|
};
|
||||||
ctx.add_stream(WsStream::new(stream));
|
ctx.add_stream(WsStream::new(stream, Codec::new()));
|
||||||
|
|
||||||
WebsocketContextFut::new(ctx, actor, mb)
|
WebsocketContextFut::new(ctx, actor, mb, Codec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Create a new Websocket context from a request, an actor, and a codec
|
||||||
|
pub fn with_codec<S>(
|
||||||
|
actor: A,
|
||||||
|
stream: S,
|
||||||
|
codec: Codec,
|
||||||
|
) -> impl Stream<Item = Bytes, Error = Error>
|
||||||
|
where
|
||||||
|
A: StreamHandler<Message, ProtocolError>,
|
||||||
|
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||||
|
{
|
||||||
|
let mb = Mailbox::default();
|
||||||
|
let mut ctx = WebsocketContext {
|
||||||
|
inner: ContextParts::new(mb.sender_producer()),
|
||||||
|
messages: VecDeque::new(),
|
||||||
|
};
|
||||||
|
ctx.add_stream(WsStream::new(stream, codec));
|
||||||
|
|
||||||
|
WebsocketContextFut::new(ctx, actor, mb, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new Websocket context
|
/// Create a new Websocket context
|
||||||
@ -197,11 +218,11 @@ where
|
|||||||
inner: ContextParts::new(mb.sender_producer()),
|
inner: ContextParts::new(mb.sender_producer()),
|
||||||
messages: VecDeque::new(),
|
messages: VecDeque::new(),
|
||||||
};
|
};
|
||||||
ctx.add_stream(WsStream::new(stream));
|
ctx.add_stream(WsStream::new(stream, Codec::new()));
|
||||||
|
|
||||||
let act = f(&mut ctx);
|
let act = f(&mut ctx);
|
||||||
|
|
||||||
WebsocketContextFut::new(ctx, act, mb)
|
WebsocketContextFut::new(ctx, act, mb, Codec::new())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -288,11 +309,11 @@ impl<A> WebsocketContextFut<A>
|
|||||||
where
|
where
|
||||||
A: Actor<Context = WebsocketContext<A>>,
|
A: Actor<Context = WebsocketContext<A>>,
|
||||||
{
|
{
|
||||||
fn new(ctx: WebsocketContext<A>, act: A, mailbox: Mailbox<A>) -> Self {
|
fn new(ctx: WebsocketContext<A>, act: A, mailbox: Mailbox<A>, codec: Codec) -> Self {
|
||||||
let fut = ContextFut::new(ctx, act, mailbox);
|
let fut = ContextFut::new(ctx, act, mailbox);
|
||||||
WebsocketContextFut {
|
WebsocketContextFut {
|
||||||
fut,
|
fut,
|
||||||
encoder: Codec::new(),
|
encoder: codec,
|
||||||
buf: BytesMut::new(),
|
buf: BytesMut::new(),
|
||||||
closed: false,
|
closed: false,
|
||||||
}
|
}
|
||||||
@ -353,10 +374,10 @@ impl<S> WsStream<S>
|
|||||||
where
|
where
|
||||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||||
{
|
{
|
||||||
fn new(stream: S) -> Self {
|
fn new(stream: S, codec: Codec) -> Self {
|
||||||
Self {
|
Self {
|
||||||
stream,
|
stream,
|
||||||
decoder: Codec::new(),
|
decoder: codec,
|
||||||
buf: BytesMut::new(),
|
buf: BytesMut::new(),
|
||||||
closed: false,
|
closed: false,
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,21 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.2] - 2019-06-04
|
||||||
|
|
||||||
|
* Add macros for head, options, trace, connect and patch http methods
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-06-01
|
||||||
|
|
||||||
|
* Add syn "extra-traits" feature
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-05-18
|
||||||
|
|
||||||
|
* Release
|
||||||
|
|
||||||
|
## [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
|
## [0.1.0-alpha.6] - 2019-04-14
|
||||||
|
|
||||||
* Gen code for actix-web 1.0.0-alpha.6
|
* Gen code for actix-web 1.0.0-alpha.6
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web-codegen"
|
name = "actix-web-codegen"
|
||||||
version = "0.1.0-alpha.6"
|
version = "0.1.2"
|
||||||
description = "Actix web proc macros"
|
description = "Actix web proc macros"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
@ -12,11 +12,11 @@ workspace = ".."
|
|||||||
proc-macro = true
|
proc-macro = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
quote = "0.6"
|
quote = "0.6.12"
|
||||||
syn = { version = "0.15", features = ["full", "parsing"] }
|
syn = { version = "0.15.34", features = ["full", "parsing", "extra-traits"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "1.0.0-alpha.6" }
|
actix-web = { version = "1.0.0" }
|
||||||
actix-http = { version = "0.1.0-alpha.5", features=["ssl"] }
|
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.1.0-alpha.3", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
futures = { version = "0.1" }
|
futures = { version = "0.1" }
|
||||||
|
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-web-codegen/LICENSE-MIT
Symbolic link
1
actix-web-codegen/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -11,6 +11,11 @@
|
|||||||
//! - [post](attr.post.html)
|
//! - [post](attr.post.html)
|
||||||
//! - [put](attr.put.html)
|
//! - [put](attr.put.html)
|
||||||
//! - [delete](attr.delete.html)
|
//! - [delete](attr.delete.html)
|
||||||
|
//! - [head](attr.head.html)
|
||||||
|
//! - [connect](attr.connect.html)
|
||||||
|
//! - [options](attr.options.html)
|
||||||
|
//! - [trace](attr.trace.html)
|
||||||
|
//! - [patch](attr.patch.html)
|
||||||
//!
|
//!
|
||||||
//! ### Attributes:
|
//! ### Attributes:
|
||||||
//!
|
//!
|
||||||
@ -92,3 +97,63 @@ pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
|
|||||||
let gen = route::Args::new(&args, input, route::GuardType::Delete);
|
let gen = route::Args::new(&args, input, route::GuardType::Delete);
|
||||||
gen.generate()
|
gen.generate()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates route handler with `HEAD` method guard.
|
||||||
|
///
|
||||||
|
/// Syntax: `#[head("path"[, attributes])]`
|
||||||
|
///
|
||||||
|
/// Attributes are the same as in [head](attr.head.html)
|
||||||
|
#[proc_macro_attribute]
|
||||||
|
pub fn head(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||||
|
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||||
|
let gen = route::Args::new(&args, input, route::GuardType::Head);
|
||||||
|
gen.generate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates route handler with `CONNECT` method guard.
|
||||||
|
///
|
||||||
|
/// Syntax: `#[connect("path"[, attributes])]`
|
||||||
|
///
|
||||||
|
/// Attributes are the same as in [connect](attr.connect.html)
|
||||||
|
#[proc_macro_attribute]
|
||||||
|
pub fn connect(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||||
|
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||||
|
let gen = route::Args::new(&args, input, route::GuardType::Connect);
|
||||||
|
gen.generate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates route handler with `OPTIONS` method guard.
|
||||||
|
///
|
||||||
|
/// Syntax: `#[options("path"[, attributes])]`
|
||||||
|
///
|
||||||
|
/// Attributes are the same as in [options](attr.options.html)
|
||||||
|
#[proc_macro_attribute]
|
||||||
|
pub fn options(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||||
|
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||||
|
let gen = route::Args::new(&args, input, route::GuardType::Options);
|
||||||
|
gen.generate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates route handler with `TRACE` method guard.
|
||||||
|
///
|
||||||
|
/// Syntax: `#[trace("path"[, attributes])]`
|
||||||
|
///
|
||||||
|
/// Attributes are the same as in [trace](attr.trace.html)
|
||||||
|
#[proc_macro_attribute]
|
||||||
|
pub fn trace(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||||
|
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||||
|
let gen = route::Args::new(&args, input, route::GuardType::Trace);
|
||||||
|
gen.generate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates route handler with `PATCH` method guard.
|
||||||
|
///
|
||||||
|
/// Syntax: `#[patch("path"[, attributes])]`
|
||||||
|
///
|
||||||
|
/// Attributes are the same as in [patch](attr.patch.html)
|
||||||
|
#[proc_macro_attribute]
|
||||||
|
pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||||
|
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||||
|
let gen = route::Args::new(&args, input, route::GuardType::Patch);
|
||||||
|
gen.generate()
|
||||||
|
}
|
||||||
|
@ -25,6 +25,11 @@ pub enum GuardType {
|
|||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Delete,
|
Delete,
|
||||||
|
Head,
|
||||||
|
Connect,
|
||||||
|
Options,
|
||||||
|
Trace,
|
||||||
|
Patch,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for GuardType {
|
impl fmt::Display for GuardType {
|
||||||
@ -34,6 +39,11 @@ impl fmt::Display for GuardType {
|
|||||||
&GuardType::Post => write!(f, "Post"),
|
&GuardType::Post => write!(f, "Post"),
|
||||||
&GuardType::Put => write!(f, "Put"),
|
&GuardType::Put => write!(f, "Put"),
|
||||||
&GuardType::Delete => write!(f, "Delete"),
|
&GuardType::Delete => write!(f, "Delete"),
|
||||||
|
&GuardType::Head => write!(f, "Head"),
|
||||||
|
&GuardType::Connect => write!(f, "Connect"),
|
||||||
|
&GuardType::Options => write!(f, "Options"),
|
||||||
|
&GuardType::Trace => write!(f, "Trace"),
|
||||||
|
&GuardType::Patch => write!(f, "Patch"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_web::{http, App, HttpResponse, Responder};
|
use actix_web::{http, web::Path, App, HttpResponse, Responder};
|
||||||
use actix_web_codegen::get;
|
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
|
||||||
use futures::{future, Future};
|
use futures::{future, Future};
|
||||||
|
|
||||||
#[get("/test")]
|
#[get("/test")]
|
||||||
@ -9,6 +9,41 @@ fn test() -> impl Responder {
|
|||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[put("/test")]
|
||||||
|
fn put_test() -> impl Responder {
|
||||||
|
HttpResponse::Created()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[patch("/test")]
|
||||||
|
fn patch_test() -> impl Responder {
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/test")]
|
||||||
|
fn post_test() -> impl Responder {
|
||||||
|
HttpResponse::NoContent()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[head("/test")]
|
||||||
|
fn head_test() -> impl Responder {
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[connect("/test")]
|
||||||
|
fn connect_test() -> impl Responder {
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[options("/test")]
|
||||||
|
fn options_test() -> impl Responder {
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[trace("/test")]
|
||||||
|
fn trace_test() -> impl Responder {
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
#[get("/test")]
|
#[get("/test")]
|
||||||
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
||||||
future::ok(HttpResponse::Ok().finish())
|
future::ok(HttpResponse::Ok().finish())
|
||||||
@ -19,13 +54,94 @@ fn auto_sync() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
|||||||
future::ok(HttpResponse::Ok().finish())
|
future::ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[put("/test/{param}")]
|
||||||
|
fn put_param_test(_: Path<String>) -> impl Responder {
|
||||||
|
HttpResponse::Created()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[delete("/test/{param}")]
|
||||||
|
fn delete_param_test(_: Path<String>) -> impl Responder {
|
||||||
|
HttpResponse::NoContent()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/test/{param}")]
|
||||||
|
fn get_param_test(_: Path<String>) -> impl Responder {
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_params() {
|
||||||
|
let mut srv = TestServer::new(|| {
|
||||||
|
HttpService::new(
|
||||||
|
App::new()
|
||||||
|
.service(get_param_test)
|
||||||
|
.service(put_param_test)
|
||||||
|
.service(delete_param_test),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::GET, srv.url("/test/it"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert_eq!(response.status(), http::StatusCode::OK);
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::PUT, srv.url("/test/it"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert_eq!(response.status(), http::StatusCode::CREATED);
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::DELETE, srv.url("/test/it"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_body() {
|
fn test_body() {
|
||||||
let mut srv = TestServer::new(|| HttpService::new(App::new().service(test)));
|
let mut srv = TestServer::new(|| {
|
||||||
|
HttpService::new(
|
||||||
|
App::new()
|
||||||
|
.service(post_test)
|
||||||
|
.service(put_test)
|
||||||
|
.service(head_test)
|
||||||
|
.service(connect_test)
|
||||||
|
.service(options_test)
|
||||||
|
.service(trace_test)
|
||||||
|
.service(patch_test)
|
||||||
|
.service(test),
|
||||||
|
)
|
||||||
|
});
|
||||||
let request = srv.request(http::Method::GET, srv.url("/test"));
|
let request = srv.request(http::Method::GET, srv.url("/test"));
|
||||||
let response = srv.block_on(request.send()).unwrap();
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::HEAD, srv.url("/test"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::CONNECT, srv.url("/test"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::OPTIONS, srv.url("/test"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::TRACE, srv.url("/test"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::PATCH, srv.url("/test"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::PUT, srv.url("/test"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
assert_eq!(response.status(), http::StatusCode::CREATED);
|
||||||
|
|
||||||
|
let request = srv.request(http::Method::POST, srv.url("/test"));
|
||||||
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
|
||||||
|
|
||||||
let mut srv = TestServer::new(|| HttpService::new(App::new().service(auto_sync)));
|
let mut srv = TestServer::new(|| HttpService::new(App::new().service(auto_sync)));
|
||||||
let request = srv.request(http::Method::GET, srv.url("/test"));
|
let request = srv.request(http::Method::GET, srv.url("/test"));
|
||||||
let response = srv.block_on(request.send()).unwrap();
|
let response = srv.block_on(request.send()).unwrap();
|
||||||
|
@ -1,5 +1,47 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.2] - 2019-07-01
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Always append a colon after username in basic auth
|
||||||
|
|
||||||
|
* Upgrade `rand` dependency version to 0.7
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.1] - 2019-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add license files
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to send headers in `Camel-Case` form.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Upgrade actix-http dependency.
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-04-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to specify server address for http and ws requests.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* `ClientRequest::if_true()` and `ClientRequest::if_some()` use instance instead of ref
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-04-16
|
||||||
|
|
||||||
|
* No changes
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0-alpha.6] - 2019-04-14
|
## [0.1.0-alpha.6] - 2019-04-14
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user