mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-06 19:00:18 +02:00
Compare commits
37 Commits
http-v1.0.
...
web-v2.0.0
Author | SHA1 | Date | |
---|---|---|---|
6db909a3e7 | |||
642ae161c0 | |||
7b3c99b933 | |||
f86ce0390e | |||
7882f545e5 | |||
1c75e6876b | |||
6a0cd2dced | |||
c7f3915779 | |||
f45db1f909 | |||
3751a4018e | |||
0cb1b0642f | |||
48476362a3 | |||
2b4256baab | |||
e5a50f423d | |||
8b8a9a995d | |||
74fa4060c2 | |||
c877840c07 | |||
20248daeda | |||
a08d8dab70 | |||
fbbb4a86e9 | |||
1d12ba9d5f | |||
8c54054844 | |||
1732ae8c79 | |||
3b860ebdc7 | |||
29ac6463e1 | |||
01613f334b | |||
30dcaf9da0 | |||
b0aa9395da | |||
a153374b61 | |||
a791aab418 | |||
cb705317b8 | |||
e8e0f98f96 | |||
c878f66d05 | |||
fac6dec3c9 | |||
232f71b3b5 | |||
8881c13e60 | |||
d006a7b31f |
67
.github/workflows/main.yml
vendored
Normal file
67
.github/workflows/main.yml
vendored
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKGRS_DYNAMIC: 1
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_test:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
toolchain:
|
||||||
|
- x86_64-pc-windows-msvc
|
||||||
|
# - i686-pc-windows-msvc
|
||||||
|
- x86_64-apple-darwin
|
||||||
|
version:
|
||||||
|
- stable
|
||||||
|
- nightly
|
||||||
|
include:
|
||||||
|
- toolchain: x86_64-pc-windows-msvc
|
||||||
|
os: windows-latest
|
||||||
|
arch: x64
|
||||||
|
# - toolchain: i686-pc-windows-msvc
|
||||||
|
# os: windows-latest
|
||||||
|
# arch: x86
|
||||||
|
- toolchain: x86_64-apple-darwin
|
||||||
|
os: macOS-latest
|
||||||
|
|
||||||
|
name: ${{ matrix.version }} - ${{ matrix.toolchain }}
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@master
|
||||||
|
|
||||||
|
- name: Install ${{ matrix.version }}
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: ${{ matrix.version }}-${{ matrix.toolchain }}
|
||||||
|
default: true
|
||||||
|
|
||||||
|
- name: Install OpenSSL
|
||||||
|
if: matrix.os == 'windows-latest'
|
||||||
|
run: |
|
||||||
|
vcpkg integrate install
|
||||||
|
vcpkg install openssl:${{ matrix.arch }}-windows
|
||||||
|
|
||||||
|
- name: check nightly
|
||||||
|
if: matrix.version == 'nightly'
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
args: --all --benches --bins --examples --tests
|
||||||
|
|
||||||
|
- name: check stable
|
||||||
|
if: matrix.version == 'stable'
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: check
|
||||||
|
args: --all --bins --examples --tests
|
||||||
|
|
||||||
|
- name: tests
|
||||||
|
if: matrix.toolchain != 'x86_64-pc-windows-gnu'
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: test
|
||||||
|
args: --all --all-features -- --nocapture
|
41
CHANGES.md
41
CHANGES.md
@ -1,5 +1,46 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [2.0.0] - 2019-12-25
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Rename `HttpServer::start()` to `HttpServer::run()`
|
||||||
|
|
||||||
|
* Allow to gracefully stop test server via `TestServer::stop()`
|
||||||
|
|
||||||
|
* Allow to specify multi-patterns for resources
|
||||||
|
|
||||||
|
## [2.0.0-rc] - 2019-12-20
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Move `BodyEncoding` to `dev` module #1220
|
||||||
|
|
||||||
|
* Allow to set `peer_addr` for TestRequest #1074
|
||||||
|
|
||||||
|
* Make web::Data deref to Arc<T> #1214
|
||||||
|
|
||||||
|
* Rename `App::register_data()` to `App::app_data()`
|
||||||
|
|
||||||
|
* `HttpRequest::app_data<T>()` returns `Option<&T>` instead of `Option<&Data<T>>`
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix `AppConfig::secure()` is always false. #1202
|
||||||
|
|
||||||
|
|
||||||
|
## [2.0.0-alpha.6] - 2019-12-15
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fixed compilation with default features off
|
||||||
|
|
||||||
|
## [2.0.0-alpha.5] - 2019-12-13
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add test server, `test::start()` and `test::start_with()`
|
||||||
|
|
||||||
## [2.0.0-alpha.4] - 2019-12-08
|
## [2.0.0-alpha.4] - 2019-12-08
|
||||||
|
|
||||||
### Deleted
|
### Deleted
|
||||||
|
27
Cargo.toml
27
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web"
|
name = "actix-web"
|
||||||
version = "2.0.0-alpha.4"
|
version = "2.0.0"
|
||||||
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"
|
||||||
@ -12,11 +12,10 @@ categories = ["network-programming", "asynchronous",
|
|||||||
"web-programming::http-server",
|
"web-programming::http-server",
|
||||||
"web-programming::websocket"]
|
"web-programming::websocket"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["openssl", "compress", "secure-cookies", "client"]
|
features = ["openssl", "rustls", "compress", "secure-cookies"]
|
||||||
|
|
||||||
[badges]
|
[badges]
|
||||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||||
@ -61,21 +60,21 @@ rustls = ["actix-tls/rustls", "awc/rustls", "rust-tls"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-utils = "1.0.3"
|
actix-utils = "1.0.4"
|
||||||
actix-router = "0.2.0"
|
actix-router = "0.2.1"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-server = "1.0.0"
|
actix-server = "1.0.0"
|
||||||
actix-testing = "1.0.0"
|
actix-testing = "1.0.0"
|
||||||
actix-macros = "0.1.0"
|
actix-macros = "0.1.0"
|
||||||
actix-threadpool = "0.3.0"
|
actix-threadpool = "0.3.1"
|
||||||
actix-tls = "1.0.0"
|
actix-tls = "1.0.0"
|
||||||
|
|
||||||
actix-web-codegen = "0.2.0-alpha.2"
|
actix-web-codegen = "0.2.0"
|
||||||
actix-http = "1.0.0"
|
actix-http = "1.0.1"
|
||||||
awc = { version = "1.0.0", default-features = false }
|
awc = { version = "1.0.1", default-features = false }
|
||||||
|
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
encoding_rs = "0.8"
|
encoding_rs = "0.8"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
@ -94,11 +93,11 @@ open-ssl = { version="0.10", package = "openssl", optional = true }
|
|||||||
rust-tls = { version = "0.16.0", package = "rustls", optional = true }
|
rust-tls = { version = "0.16.0", package = "rustls", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
# actix = "0.8.3"
|
actix = "0.9.0"
|
||||||
rand = "0.7"
|
rand = "0.7"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
brotli = "3.3.0"
|
brotli2 = "0.3.2"
|
||||||
flate2 = "1.0.13"
|
flate2 = "1.0.13"
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
@ -116,4 +115,4 @@ actix-identity = { path = "actix-identity" }
|
|||||||
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" }
|
actix-multipart = { path = "actix-multipart" }
|
||||||
awc = { path = "awc" }
|
awc = { path = "awc" }
|
15
MIGRATION.md
15
MIGRATION.md
@ -1,10 +1,21 @@
|
|||||||
## 2.0.0
|
## 2.0.0
|
||||||
|
|
||||||
* Sync handlers has been removed. `.to_async()` method has been renamed to `.to()`
|
* `HttpServer::start()` renamed to `HttpServer::run()`. It also possible to
|
||||||
|
`.await` on `run` method result, in that case it awaits server exit.
|
||||||
|
|
||||||
|
* `App::register_data()` renamed to `App::app_data()` and accepts any type `T: 'static`.
|
||||||
|
Stored data is available via `HttpRequest::app_data()` method at runtime.
|
||||||
|
|
||||||
|
* Extractor configuration must be registered with `App::app_data()` instead of `App::data()`
|
||||||
|
|
||||||
|
* Sync handlers has been removed. `.to_async()` method has been renamed to `.to()`
|
||||||
replace `fn` with `async fn` to convert sync handler to async
|
replace `fn` with `async fn` to convert sync handler to async
|
||||||
|
|
||||||
* `TestServer::new()` renamed to `TestServer::start()`
|
* `actix_http_test::TestServer` moved to `actix_web::test` module. To start
|
||||||
|
test server use `test::start()` or `test_start_with_config()` methods
|
||||||
|
|
||||||
|
* `ResponseError` trait has been reafctored. `ResponseError::error_response()` renders
|
||||||
|
http response.
|
||||||
|
|
||||||
|
|
||||||
## 1.0.1
|
## 1.0.1
|
||||||
|
@ -53,7 +53,7 @@ async fn index(info: web::Path<(u32, String)>) -> impl Responder {
|
|||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
HttpServer::new(|| App::new().service(index))
|
HttpServer::new(|| App::new().service(index))
|
||||||
.bind("127.0.0.1:8080")?
|
.bind("127.0.0.1:8080")?
|
||||||
.start()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-12-20
|
||||||
|
|
||||||
|
* Release
|
||||||
|
|
||||||
## [0.2.0-alpha.3] - 2019-12-07
|
## [0.2.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
* Migrate to actix-web 2.0.0
|
* Migrate to actix-web 2.0.0
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-cors"
|
name = "actix-cors"
|
||||||
version = "0.2.0-alpha.3"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Cross-origin resource sharing (CORS) for Actix applications."
|
description = "Cross-origin resource sharing (CORS) for Actix applications."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -17,8 +17,8 @@ name = "actix_cors"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "2.0.0-alpha.3"
|
actix-web = "2.0.0-rc"
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
|
|
||||||
|
@ -814,7 +814,7 @@ where
|
|||||||
res
|
res
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.boxed_local(),
|
.boxed_local(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,14 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## [0.2.0-alpha.7] - 2019-12-07
|
## [0.2.1] - 2019-12-22
|
||||||
|
|
||||||
|
* Use the same format for file URLs regardless of platforms
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-12-20
|
||||||
|
|
||||||
|
* Fix BodyEncoding trait import #1220
|
||||||
|
|
||||||
|
## [0.2.0-alpha.1] - 2019-12-07
|
||||||
|
|
||||||
* Migrate to `std::future`
|
* Migrate to `std::future`
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-files"
|
name = "actix-files"
|
||||||
version = "0.2.0-alpha.3"
|
version = "0.2.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Static files support for actix web."
|
description = "Static files support for actix web."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -18,11 +18,11 @@ name = "actix_files"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "2.0.0-alpha.3", default-features = false }
|
actix-web = { version = "2.0.0-rc", default-features = false }
|
||||||
actix-http = "1.0.0-alpha.3"
|
actix-http = "1.0.1"
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
bitflags = "1"
|
bitflags = "1"
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
@ -33,4 +33,4 @@ v_htmlescape = "0.4"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-web = { version = "2.0.0-alpha.3", features=["openssl"] }
|
actix-web = { version = "2.0.0-rc", features=["openssl"] }
|
||||||
|
@ -155,7 +155,7 @@ impl Directory {
|
|||||||
// show file url as relative to static path
|
// show file url as relative to static path
|
||||||
macro_rules! encode_file_url {
|
macro_rules! encode_file_url {
|
||||||
($path:ident) => {
|
($path:ident) => {
|
||||||
utf8_percent_encode(&$path.to_string_lossy(), CONTROLS)
|
utf8_percent_encode(&$path, CONTROLS)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -178,7 +178,10 @@ fn directory_listing(
|
|||||||
if dir.is_visible(&entry) {
|
if dir.is_visible(&entry) {
|
||||||
let entry = entry.unwrap();
|
let entry = entry.unwrap();
|
||||||
let p = match entry.path().strip_prefix(&dir.path) {
|
let p = match entry.path().strip_prefix(&dir.path) {
|
||||||
Ok(p) => base.join(p),
|
Ok(p) if cfg!(windows) => {
|
||||||
|
base.join(p).to_string_lossy().replace("\\", "/")
|
||||||
|
}
|
||||||
|
Ok(p) => base.join(p).to_string_lossy().into_owned(),
|
||||||
Err(_) => continue,
|
Err(_) => continue,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -12,11 +12,11 @@ use mime;
|
|||||||
use mime_guess::from_path;
|
use mime_guess::from_path;
|
||||||
|
|
||||||
use actix_http::body::SizedStream;
|
use actix_http::body::SizedStream;
|
||||||
|
use actix_web::dev::BodyEncoding;
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
|
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
|
||||||
};
|
};
|
||||||
use actix_web::http::{ContentEncoding, StatusCode};
|
use actix_web::http::{ContentEncoding, StatusCode};
|
||||||
use actix_web::middleware::BodyEncoding;
|
|
||||||
use actix_web::{Error, HttpMessage, HttpRequest, HttpResponse, Responder};
|
use actix_web::{Error, HttpMessage, HttpRequest, HttpResponse, Responder};
|
||||||
use futures::future::{ready, Ready};
|
use futures::future::{ready, Ready};
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-framed"
|
name = "actix-framed"
|
||||||
version = "0.3.0-alpha.1"
|
version = "0.3.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"
|
||||||
@ -13,7 +13,6 @@ categories = ["network-programming", "asynchronous",
|
|||||||
"web-programming::websocket"]
|
"web-programming::websocket"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
workspace =".."
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_framed"
|
name = "actix_framed"
|
||||||
@ -21,12 +20,12 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-router = "0.2.0"
|
actix-router = "0.2.1"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-http = "1.0.0-alpha.3"
|
actix-http = "1.0.1"
|
||||||
|
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
pin-project = "0.4.6"
|
pin-project = "0.4.6"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
@ -34,5 +33,5 @@ log = "0.4"
|
|||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-server = "1.0.0"
|
actix-server = "1.0.0"
|
||||||
actix-connect = { version = "1.0.0", features=["openssl"] }
|
actix-connect = { version = "1.0.0", features=["openssl"] }
|
||||||
actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
|
actix-http-test = { version = "1.0.0", features=["openssl"] }
|
||||||
actix-utils = "1.0.0"
|
actix-utils = "1.0.3"
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.3.0] - 2019-12-25
|
||||||
|
|
||||||
|
* Migrate to actix-http 1.0
|
||||||
|
|
||||||
## [0.2.1] - 2019-07-20
|
## [0.2.1] - 2019-07-20
|
||||||
|
|
||||||
* Remove unneeded actix-utils dependency
|
* Remove unneeded actix-utils dependency
|
||||||
|
@ -66,7 +66,7 @@ where
|
|||||||
service
|
service
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -154,6 +154,6 @@ where
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,13 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-20
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Poll upgrade service's readiness from HTTP service handlers
|
||||||
|
|
||||||
|
* Replace brotli with brotli2 #1224
|
||||||
|
|
||||||
## [1.0.0] - 2019-12-13
|
## [1.0.0] - 2019-12-13
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http"
|
name = "actix-http"
|
||||||
version = "1.0.0"
|
version = "1.0.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix http primitives"
|
description = "Actix http primitives"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -15,7 +15,7 @@ license = "MIT/Apache-2.0"
|
|||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["openssl", "rustls", "fail", "compress", "secure-cookies"]
|
features = ["openssl", "rustls", "failure", "compress", "secure-cookies"]
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_http"
|
name = "actix_http"
|
||||||
@ -31,7 +31,7 @@ openssl = ["actix-tls/openssl", "actix-connect/openssl"]
|
|||||||
rustls = ["actix-tls/rustls", "actix-connect/rustls"]
|
rustls = ["actix-tls/rustls", "actix-connect/rustls"]
|
||||||
|
|
||||||
# enable compressison support
|
# enable compressison support
|
||||||
compress = ["flate2", "brotli"]
|
compress = ["flate2", "brotli2"]
|
||||||
|
|
||||||
# failure integration. actix does not use failure anymore
|
# failure integration. actix does not use failure anymore
|
||||||
failure = ["fail-ure"]
|
failure = ["fail-ure"]
|
||||||
@ -40,9 +40,9 @@ failure = ["fail-ure"]
|
|||||||
secure-cookies = ["ring"]
|
secure-cookies = ["ring"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-connect = "1.0.0"
|
actix-connect = "1.0.1"
|
||||||
actix-utils = "1.0.3"
|
actix-utils = "1.0.3"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-threadpool = "0.3.1"
|
actix-threadpool = "0.3.1"
|
||||||
@ -83,7 +83,7 @@ time = "0.1.42"
|
|||||||
ring = { version = "0.16.9", optional = true }
|
ring = { version = "0.16.9", optional = true }
|
||||||
|
|
||||||
# compression
|
# compression
|
||||||
brotli = { version = "3.3.0", optional = true }
|
brotli2 = { version="0.3.2", optional = true }
|
||||||
flate2 = { version = "1.0.13", optional = true }
|
flate2 = { version = "1.0.13", optional = true }
|
||||||
|
|
||||||
# optional deps
|
# optional deps
|
||||||
@ -92,7 +92,7 @@ fail-ure = { version = "0.1.5", package="failure", optional = true }
|
|||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-server = "1.0.0"
|
actix-server = "1.0.0"
|
||||||
actix-connect = { version = "1.0.0", features=["openssl"] }
|
actix-connect = { version = "1.0.0", features=["openssl"] }
|
||||||
actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
|
actix-http-test = { version = "1.0.0", features=["openssl"] }
|
||||||
actix-tls = { version = "1.0.0", features=["openssl"] }
|
actix-tls = { version = "1.0.0", features=["openssl"] }
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
|
@ -51,11 +51,7 @@ impl From<Utf8Error> for ParseError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for ParseError {
|
impl Error for ParseError {}
|
||||||
fn description(&self) -> &str {
|
|
||||||
self.as_str()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn indexes_of(needle: &str, haystack: &str) -> Option<(usize, usize)> {
|
fn indexes_of(needle: &str, haystack: &str) -> Option<(usize, usize)> {
|
||||||
let haystack_start = haystack.as_ptr() as usize;
|
let haystack_start = haystack.as_ptr() as usize;
|
||||||
|
@ -4,7 +4,7 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_threadpool::{run, CpuFuture};
|
use actix_threadpool::{run, CpuFuture};
|
||||||
use brotli::DecompressorWriter;
|
use brotli2::write::BrotliDecoder;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use flate2::write::{GzDecoder, ZlibDecoder};
|
use flate2::write::{GzDecoder, ZlibDecoder};
|
||||||
use futures_core::{ready, Stream};
|
use futures_core::{ready, Stream};
|
||||||
@ -31,7 +31,7 @@ where
|
|||||||
pub fn new(stream: S, encoding: ContentEncoding) -> Decoder<S> {
|
pub fn new(stream: S, encoding: ContentEncoding) -> Decoder<S> {
|
||||||
let decoder = match encoding {
|
let decoder = match encoding {
|
||||||
ContentEncoding::Br => Some(ContentDecoder::Br(Box::new(
|
ContentEncoding::Br => Some(ContentDecoder::Br(Box::new(
|
||||||
DecompressorWriter::new(Writer::new(), 0),
|
BrotliDecoder::new(Writer::new()),
|
||||||
))),
|
))),
|
||||||
ContentEncoding::Deflate => Some(ContentDecoder::Deflate(Box::new(
|
ContentEncoding::Deflate => Some(ContentDecoder::Deflate(Box::new(
|
||||||
ZlibDecoder::new(Writer::new()),
|
ZlibDecoder::new(Writer::new()),
|
||||||
@ -137,7 +137,7 @@ where
|
|||||||
enum ContentDecoder {
|
enum ContentDecoder {
|
||||||
Deflate(Box<ZlibDecoder<Writer>>),
|
Deflate(Box<ZlibDecoder<Writer>>),
|
||||||
Gzip(Box<GzDecoder<Writer>>),
|
Gzip(Box<GzDecoder<Writer>>),
|
||||||
Br(Box<DecompressorWriter<Writer>>),
|
Br(Box<BrotliDecoder<Writer>>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ContentDecoder {
|
impl ContentDecoder {
|
||||||
|
@ -5,7 +5,7 @@ use std::pin::Pin;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_threadpool::{run, CpuFuture};
|
use actix_threadpool::{run, CpuFuture};
|
||||||
use brotli::CompressorWriter;
|
use brotli2::write::BrotliEncoder;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use flate2::write::{GzEncoder, ZlibEncoder};
|
use flate2::write::{GzEncoder, ZlibEncoder};
|
||||||
use futures_core::ready;
|
use futures_core::ready;
|
||||||
@ -17,7 +17,7 @@ use crate::{Error, ResponseHead};
|
|||||||
|
|
||||||
use super::Writer;
|
use super::Writer;
|
||||||
|
|
||||||
const INPLACE: usize = 2049;
|
const INPLACE: usize = 1024;
|
||||||
|
|
||||||
pub struct Encoder<B> {
|
pub struct Encoder<B> {
|
||||||
eof: bool,
|
eof: bool,
|
||||||
@ -174,7 +174,7 @@ fn update_head(encoding: ContentEncoding, head: &mut ResponseHead) {
|
|||||||
enum ContentEncoder {
|
enum ContentEncoder {
|
||||||
Deflate(ZlibEncoder<Writer>),
|
Deflate(ZlibEncoder<Writer>),
|
||||||
Gzip(GzEncoder<Writer>),
|
Gzip(GzEncoder<Writer>),
|
||||||
Br(Box<CompressorWriter<Writer>>),
|
Br(BrotliEncoder<Writer>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ContentEncoder {
|
impl ContentEncoder {
|
||||||
@ -188,9 +188,9 @@ impl ContentEncoder {
|
|||||||
Writer::new(),
|
Writer::new(),
|
||||||
flate2::Compression::fast(),
|
flate2::Compression::fast(),
|
||||||
))),
|
))),
|
||||||
ContentEncoding::Br => Some(ContentEncoder::Br(Box::new(
|
ContentEncoding::Br => {
|
||||||
CompressorWriter::new(Writer::new(), 0, 3, 0),
|
Some(ContentEncoder::Br(BrotliEncoder::new(Writer::new(), 3)))
|
||||||
))),
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -198,12 +198,7 @@ impl ContentEncoder {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub(crate) fn take(&mut self) -> Bytes {
|
pub(crate) fn take(&mut self) -> Bytes {
|
||||||
match *self {
|
match *self {
|
||||||
ContentEncoder::Br(ref mut encoder) => {
|
ContentEncoder::Br(ref mut encoder) => encoder.get_mut().take(),
|
||||||
let mut encoder_new =
|
|
||||||
Box::new(CompressorWriter::new(Writer::new(), 0, 3, 0));
|
|
||||||
std::mem::swap(encoder, &mut encoder_new);
|
|
||||||
encoder_new.into_inner().freeze()
|
|
||||||
}
|
|
||||||
ContentEncoder::Deflate(ref mut encoder) => encoder.get_mut().take(),
|
ContentEncoder::Deflate(ref mut encoder) => encoder.get_mut().take(),
|
||||||
ContentEncoder::Gzip(ref mut encoder) => encoder.get_mut().take(),
|
ContentEncoder::Gzip(ref mut encoder) => encoder.get_mut().take(),
|
||||||
}
|
}
|
||||||
@ -211,7 +206,10 @@ impl ContentEncoder {
|
|||||||
|
|
||||||
fn finish(self) -> Result<Bytes, io::Error> {
|
fn finish(self) -> Result<Bytes, io::Error> {
|
||||||
match self {
|
match self {
|
||||||
ContentEncoder::Br(encoder) => Ok(encoder.into_inner().buf.freeze()),
|
ContentEncoder::Br(encoder) => match encoder.finish() {
|
||||||
|
Ok(writer) => Ok(writer.buf.freeze()),
|
||||||
|
Err(err) => Err(err),
|
||||||
|
},
|
||||||
ContentEncoder::Gzip(encoder) => match encoder.finish() {
|
ContentEncoder::Gzip(encoder) => match encoder.finish() {
|
||||||
Ok(writer) => Ok(writer.buf.freeze()),
|
Ok(writer) => Ok(writer.buf.freeze()),
|
||||||
Err(err) => Err(err),
|
Err(err) => Err(err),
|
||||||
|
@ -19,12 +19,10 @@ impl Writer {
|
|||||||
buf: BytesMut::with_capacity(8192),
|
buf: BytesMut::with_capacity(8192),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn take(&mut self) -> Bytes {
|
fn take(&mut self) -> Bytes {
|
||||||
self.buf.split().freeze()
|
self.buf.split().freeze()
|
||||||
}
|
}
|
||||||
fn freeze(self) -> Bytes {
|
|
||||||
self.buf.freeze()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl io::Write for Writer {
|
impl io::Write for Writer {
|
||||||
@ -32,6 +30,7 @@ impl io::Write for Writer {
|
|||||||
self.buf.extend_from_slice(buf);
|
self.buf.extend_from_slice(buf);
|
||||||
Ok(buf.len())
|
Ok(buf.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flush(&mut self) -> io::Result<()> {
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,9 @@ use std::str::Utf8Error;
|
|||||||
use std::string::FromUtf8Error;
|
use std::string::FromUtf8Error;
|
||||||
use std::{fmt, io, result};
|
use std::{fmt, io, result};
|
||||||
|
|
||||||
|
use actix_codec::{Decoder, Encoder};
|
||||||
pub use actix_threadpool::BlockingError;
|
pub use actix_threadpool::BlockingError;
|
||||||
|
use actix_utils::framed::DispatcherError as FramedDispatcherError;
|
||||||
use actix_utils::timeout::TimeoutError;
|
use actix_utils::timeout::TimeoutError;
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use derive_more::{Display, From};
|
use derive_more::{Display, From};
|
||||||
@ -114,10 +116,6 @@ impl fmt::Debug for Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for Error {
|
impl std::error::Error for Error {
|
||||||
fn description(&self) -> &str {
|
|
||||||
"actix-http::Error"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cause(&self) -> Option<&dyn std::error::Error> {
|
fn cause(&self) -> Option<&dyn std::error::Error> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@ -467,6 +465,14 @@ impl ResponseError for ContentTypeError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<E, U: Encoder + Decoder> ResponseError for FramedDispatcherError<E, U>
|
||||||
|
where
|
||||||
|
E: fmt::Debug + fmt::Display,
|
||||||
|
<U as Encoder>::Error: fmt::Debug,
|
||||||
|
<U as Decoder>::Error: fmt::Debug,
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
/// Helper type that can wrap any error and generate custom response.
|
/// Helper type that can wrap any error and generate custom response.
|
||||||
///
|
///
|
||||||
/// In following example any `io::Error` will be converted into "BAD REQUEST"
|
/// In following example any `io::Error` will be converted into "BAD REQUEST"
|
||||||
@ -966,7 +972,6 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use http::{Error as HttpError, StatusCode};
|
use http::{Error as HttpError, StatusCode};
|
||||||
use httparse;
|
use httparse;
|
||||||
use std::error::Error as StdError;
|
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -995,7 +1000,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_error_cause() {
|
fn test_error_cause() {
|
||||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||||
let desc = orig.description().to_owned();
|
let desc = orig.to_string();
|
||||||
let e = Error::from(orig);
|
let e = Error::from(orig);
|
||||||
assert_eq!(format!("{}", e.as_response_error()), desc);
|
assert_eq!(format!("{}", e.as_response_error()), desc);
|
||||||
}
|
}
|
||||||
@ -1003,7 +1008,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_error_display() {
|
fn test_error_display() {
|
||||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||||
let desc = orig.description().to_owned();
|
let desc = orig.to_string();
|
||||||
let e = Error::from(orig);
|
let e = Error::from(orig);
|
||||||
assert_eq!(format!("{}", e), desc);
|
assert_eq!(format!("{}", e), desc);
|
||||||
}
|
}
|
||||||
@ -1045,7 +1050,7 @@ mod tests {
|
|||||||
match ParseError::from($from) {
|
match ParseError::from($from) {
|
||||||
e @ $error => {
|
e @ $error => {
|
||||||
let desc = format!("{}", e);
|
let desc = format!("{}", e);
|
||||||
assert_eq!(desc, format!("IO error: {}", $from.description()));
|
assert_eq!(desc, format!("IO error: {}", $from));
|
||||||
}
|
}
|
||||||
_ => unreachable!("{:?}", $from),
|
_ => unreachable!("{:?}", $from),
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ use std::mem::MaybeUninit;
|
|||||||
use std::task::Poll;
|
use std::task::Poll;
|
||||||
|
|
||||||
use actix_codec::Decoder;
|
use actix_codec::Decoder;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Buf, Bytes, BytesMut};
|
||||||
use http::header::{HeaderName, HeaderValue};
|
use http::header::{HeaderName, HeaderValue};
|
||||||
use http::{header, Method, StatusCode, Uri, Version};
|
use http::{header, Method, StatusCode, Uri, Version};
|
||||||
use httparse;
|
use httparse;
|
||||||
@ -477,7 +477,7 @@ macro_rules! byte (
|
|||||||
($rdr:ident) => ({
|
($rdr:ident) => ({
|
||||||
if $rdr.len() > 0 {
|
if $rdr.len() > 0 {
|
||||||
let b = $rdr[0];
|
let b = $rdr[0];
|
||||||
let _ = $rdr.split_to(1);
|
$rdr.advance(1);
|
||||||
b
|
b
|
||||||
} else {
|
} else {
|
||||||
return Poll::Pending
|
return Poll::Pending
|
||||||
|
@ -8,7 +8,7 @@ use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed, FramedParts};
|
|||||||
use actix_rt::time::{delay_until, Delay, Instant};
|
use actix_rt::time::{delay_until, Delay, Instant};
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
use bytes::BytesMut;
|
use bytes::{Buf, BytesMut};
|
||||||
use log::{error, trace};
|
use log::{error, trace};
|
||||||
|
|
||||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||||
@ -66,7 +66,6 @@ where
|
|||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
Normal(InnerDispatcher<T, S, B, X, U>),
|
Normal(InnerDispatcher<T, S, B, X, U>),
|
||||||
UpgradeReadiness(InnerDispatcher<T, S, B, X, U>, Request),
|
|
||||||
Upgrade(U::Future),
|
Upgrade(U::Future),
|
||||||
None,
|
None,
|
||||||
}
|
}
|
||||||
@ -313,7 +312,7 @@ where
|
|||||||
}
|
}
|
||||||
Poll::Pending => {
|
Poll::Pending => {
|
||||||
if written > 0 {
|
if written > 0 {
|
||||||
let _ = self.write_buf.split_to(written);
|
self.write_buf.advance(written);
|
||||||
}
|
}
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
}
|
}
|
||||||
@ -323,7 +322,7 @@ where
|
|||||||
if written == self.write_buf.len() {
|
if written == self.write_buf.len() {
|
||||||
unsafe { self.write_buf.set_len(0) }
|
unsafe { self.write_buf.set_len(0) }
|
||||||
} else {
|
} else {
|
||||||
let _ = self.write_buf.split_to(written);
|
self.write_buf.advance(written);
|
||||||
}
|
}
|
||||||
Ok(false)
|
Ok(false)
|
||||||
}
|
}
|
||||||
@ -764,8 +763,16 @@ where
|
|||||||
if let DispatcherState::Normal(inner) =
|
if let DispatcherState::Normal(inner) =
|
||||||
std::mem::replace(&mut self.inner, DispatcherState::None)
|
std::mem::replace(&mut self.inner, DispatcherState::None)
|
||||||
{
|
{
|
||||||
self.inner =
|
let mut parts = FramedParts::with_read_buf(
|
||||||
DispatcherState::UpgradeReadiness(inner, req);
|
inner.io,
|
||||||
|
inner.codec,
|
||||||
|
inner.read_buf,
|
||||||
|
);
|
||||||
|
parts.write_buf = inner.write_buf;
|
||||||
|
let framed = Framed::from_parts(parts);
|
||||||
|
self.inner = DispatcherState::Upgrade(
|
||||||
|
inner.upgrade.unwrap().call((req, framed)),
|
||||||
|
);
|
||||||
return self.poll(cx);
|
return self.poll(cx);
|
||||||
} else {
|
} else {
|
||||||
panic!()
|
panic!()
|
||||||
@ -815,35 +822,6 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DispatcherState::UpgradeReadiness(ref mut inner, _) => {
|
|
||||||
let upgrade = inner.upgrade.as_mut().unwrap();
|
|
||||||
match upgrade.poll_ready(cx) {
|
|
||||||
Poll::Ready(Ok(_)) => {
|
|
||||||
if let DispatcherState::UpgradeReadiness(inner, req) =
|
|
||||||
std::mem::replace(&mut self.inner, DispatcherState::None)
|
|
||||||
{
|
|
||||||
let mut parts = FramedParts::with_read_buf(
|
|
||||||
inner.io,
|
|
||||||
inner.codec,
|
|
||||||
inner.read_buf,
|
|
||||||
);
|
|
||||||
parts.write_buf = inner.write_buf;
|
|
||||||
let framed = Framed::from_parts(parts);
|
|
||||||
self.inner = DispatcherState::Upgrade(
|
|
||||||
inner.upgrade.unwrap().call((req, framed)),
|
|
||||||
);
|
|
||||||
self.poll(cx)
|
|
||||||
} else {
|
|
||||||
panic!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Poll::Pending => Poll::Pending,
|
|
||||||
Poll::Ready(Err(e)) => {
|
|
||||||
error!("Upgrade handler readiness check error: {}", e);
|
|
||||||
Poll::Ready(Err(DispatchError::Upgrade))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DispatcherState::Upgrade(ref mut fut) => {
|
DispatcherState::Upgrade(ref mut fut) => {
|
||||||
unsafe { Pin::new_unchecked(fut) }.poll(cx).map_err(|e| {
|
unsafe { Pin::new_unchecked(fut) }.poll(cx).map_err(|e| {
|
||||||
error!("Upgrade handler error: {}", e);
|
error!("Upgrade handler error: {}", e);
|
||||||
|
@ -72,7 +72,7 @@ where
|
|||||||
Request = (Request, Framed<TcpStream, Codec>),
|
Request = (Request, Framed<TcpStream, Codec>),
|
||||||
Response = (),
|
Response = (),
|
||||||
>,
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
/// Create simple tcp stream service
|
/// Create simple tcp stream service
|
||||||
@ -115,7 +115,7 @@ mod openssl {
|
|||||||
Request = (Request, Framed<SslStream<TcpStream>, Codec>),
|
Request = (Request, Framed<SslStream<TcpStream>, Codec>),
|
||||||
Response = (),
|
Response = (),
|
||||||
>,
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
/// Create openssl based service
|
/// Create openssl based service
|
||||||
@ -165,7 +165,7 @@ mod rustls {
|
|||||||
Request = (Request, Framed<TlsStream<TcpStream>, Codec>),
|
Request = (Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||||
Response = (),
|
Response = (),
|
||||||
>,
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
/// Create rustls based service
|
/// Create rustls based service
|
||||||
@ -255,7 +255,7 @@ where
|
|||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
U: ServiceFactory<Config = (), Request = (Request, Framed<T, Codec>), Response = ()>,
|
U: ServiceFactory<Config = (), Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
{
|
{
|
||||||
type Config = ();
|
type Config = ();
|
||||||
@ -412,7 +412,7 @@ where
|
|||||||
X: Service<Request = Request, Response = Request>,
|
X: Service<Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
|
U: Service<Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
{
|
{
|
||||||
type Request = (T, Option<net::SocketAddr>);
|
type Request = (T, Option<net::SocketAddr>);
|
||||||
type Response = ();
|
type Response = ();
|
||||||
@ -441,6 +441,19 @@ where
|
|||||||
.is_ready()
|
.is_ready()
|
||||||
&& ready;
|
&& ready;
|
||||||
|
|
||||||
|
let ready = if let Some(ref mut upg) = self.upgrade {
|
||||||
|
upg.poll_ready(cx)
|
||||||
|
.map_err(|e| {
|
||||||
|
let e = e.into();
|
||||||
|
log::error!("Http service readiness error: {:?}", e);
|
||||||
|
DispatchError::Service(e)
|
||||||
|
})?
|
||||||
|
.is_ready()
|
||||||
|
&& ready
|
||||||
|
} else {
|
||||||
|
ready
|
||||||
|
};
|
||||||
|
|
||||||
if ready {
|
if ready {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
} else {
|
} else {
|
||||||
|
@ -169,7 +169,7 @@ where
|
|||||||
Request = (Request, Framed<TcpStream, h1::Codec>),
|
Request = (Request, Framed<TcpStream, h1::Codec>),
|
||||||
Response = (),
|
Response = (),
|
||||||
>,
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
<U::Service as Service>::Future: 'static,
|
<U::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
@ -214,7 +214,7 @@ mod openssl {
|
|||||||
Request = (Request, Framed<SslStream<TcpStream>, h1::Codec>),
|
Request = (Request, Framed<SslStream<TcpStream>, h1::Codec>),
|
||||||
Response = (),
|
Response = (),
|
||||||
>,
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
<U::Service as Service>::Future: 'static,
|
<U::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
@ -276,7 +276,7 @@ mod rustls {
|
|||||||
Request = (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
|
Request = (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
|
||||||
Response = (),
|
Response = (),
|
||||||
>,
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
<U::Service as Service>::Future: 'static,
|
<U::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
@ -335,7 +335,7 @@ where
|
|||||||
Request = (Request, Framed<T, h1::Codec>),
|
Request = (Request, Framed<T, h1::Codec>),
|
||||||
Response = (),
|
Response = (),
|
||||||
>,
|
>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
U::InitError: fmt::Debug,
|
U::InitError: fmt::Debug,
|
||||||
<U::Service as Service>::Future: 'static,
|
<U::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
@ -493,7 +493,7 @@ where
|
|||||||
X: Service<Request = Request, Response = Request>,
|
X: Service<Request = Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
U: Service<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
{
|
{
|
||||||
type Request = (T, Protocol, Option<net::SocketAddr>);
|
type Request = (T, Protocol, Option<net::SocketAddr>);
|
||||||
type Response = ();
|
type Response = ();
|
||||||
@ -522,6 +522,19 @@ where
|
|||||||
.is_ready()
|
.is_ready()
|
||||||
&& ready;
|
&& ready;
|
||||||
|
|
||||||
|
let ready = if let Some(ref mut upg) = self.upgrade {
|
||||||
|
upg.poll_ready(cx)
|
||||||
|
.map_err(|e| {
|
||||||
|
let e = e.into();
|
||||||
|
log::error!("Http service readiness error: {:?}", e);
|
||||||
|
DispatchError::Service(e)
|
||||||
|
})?
|
||||||
|
.is_ready()
|
||||||
|
&& ready
|
||||||
|
} else {
|
||||||
|
ready
|
||||||
|
};
|
||||||
|
|
||||||
if ready {
|
if ready {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
} else {
|
} else {
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{Buf, BufMut, BytesMut};
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use rand;
|
use rand;
|
||||||
|
|
||||||
@ -108,7 +108,7 @@ impl Parser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// remove prefix
|
// remove prefix
|
||||||
let _ = src.split_to(idx);
|
src.advance(idx);
|
||||||
|
|
||||||
// no need for body
|
// no need for body
|
||||||
if length == 0 {
|
if length == 0 {
|
||||||
|
@ -1,24 +1,70 @@
|
|||||||
|
use std::cell::Cell;
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_http::{body, h1, ws, Error, HttpService, Request, Response};
|
use actix_http::{body, h1, ws, Error, HttpService, Request, Response};
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
|
use actix_service::{fn_factory, Service};
|
||||||
use actix_utils::framed::Dispatcher;
|
use actix_utils::framed::Dispatcher;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future;
|
use futures::future;
|
||||||
use futures::{SinkExt, StreamExt};
|
use futures::task::{Context, Poll};
|
||||||
|
use futures::{Future, SinkExt, StreamExt};
|
||||||
|
|
||||||
async fn ws_service<T: AsyncRead + AsyncWrite + Unpin>(
|
struct WsService<T>(Arc<Mutex<(PhantomData<T>, Cell<bool>)>>);
|
||||||
(req, mut framed): (Request, Framed<T, h1::Codec>),
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
let res = ws::handshake(req.head()).unwrap().message_body(());
|
|
||||||
|
|
||||||
framed
|
impl<T> WsService<T> {
|
||||||
.send((res, body::BodySize::None).into())
|
fn new() -> Self {
|
||||||
.await
|
WsService(Arc::new(Mutex::new((PhantomData, Cell::new(false)))))
|
||||||
.unwrap();
|
}
|
||||||
|
|
||||||
Dispatcher::new(framed.into_framed(ws::Codec::new()), service)
|
fn set_polled(&mut self) {
|
||||||
.await
|
*self.0.lock().unwrap().1.get_mut() = true;
|
||||||
.map_err(|_| panic!())
|
}
|
||||||
|
|
||||||
|
fn was_polled(&self) -> bool {
|
||||||
|
self.0.lock().unwrap().1.get()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Clone for WsService<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
WsService(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Service for WsService<T>
|
||||||
|
where
|
||||||
|
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||||
|
{
|
||||||
|
type Request = (Request, Framed<T, h1::Codec>);
|
||||||
|
type Response = ();
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Pin<Box<dyn Future<Output = Result<(), Error>>>>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
self.set_polled();
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, (req, mut framed): Self::Request) -> Self::Future {
|
||||||
|
let fut = async move {
|
||||||
|
let res = ws::handshake(req.head()).unwrap().message_body(());
|
||||||
|
|
||||||
|
framed
|
||||||
|
.send((res, body::BodySize::None).into())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Dispatcher::new(framed.into_framed(ws::Codec::new()), service)
|
||||||
|
.await
|
||||||
|
.map_err(|_| panic!())
|
||||||
|
};
|
||||||
|
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
|
async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
|
||||||
@ -37,11 +83,16 @@ async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
|
|||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_simple() {
|
async fn test_simple() {
|
||||||
let mut srv = test_server(|| {
|
let ws_service = WsService::new();
|
||||||
HttpService::build()
|
let mut srv = test_server({
|
||||||
.upgrade(actix_service::fn_service(ws_service))
|
let ws_service = ws_service.clone();
|
||||||
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
|
move || {
|
||||||
.tcp()
|
let ws_service = ws_service.clone();
|
||||||
|
HttpService::build()
|
||||||
|
.upgrade(fn_factory(move || future::ok::<_, ()>(ws_service.clone())))
|
||||||
|
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
|
||||||
|
.tcp()
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
@ -138,4 +189,6 @@ async fn test_simple() {
|
|||||||
item.unwrap().unwrap(),
|
item.unwrap().unwrap(),
|
||||||
ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
|
ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
|
||||||
);
|
);
|
||||||
|
|
||||||
|
assert!(ws_service.was_polled());
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-12-20
|
||||||
|
|
||||||
|
* Use actix-web 2.0
|
||||||
|
|
||||||
## [0.1.0] - 2019-06-xx
|
## [0.1.0] - 2019-06-xx
|
||||||
|
|
||||||
* Move identity middleware to separate crate
|
* Move identity middleware to separate crate
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-identity"
|
name = "actix-identity"
|
||||||
version = "0.2.0-alpha.3"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Identity service for actix web framework."
|
description = "Identity service for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -17,8 +17,8 @@ name = "actix_identity"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "2.0.0-alpha.3", default-features = false, features = ["secure-cookies"] }
|
actix-web = { version = "2.0.0-rc", default-features = false, features = ["secure-cookies"] }
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
@ -26,5 +26,5 @@ time = "0.1.42"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-http = "1.0.0-alpha.3"
|
actix-http = "1.0.1"
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
@ -294,7 +294,7 @@ where
|
|||||||
Err(err) => Ok(req.error_response(err)),
|
Err(err) => Ok(req.error_response(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,6 +1,10 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## [2.0.0-alpha.4] - 2019-12-xx
|
## [0.2.0] - 2019-12-20
|
||||||
|
|
||||||
|
* Release
|
||||||
|
|
||||||
|
## [0.2.0-alpha.4] - 2019-12-xx
|
||||||
|
|
||||||
* Multipart handling now handles Pending during read of boundary #1205
|
* Multipart handling now handles Pending during read of boundary #1205
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-multipart"
|
name = "actix-multipart"
|
||||||
version = "0.2.0-alpha.3"
|
version = "0.2.0"
|
||||||
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"
|
||||||
@ -9,8 +9,6 @@ homepage = "https://actix.rs"
|
|||||||
repository = "https://github.com/actix/actix-web.git"
|
repository = "https://github.com/actix/actix-web.git"
|
||||||
documentation = "https://docs.rs/actix-multipart/"
|
documentation = "https://docs.rs/actix-multipart/"
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
workspace = ".."
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
@ -18,10 +16,10 @@ name = "actix_multipart"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "2.0.0-alpha.3", default-features = false }
|
actix-web = { version = "2.0.0-rc", default-features = false }
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-utils = "1.0.0"
|
actix-utils = "1.0.3"
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
@ -32,4 +30,4 @@ twoway = "0.2"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-http = "1.0.0-alpha.3"
|
actix-http = "1.0.0"
|
@ -1,5 +1,13 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.3.0] - 2019-12-20
|
||||||
|
|
||||||
|
* Release
|
||||||
|
|
||||||
|
## [0.3.0-alpha.4] - 2019-12-xx
|
||||||
|
|
||||||
|
* Allow access to sessions also from not mutable references to the request
|
||||||
|
|
||||||
## [0.3.0-alpha.3] - 2019-12-xx
|
## [0.3.0-alpha.3] - 2019-12-xx
|
||||||
|
|
||||||
* Add access to the session from RequestHead for use of session from guard methods
|
* Add access to the session from RequestHead for use of session from guard methods
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-session"
|
name = "actix-session"
|
||||||
version = "0.3.0-alpha.3"
|
version = "0.3.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"
|
||||||
@ -9,8 +9,6 @@ homepage = "https://actix.rs"
|
|||||||
repository = "https://github.com/actix/actix-web.git"
|
repository = "https://github.com/actix/actix-web.git"
|
||||||
documentation = "https://docs.rs/actix-session/"
|
documentation = "https://docs.rs/actix-session/"
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
workspace = ".."
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
@ -24,9 +22,9 @@ default = ["cookie-session"]
|
|||||||
cookie-session = ["actix-web/secure-cookies"]
|
cookie-session = ["actix-web/secure-cookies"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "2.0.0-alpha.3"
|
actix-web = "2.0.0-rc"
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
|
@ -354,7 +354,7 @@ where
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -37,7 +37,7 @@
|
|||||||
//! )
|
//! )
|
||||||
//! .service(web::resource("/").to(|| HttpResponse::Ok())))
|
//! .service(web::resource("/").to(|| HttpResponse::Ok())))
|
||||||
//! .bind("127.0.0.1:59880")?
|
//! .bind("127.0.0.1:59880")?
|
||||||
//! .start()
|
//! .run()
|
||||||
//! .await
|
//! .await
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
@ -85,23 +85,23 @@ pub struct Session(Rc<RefCell<SessionInner>>);
|
|||||||
|
|
||||||
/// Helper trait that allows to get session
|
/// Helper trait that allows to get session
|
||||||
pub trait UserSession {
|
pub trait UserSession {
|
||||||
fn get_session(&mut self) -> Session;
|
fn get_session(&self) -> Session;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UserSession for HttpRequest {
|
impl UserSession for HttpRequest {
|
||||||
fn get_session(&mut self) -> Session {
|
fn get_session(&self) -> Session {
|
||||||
Session::get_session(&mut *self.extensions_mut())
|
Session::get_session(&mut *self.extensions_mut())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UserSession for ServiceRequest {
|
impl UserSession for ServiceRequest {
|
||||||
fn get_session(&mut self) -> Session {
|
fn get_session(&self) -> Session {
|
||||||
Session::get_session(&mut *self.extensions_mut())
|
Session::get_session(&mut *self.extensions_mut())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UserSession for RequestHead {
|
impl UserSession for RequestHead {
|
||||||
fn get_session(&mut self) -> Session {
|
fn get_session(&self) -> Session {
|
||||||
Session::get_session(&mut *self.extensions_mut())
|
Session::get_session(&mut *self.extensions_mut())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,13 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [2.0.0] - 2019-12-20
|
||||||
|
|
||||||
|
* Release
|
||||||
|
|
||||||
|
## [2.0.0-alpha.1] - 2019-12-15
|
||||||
|
|
||||||
|
* Migrate to actix-web 2.0.0
|
||||||
|
|
||||||
## [1.0.4] - 2019-12-07
|
## [1.0.4] - 2019-12-07
|
||||||
|
|
||||||
* Allow comma-separated websocket subprotocols without spaces (#1172)
|
* Allow comma-separated websocket subprotocols without spaces (#1172)
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web-actors"
|
name = "actix-web-actors"
|
||||||
version = "1.0.4"
|
version = "2.0.0"
|
||||||
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"
|
||||||
@ -9,8 +9,6 @@ homepage = "https://actix.rs"
|
|||||||
repository = "https://github.com/actix/actix-web.git"
|
repository = "https://github.com/actix/actix-web.git"
|
||||||
documentation = "https://docs.rs/actix-web-actors/"
|
documentation = "https://docs.rs/actix-web-actors/"
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|
||||||
workspace = ".."
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
@ -18,13 +16,14 @@ name = "actix_web_actors"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.8.3"
|
actix = "0.9.0"
|
||||||
actix-web = "1.0.9"
|
actix-web = "2.0.0-rc"
|
||||||
actix-http = "0.2.11"
|
actix-http = "1.0.1"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.2.0"
|
||||||
bytes = "0.4"
|
bytes = "0.5.2"
|
||||||
futures = "0.1.25"
|
futures = "0.3.1"
|
||||||
|
pin-project = "0.4.6"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
actix-rt = "1.0.0"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix::dev::{
|
use actix::dev::{
|
||||||
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, ToEnvelope,
|
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, ToEnvelope,
|
||||||
@ -7,10 +9,10 @@ use actix::fut::ActorFuture;
|
|||||||
use actix::{
|
use actix::{
|
||||||
Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, SpawnHandle,
|
Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, SpawnHandle,
|
||||||
};
|
};
|
||||||
use actix_web::error::{Error, ErrorInternalServerError};
|
use actix_web::error::Error;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::sync::oneshot::Sender;
|
use futures::channel::oneshot::Sender;
|
||||||
use futures::{Async, Future, Poll, Stream};
|
use futures::{Future, Stream};
|
||||||
|
|
||||||
/// Execution context for http actors
|
/// Execution context for http actors
|
||||||
pub struct HttpContext<A>
|
pub struct HttpContext<A>
|
||||||
@ -43,7 +45,7 @@ where
|
|||||||
#[inline]
|
#[inline]
|
||||||
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
|
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
|
||||||
where
|
where
|
||||||
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
|
F: ActorFuture<Output = (), Actor = A> + 'static,
|
||||||
{
|
{
|
||||||
self.inner.spawn(fut)
|
self.inner.spawn(fut)
|
||||||
}
|
}
|
||||||
@ -51,7 +53,7 @@ where
|
|||||||
#[inline]
|
#[inline]
|
||||||
fn wait<F>(&mut self, fut: F)
|
fn wait<F>(&mut self, fut: F)
|
||||||
where
|
where
|
||||||
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
|
F: ActorFuture<Output = (), Actor = A> + 'static,
|
||||||
{
|
{
|
||||||
self.inner.wait(fut)
|
self.inner.wait(fut)
|
||||||
}
|
}
|
||||||
@ -81,7 +83,7 @@ where
|
|||||||
{
|
{
|
||||||
#[inline]
|
#[inline]
|
||||||
/// Create a new HTTP Context from a request and an actor
|
/// Create a new HTTP Context from a request and an actor
|
||||||
pub fn create(actor: A) -> impl Stream<Item = Bytes, Error = Error> {
|
pub fn create(actor: A) -> impl Stream<Item = Result<Bytes, Error>> {
|
||||||
let mb = Mailbox::default();
|
let mb = Mailbox::default();
|
||||||
let ctx = HttpContext {
|
let ctx = HttpContext {
|
||||||
inner: ContextParts::new(mb.sender_producer()),
|
inner: ContextParts::new(mb.sender_producer()),
|
||||||
@ -91,7 +93,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new HTTP Context
|
/// Create a new HTTP Context
|
||||||
pub fn with_factory<F>(f: F) -> impl Stream<Item = Bytes, Error = Error>
|
pub fn with_factory<F>(f: F) -> impl Stream<Item = Result<Bytes, Error>>
|
||||||
where
|
where
|
||||||
F: FnOnce(&mut Self) -> A + 'static,
|
F: FnOnce(&mut Self) -> A + 'static,
|
||||||
{
|
{
|
||||||
@ -160,24 +162,23 @@ impl<A> Stream for HttpContextFut<A>
|
|||||||
where
|
where
|
||||||
A: Actor<Context = HttpContext<A>>,
|
A: Actor<Context = HttpContext<A>>,
|
||||||
{
|
{
|
||||||
type Item = Bytes;
|
type Item = Result<Bytes, Error>;
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Option<Bytes>, Error> {
|
fn poll_next(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Self::Item>> {
|
||||||
if self.fut.alive() {
|
if self.fut.alive() {
|
||||||
match self.fut.poll() {
|
let _ = Pin::new(&mut self.fut).poll(cx);
|
||||||
Ok(Async::NotReady) | Ok(Async::Ready(())) => (),
|
|
||||||
Err(_) => return Err(ErrorInternalServerError("error")),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// frames
|
// frames
|
||||||
if let Some(data) = self.fut.ctx().stream.pop_front() {
|
if let Some(data) = self.fut.ctx().stream.pop_front() {
|
||||||
Ok(Async::Ready(data))
|
Poll::Ready(data.map(|b| Ok(b)))
|
||||||
} else if self.fut.alive() {
|
} else if self.fut.alive() {
|
||||||
Ok(Async::NotReady)
|
Poll::Pending
|
||||||
} else {
|
} else {
|
||||||
Ok(Async::Ready(None))
|
Poll::Ready(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -199,9 +200,9 @@ mod tests {
|
|||||||
|
|
||||||
use actix::Actor;
|
use actix::Actor;
|
||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use actix_web::test::{block_on, call_service, init_service, TestRequest};
|
use actix_web::test::{call_service, init_service, read_body, TestRequest};
|
||||||
use actix_web::{web, App, HttpResponse};
|
use actix_web::{web, App, HttpResponse};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::Bytes;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
@ -223,31 +224,25 @@ mod tests {
|
|||||||
if self.count > 3 {
|
if self.count > 3 {
|
||||||
ctx.write_eof()
|
ctx.write_eof()
|
||||||
} else {
|
} else {
|
||||||
ctx.write(Bytes::from(format!("LINE-{}", self.count).as_bytes()));
|
ctx.write(Bytes::from(format!("LINE-{}", self.count)));
|
||||||
ctx.run_later(Duration::from_millis(100), |slf, ctx| slf.write(ctx));
|
ctx.run_later(Duration::from_millis(100), |slf, ctx| slf.write(ctx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[actix_rt::test]
|
||||||
fn test_default_resource() {
|
async fn test_default_resource() {
|
||||||
let mut srv =
|
let mut srv =
|
||||||
init_service(App::new().service(web::resource("/test").to(|| {
|
init_service(App::new().service(web::resource("/test").to(|| {
|
||||||
HttpResponse::Ok().streaming(HttpContext::create(MyActor { count: 0 }))
|
HttpResponse::Ok().streaming(HttpContext::create(MyActor { count: 0 }))
|
||||||
})));
|
})))
|
||||||
|
.await;
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/test").to_request();
|
let req = TestRequest::with_uri("/test").to_request();
|
||||||
let mut resp = call_service(&mut srv, req);
|
let resp = call_service(&mut srv, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let body = block_on(resp.take_body().fold(
|
let body = read_body(resp).await;
|
||||||
BytesMut::new(),
|
assert_eq!(body, Bytes::from_static(b"LINE-1LINE-2LINE-3"));
|
||||||
move |mut body, chunk| {
|
|
||||||
body.extend_from_slice(&chunk);
|
|
||||||
Ok::<_, Error>(body)
|
|
||||||
},
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(body.freeze(), Bytes::from_static(b"LINE-1LINE-2LINE-3"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
//! Websocket integration
|
//! Websocket integration
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use std::io;
|
use std::io;
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix::dev::{
|
use actix::dev::{
|
||||||
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, StreamHandler,
|
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, StreamHandler,
|
||||||
@ -16,20 +18,20 @@ use actix_http::ws::{hash_key, Codec};
|
|||||||
pub use actix_http::ws::{
|
pub use actix_http::ws::{
|
||||||
CloseCode, CloseReason, Frame, HandshakeError, Message, ProtocolError,
|
CloseCode, CloseReason, Frame, HandshakeError, Message, ProtocolError,
|
||||||
};
|
};
|
||||||
|
|
||||||
use actix_web::dev::HttpResponseBuilder;
|
use actix_web::dev::HttpResponseBuilder;
|
||||||
use actix_web::error::{Error, ErrorInternalServerError, PayloadError};
|
use actix_web::error::{Error, PayloadError};
|
||||||
use actix_web::http::{header, Method, StatusCode};
|
use actix_web::http::{header, Method, StatusCode};
|
||||||
use actix_web::{HttpRequest, HttpResponse};
|
use actix_web::{HttpRequest, HttpResponse};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::sync::oneshot::Sender;
|
use futures::channel::oneshot::Sender;
|
||||||
use futures::{Async, Future, Poll, Stream};
|
use futures::{Future, Stream};
|
||||||
|
|
||||||
/// Do websocket handshake and start ws actor.
|
/// Do websocket handshake and start ws actor.
|
||||||
pub fn start<A, T>(actor: A, req: &HttpRequest, stream: T) -> Result<HttpResponse, Error>
|
pub fn start<A, T>(actor: A, req: &HttpRequest, stream: T) -> Result<HttpResponse, Error>
|
||||||
where
|
where
|
||||||
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
|
A: Actor<Context = WebsocketContext<A>>
|
||||||
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
+ StreamHandler<Result<Message, ProtocolError>>,
|
||||||
|
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||||
{
|
{
|
||||||
let mut res = handshake(req)?;
|
let mut res = handshake(req)?;
|
||||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
||||||
@ -52,8 +54,9 @@ pub fn start_with_addr<A, T>(
|
|||||||
stream: T,
|
stream: T,
|
||||||
) -> Result<(Addr<A>, HttpResponse), Error>
|
) -> Result<(Addr<A>, HttpResponse), Error>
|
||||||
where
|
where
|
||||||
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
|
A: Actor<Context = WebsocketContext<A>>
|
||||||
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
+ StreamHandler<Result<Message, ProtocolError>>,
|
||||||
|
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||||
{
|
{
|
||||||
let mut res = handshake(req)?;
|
let mut res = handshake(req)?;
|
||||||
let (addr, out_stream) = WebsocketContext::create_with_addr(actor, stream);
|
let (addr, out_stream) = WebsocketContext::create_with_addr(actor, stream);
|
||||||
@ -70,8 +73,9 @@ pub fn start_with_protocols<A, T>(
|
|||||||
stream: T,
|
stream: T,
|
||||||
) -> Result<HttpResponse, Error>
|
) -> Result<HttpResponse, Error>
|
||||||
where
|
where
|
||||||
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
|
A: Actor<Context = WebsocketContext<A>>
|
||||||
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
+ StreamHandler<Result<Message, ProtocolError>>,
|
||||||
|
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||||
{
|
{
|
||||||
let mut res = handshake_with_protocols(req, protocols)?;
|
let mut res = handshake_with_protocols(req, protocols)?;
|
||||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
||||||
@ -202,14 +206,14 @@ where
|
|||||||
{
|
{
|
||||||
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
|
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
|
||||||
where
|
where
|
||||||
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
|
F: ActorFuture<Output = (), Actor = A> + 'static,
|
||||||
{
|
{
|
||||||
self.inner.spawn(fut)
|
self.inner.spawn(fut)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn wait<F>(&mut self, fut: F)
|
fn wait<F>(&mut self, fut: F)
|
||||||
where
|
where
|
||||||
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
|
F: ActorFuture<Output = (), Actor = A> + 'static,
|
||||||
{
|
{
|
||||||
self.inner.wait(fut)
|
self.inner.wait(fut)
|
||||||
}
|
}
|
||||||
@ -238,10 +242,10 @@ where
|
|||||||
{
|
{
|
||||||
#[inline]
|
#[inline]
|
||||||
/// Create a new Websocket context from a request and an actor
|
/// Create a new Websocket context from a request and an actor
|
||||||
pub fn create<S>(actor: A, stream: S) -> impl Stream<Item = Bytes, Error = Error>
|
pub fn create<S>(actor: A, stream: S) -> impl Stream<Item = Result<Bytes, Error>>
|
||||||
where
|
where
|
||||||
A: StreamHandler<Message, ProtocolError>,
|
A: StreamHandler<Result<Message, ProtocolError>>,
|
||||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||||
{
|
{
|
||||||
let (_, stream) = WebsocketContext::create_with_addr(actor, stream);
|
let (_, stream) = WebsocketContext::create_with_addr(actor, stream);
|
||||||
stream
|
stream
|
||||||
@ -256,10 +260,10 @@ where
|
|||||||
pub fn create_with_addr<S>(
|
pub fn create_with_addr<S>(
|
||||||
actor: A,
|
actor: A,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> (Addr<A>, impl Stream<Item = Bytes, Error = Error>)
|
) -> (Addr<A>, impl Stream<Item = Result<Bytes, Error>>)
|
||||||
where
|
where
|
||||||
A: StreamHandler<Message, ProtocolError>,
|
A: StreamHandler<Result<Message, ProtocolError>>,
|
||||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||||
{
|
{
|
||||||
let mb = Mailbox::default();
|
let mb = Mailbox::default();
|
||||||
let mut ctx = WebsocketContext {
|
let mut ctx = WebsocketContext {
|
||||||
@ -279,10 +283,10 @@ where
|
|||||||
actor: A,
|
actor: A,
|
||||||
stream: S,
|
stream: S,
|
||||||
codec: Codec,
|
codec: Codec,
|
||||||
) -> impl Stream<Item = Bytes, Error = Error>
|
) -> impl Stream<Item = Result<Bytes, Error>>
|
||||||
where
|
where
|
||||||
A: StreamHandler<Message, ProtocolError>,
|
A: StreamHandler<Result<Message, ProtocolError>>,
|
||||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||||
{
|
{
|
||||||
let mb = Mailbox::default();
|
let mb = Mailbox::default();
|
||||||
let mut ctx = WebsocketContext {
|
let mut ctx = WebsocketContext {
|
||||||
@ -298,11 +302,11 @@ where
|
|||||||
pub fn with_factory<S, F>(
|
pub fn with_factory<S, F>(
|
||||||
stream: S,
|
stream: S,
|
||||||
f: F,
|
f: F,
|
||||||
) -> impl Stream<Item = Bytes, Error = Error>
|
) -> impl Stream<Item = Result<Bytes, Error>>
|
||||||
where
|
where
|
||||||
F: FnOnce(&mut Self) -> A + 'static,
|
F: FnOnce(&mut Self) -> A + 'static,
|
||||||
A: StreamHandler<Message, ProtocolError>,
|
A: StreamHandler<Result<Message, ProtocolError>>,
|
||||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
S: Stream<Item = Result<Bytes, PayloadError>> + 'static,
|
||||||
{
|
{
|
||||||
let mb = Mailbox::default();
|
let mb = Mailbox::default();
|
||||||
let mut ctx = WebsocketContext {
|
let mut ctx = WebsocketContext {
|
||||||
@ -346,14 +350,14 @@ where
|
|||||||
|
|
||||||
/// Send ping frame
|
/// Send ping frame
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn ping(&mut self, message: &str) {
|
pub fn ping(&mut self, message: &[u8]) {
|
||||||
self.write_raw(Message::Ping(message.to_string()));
|
self.write_raw(Message::Ping(Bytes::copy_from_slice(message)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send pong frame
|
/// Send pong frame
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn pong(&mut self, message: &str) {
|
pub fn pong(&mut self, message: &[u8]) {
|
||||||
self.write_raw(Message::Pong(message.to_string()));
|
self.write_raw(Message::Pong(Bytes::copy_from_slice(message)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send close frame
|
/// Send close frame
|
||||||
@ -415,30 +419,34 @@ impl<A> Stream for WebsocketContextFut<A>
|
|||||||
where
|
where
|
||||||
A: Actor<Context = WebsocketContext<A>>,
|
A: Actor<Context = WebsocketContext<A>>,
|
||||||
{
|
{
|
||||||
type Item = Bytes;
|
type Item = Result<Bytes, Error>;
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Option<Bytes>, Error> {
|
fn poll_next(
|
||||||
if self.fut.alive() && self.fut.poll().is_err() {
|
self: Pin<&mut Self>,
|
||||||
return Err(ErrorInternalServerError("error"));
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Self::Item>> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
|
||||||
|
if this.fut.alive() {
|
||||||
|
let _ = Pin::new(&mut this.fut).poll(cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
// encode messages
|
// encode messages
|
||||||
while let Some(item) = self.fut.ctx().messages.pop_front() {
|
while let Some(item) = this.fut.ctx().messages.pop_front() {
|
||||||
if let Some(msg) = item {
|
if let Some(msg) = item {
|
||||||
self.encoder.encode(msg, &mut self.buf)?;
|
this.encoder.encode(msg, &mut this.buf)?;
|
||||||
} else {
|
} else {
|
||||||
self.closed = true;
|
this.closed = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.buf.is_empty() {
|
if !this.buf.is_empty() {
|
||||||
Ok(Async::Ready(Some(self.buf.take().freeze())))
|
Poll::Ready(Some(Ok(this.buf.split().freeze())))
|
||||||
} else if self.fut.alive() && !self.closed {
|
} else if this.fut.alive() && !this.closed {
|
||||||
Ok(Async::NotReady)
|
Poll::Pending
|
||||||
} else {
|
} else {
|
||||||
Ok(Async::Ready(None))
|
Poll::Ready(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -454,7 +462,9 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[pin_project::pin_project]
|
||||||
struct WsStream<S> {
|
struct WsStream<S> {
|
||||||
|
#[pin]
|
||||||
stream: S,
|
stream: S,
|
||||||
decoder: Codec,
|
decoder: Codec,
|
||||||
buf: BytesMut,
|
buf: BytesMut,
|
||||||
@ -463,7 +473,7 @@ struct WsStream<S> {
|
|||||||
|
|
||||||
impl<S> WsStream<S>
|
impl<S> WsStream<S>
|
||||||
where
|
where
|
||||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
S: Stream<Item = Result<Bytes, PayloadError>>,
|
||||||
{
|
{
|
||||||
fn new(stream: S, codec: Codec) -> Self {
|
fn new(stream: S, codec: Codec) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@ -477,62 +487,64 @@ where
|
|||||||
|
|
||||||
impl<S> Stream for WsStream<S>
|
impl<S> Stream for WsStream<S>
|
||||||
where
|
where
|
||||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
S: Stream<Item = Result<Bytes, PayloadError>>,
|
||||||
{
|
{
|
||||||
type Item = Message;
|
type Item = Result<Message, ProtocolError>;
|
||||||
type Error = ProtocolError;
|
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
fn poll_next(
|
||||||
if !self.closed {
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Self::Item>> {
|
||||||
|
let mut this = self.as_mut().project();
|
||||||
|
|
||||||
|
if !*this.closed {
|
||||||
loop {
|
loop {
|
||||||
match self.stream.poll() {
|
this = self.as_mut().project();
|
||||||
Ok(Async::Ready(Some(chunk))) => {
|
match Pin::new(&mut this.stream).poll_next(cx) {
|
||||||
self.buf.extend_from_slice(&chunk[..]);
|
Poll::Ready(Some(Ok(chunk))) => {
|
||||||
|
this.buf.extend_from_slice(&chunk[..]);
|
||||||
}
|
}
|
||||||
Ok(Async::Ready(None)) => {
|
Poll::Ready(None) => {
|
||||||
self.closed = true;
|
*this.closed = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => break,
|
Poll::Pending => break,
|
||||||
Err(e) => {
|
Poll::Ready(Some(Err(e))) => {
|
||||||
return Err(ProtocolError::Io(io::Error::new(
|
return Poll::Ready(Some(Err(ProtocolError::Io(
|
||||||
io::ErrorKind::Other,
|
io::Error::new(io::ErrorKind::Other, format!("{}", e)),
|
||||||
format!("{}", e),
|
))));
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match self.decoder.decode(&mut self.buf)? {
|
match this.decoder.decode(this.buf)? {
|
||||||
None => {
|
None => {
|
||||||
if self.closed {
|
if *this.closed {
|
||||||
Ok(Async::Ready(None))
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
Ok(Async::NotReady)
|
Poll::Pending
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(frm) => {
|
Some(frm) => {
|
||||||
let msg = match frm {
|
let msg = match frm {
|
||||||
Frame::Text(data) => {
|
Frame::Text(data) => Message::Text(
|
||||||
if let Some(data) = data {
|
std::str::from_utf8(&data)
|
||||||
Message::Text(
|
.map_err(|e| {
|
||||||
std::str::from_utf8(&data)
|
ProtocolError::Io(io::Error::new(
|
||||||
.map_err(|_| ProtocolError::BadEncoding)?
|
io::ErrorKind::Other,
|
||||||
.to_string(),
|
format!("{}", e),
|
||||||
)
|
))
|
||||||
} else {
|
})?
|
||||||
Message::Text(String::new())
|
.to_string(),
|
||||||
}
|
|
||||||
}
|
|
||||||
Frame::Binary(data) => Message::Binary(
|
|
||||||
data.map(|b| b.freeze()).unwrap_or_else(Bytes::new),
|
|
||||||
),
|
),
|
||||||
|
Frame::Binary(data) => Message::Binary(data),
|
||||||
Frame::Ping(s) => Message::Ping(s),
|
Frame::Ping(s) => Message::Ping(s),
|
||||||
Frame::Pong(s) => Message::Pong(s),
|
Frame::Pong(s) => Message::Pong(s),
|
||||||
Frame::Close(reason) => Message::Close(reason),
|
Frame::Close(reason) => Message::Close(reason),
|
||||||
|
Frame::Continuation(item) => Message::Continuation(item),
|
||||||
};
|
};
|
||||||
Ok(Async::Ready(Some(msg)))
|
Poll::Ready(Some(Ok(msg)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,8 @@
|
|||||||
use actix::prelude::*;
|
use actix::prelude::*;
|
||||||
use actix_http::HttpService;
|
use actix_web::{test, web, App, HttpRequest};
|
||||||
use actix_http_test::TestServer;
|
|
||||||
use actix_web::{web, App, HttpRequest};
|
|
||||||
use actix_web_actors::*;
|
use actix_web_actors::*;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::Bytes;
|
||||||
use futures::{Sink, Stream};
|
use futures::{SinkExt, StreamExt};
|
||||||
|
|
||||||
struct Ws;
|
struct Ws;
|
||||||
|
|
||||||
@ -12,9 +10,13 @@ impl Actor for Ws {
|
|||||||
type Context = ws::WebsocketContext<Self>;
|
type Context = ws::WebsocketContext<Self>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {
|
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Ws {
|
||||||
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
|
fn handle(
|
||||||
match msg {
|
&mut self,
|
||||||
|
msg: Result<ws::Message, ws::ProtocolError>,
|
||||||
|
ctx: &mut Self::Context,
|
||||||
|
) {
|
||||||
|
match msg.unwrap() {
|
||||||
ws::Message::Ping(msg) => ctx.pong(&msg),
|
ws::Message::Ping(msg) => ctx.pong(&msg),
|
||||||
ws::Message::Text(text) => ctx.text(text),
|
ws::Message::Text(text) => ctx.text(text),
|
||||||
ws::Message::Binary(bin) => ctx.binary(bin),
|
ws::Message::Binary(bin) => ctx.binary(bin),
|
||||||
@ -24,45 +26,42 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[actix_rt::test]
|
||||||
fn test_simple() {
|
async fn test_simple() {
|
||||||
let mut srv =
|
let mut srv = test::start(|| {
|
||||||
TestServer::new(|| {
|
App::new().service(web::resource("/").to(
|
||||||
HttpService::new(App::new().service(web::resource("/").to(
|
|req: HttpRequest, stream: web::Payload| {
|
||||||
|req: HttpRequest, stream: web::Payload| ws::start(Ws, &req, stream),
|
async move { ws::start(Ws, &req, stream) }
|
||||||
)))
|
},
|
||||||
});
|
))
|
||||||
|
});
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
let framed = srv.ws().unwrap();
|
let mut framed = srv.ws().await.unwrap();
|
||||||
let framed = srv
|
framed
|
||||||
.block_on(framed.send(ws::Message::Text("text".to_string())))
|
.send(ws::Message::Text("text".to_string()))
|
||||||
.unwrap();
|
.await
|
||||||
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
|
|
||||||
assert_eq!(item, Some(ws::Frame::Text(Some(BytesMut::from("text")))));
|
|
||||||
|
|
||||||
let framed = srv
|
|
||||||
.block_on(framed.send(ws::Message::Binary("text".into())))
|
|
||||||
.unwrap();
|
|
||||||
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
item,
|
|
||||||
Some(ws::Frame::Binary(Some(Bytes::from_static(b"text").into())))
|
|
||||||
);
|
|
||||||
|
|
||||||
let framed = srv
|
|
||||||
.block_on(framed.send(ws::Message::Ping("text".into())))
|
|
||||||
.unwrap();
|
|
||||||
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
|
|
||||||
assert_eq!(item, Some(ws::Frame::Pong("text".to_string().into())));
|
|
||||||
|
|
||||||
let framed = srv
|
|
||||||
.block_on(framed.send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))))
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let (item, _framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
|
||||||
item,
|
|
||||||
Some(ws::Frame::Close(Some(ws::CloseCode::Normal.into())))
|
framed
|
||||||
);
|
.send(ws::Message::Binary("text".into()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
|
assert_eq!(item, ws::Frame::Binary(Bytes::from_static(b"text").into()));
|
||||||
|
|
||||||
|
framed.send(ws::Message::Ping("text".into())).await.unwrap();
|
||||||
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
|
assert_eq!(item, ws::Frame::Pong(Bytes::copy_from_slice(b"text")));
|
||||||
|
|
||||||
|
framed
|
||||||
|
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
|
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.0] - 2019-12-13
|
||||||
|
|
||||||
|
* Generate code for actix-web 2.0
|
||||||
|
|
||||||
## [0.1.3] - 2019-10-14
|
## [0.1.3] - 2019-10-14
|
||||||
|
|
||||||
* Bump up `syn` & `quote` to 1.0
|
* Bump up `syn` & `quote` to 1.0
|
||||||
|
@ -18,5 +18,5 @@ proc-macro2 = "^1"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = { version = "1.0.0" }
|
actix-rt = { version = "1.0.0" }
|
||||||
actix-web = { version = "2.0.0-alpha.4" }
|
actix-web = { version = "2.0.0-rc" }
|
||||||
futures = { version = "0.3.1" }
|
futures = { version = "0.3.1" }
|
||||||
|
@ -1,5 +1,10 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-12-15
|
||||||
|
|
||||||
|
* Fix compilation with default features off
|
||||||
|
|
||||||
|
|
||||||
## [1.0.0] - 2019-12-13
|
## [1.0.0] - 2019-12-13
|
||||||
|
|
||||||
* Release
|
* Release
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "awc"
|
name = "awc"
|
||||||
version = "1.0.0"
|
version = "1.0.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix http client."
|
description = "Actix http client."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -35,12 +35,12 @@ compress = ["actix-http/compress"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-http = "1.0.0"
|
actix-http = "1.0.0"
|
||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
|
|
||||||
base64 = "0.11"
|
base64 = "0.11"
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.2"
|
||||||
futures-core = "0.3.1"
|
futures-core = "0.3.1"
|
||||||
log =" 0.4"
|
log =" 0.4"
|
||||||
@ -54,14 +54,14 @@ open-ssl = { version="0.10", package="openssl", optional = true }
|
|||||||
rust-tls = { version = "0.16.0", package="rustls", optional = true, features = ["dangerous_configuration"] }
|
rust-tls = { version = "0.16.0", package="rustls", optional = true, features = ["dangerous_configuration"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-connect = { version = "1.0.0", features=["openssl"] }
|
actix-connect = { version = "1.0.1", features=["openssl"] }
|
||||||
actix-web = { version = "2.0.0-alpha.3", features=["openssl"] }
|
actix-web = { version = "2.0.0-rc", features=["openssl"] }
|
||||||
actix-http = { version = "1.0.0", features=["openssl"] }
|
actix-http = { version = "1.0.1", features=["openssl"] }
|
||||||
actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
|
actix-http-test = { version = "1.0.0", features=["openssl"] }
|
||||||
actix-utils = "1.0.0"
|
actix-utils = "1.0.3"
|
||||||
actix-server = "1.0.0"
|
actix-server = "1.0.0"
|
||||||
actix-tls = { version = "1.0.0", features=["openssl", "rustls"] }
|
actix-tls = { version = "1.0.0", features=["openssl", "rustls"] }
|
||||||
brotli = "3.3.0"
|
brotli2 = "0.3.2"
|
||||||
flate2 = "1.0.13"
|
flate2 = "1.0.13"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
|
@ -7,15 +7,21 @@ use std::time::Duration;
|
|||||||
use actix_rt::time::{delay_for, Delay};
|
use actix_rt::time::{delay_for, Delay};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use derive_more::From;
|
use derive_more::From;
|
||||||
use futures_core::{ready, Future, Stream};
|
use futures_core::{Future, Stream};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json;
|
use serde_json;
|
||||||
|
|
||||||
use actix_http::body::{Body, BodyStream};
|
use actix_http::body::{Body, BodyStream};
|
||||||
use actix_http::encoding::Decoder;
|
use actix_http::http::header::{self, IntoHeaderValue};
|
||||||
use actix_http::http::header::{self, ContentEncoding, IntoHeaderValue};
|
|
||||||
use actix_http::http::{Error as HttpError, HeaderMap, HeaderName};
|
use actix_http::http::{Error as HttpError, HeaderMap, HeaderName};
|
||||||
use actix_http::{Error, Payload, PayloadStream, RequestHead};
|
use actix_http::{Error, RequestHead};
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
|
use actix_http::encoding::Decoder;
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
|
use actix_http::http::header::ContentEncoding;
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
|
use actix_http::{Payload, PayloadStream};
|
||||||
|
|
||||||
use crate::error::{FreezeRequestError, InvalidUrl, SendRequestError};
|
use crate::error::{FreezeRequestError, InvalidUrl, SendRequestError};
|
||||||
use crate::response::ClientResponse;
|
use crate::response::ClientResponse;
|
||||||
@ -67,6 +73,7 @@ impl SendClientRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
impl Future for SendClientRequest {
|
impl Future for SendClientRequest {
|
||||||
type Output =
|
type Output =
|
||||||
Result<ClientResponse<Decoder<Payload<PayloadStream>>>, SendRequestError>;
|
Result<ClientResponse<Decoder<Payload<PayloadStream>>>, SendRequestError>;
|
||||||
@ -83,7 +90,7 @@ impl Future for SendClientRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let res = ready!(Pin::new(send).poll(cx)).map(|res| {
|
let res = futures_core::ready!(Pin::new(send).poll(cx)).map(|res| {
|
||||||
res.map_body(|head, payload| {
|
res.map_body(|head, payload| {
|
||||||
if *response_decompress {
|
if *response_decompress {
|
||||||
Payload::Stream(Decoder::from_headers(
|
Payload::Stream(Decoder::from_headers(
|
||||||
@ -109,6 +116,30 @@ impl Future for SendClientRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "compress"))]
|
||||||
|
impl Future for SendClientRequest {
|
||||||
|
type Output = Result<ClientResponse, SendRequestError>;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
let this = self.get_mut();
|
||||||
|
match this {
|
||||||
|
SendClientRequest::Fut(send, delay, _) => {
|
||||||
|
if delay.is_some() {
|
||||||
|
match Pin::new(delay.as_mut().unwrap()).poll(cx) {
|
||||||
|
Poll::Pending => (),
|
||||||
|
_ => return Poll::Ready(Err(SendRequestError::Timeout)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Pin::new(send).poll(cx)
|
||||||
|
}
|
||||||
|
SendClientRequest::Err(ref mut e) => match e.take() {
|
||||||
|
Some(e) => Poll::Ready(Err(e)),
|
||||||
|
None => panic!("Attempting to call completed future"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<SendRequestError> for SendClientRequest {
|
impl From<SendRequestError> for SendClientRequest {
|
||||||
fn from(e: SendRequestError) -> Self {
|
fn from(e: SendRequestError) -> Self {
|
||||||
SendClientRequest::Err(Some(e))
|
SendClientRequest::Err(Some(e))
|
||||||
|
@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use brotli::CompressorWriter;
|
use brotli2::write::BrotliEncoder;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use flate2::read::GzDecoder;
|
use flate2::read::GzDecoder;
|
||||||
use flate2::write::GzEncoder;
|
use flate2::write::GzEncoder;
|
||||||
@ -14,9 +14,10 @@ use rand::Rng;
|
|||||||
|
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::pipeline_factory;
|
use actix_service::{map_config, pipeline_factory};
|
||||||
|
use actix_web::dev::{AppConfig, BodyEncoding};
|
||||||
use actix_web::http::Cookie;
|
use actix_web::http::Cookie;
|
||||||
use actix_web::middleware::{BodyEncoding, Compress};
|
use actix_web::middleware::Compress;
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
http::header, test, web, App, Error, HttpMessage, HttpRequest, HttpResponse,
|
http::header, test, web, App, Error, HttpMessage, HttpRequest, HttpResponse,
|
||||||
};
|
};
|
||||||
@ -169,10 +170,11 @@ async fn test_connection_reuse() {
|
|||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::new(
|
HttpService::new(map_config(
|
||||||
App::new()
|
App::new()
|
||||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||||
)
|
|_| AppConfig::default(),
|
||||||
|
))
|
||||||
.tcp(),
|
.tcp(),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@ -205,10 +207,11 @@ async fn test_connection_force_close() {
|
|||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::new(
|
HttpService::new(map_config(
|
||||||
App::new()
|
App::new()
|
||||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
|
||||||
)
|
|_| AppConfig::default(),
|
||||||
|
))
|
||||||
.tcp(),
|
.tcp(),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@ -241,12 +244,13 @@ async fn test_connection_server_close() {
|
|||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::new(
|
HttpService::new(map_config(
|
||||||
App::new().service(
|
App::new().service(
|
||||||
web::resource("/")
|
web::resource("/")
|
||||||
.route(web::to(|| HttpResponse::Ok().force_close().finish())),
|
.route(web::to(|| HttpResponse::Ok().force_close().finish())),
|
||||||
),
|
),
|
||||||
)
|
|_| AppConfig::default(),
|
||||||
|
))
|
||||||
.tcp(),
|
.tcp(),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@ -279,8 +283,11 @@ async fn test_connection_wait_queue() {
|
|||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::new(App::new().service(
|
HttpService::new(map_config(
|
||||||
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
App::new().service(
|
||||||
|
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
|
||||||
|
),
|
||||||
|
|_| AppConfig::default(),
|
||||||
))
|
))
|
||||||
.tcp(),
|
.tcp(),
|
||||||
)
|
)
|
||||||
@ -323,12 +330,13 @@ async fn test_connection_wait_queue_force_close() {
|
|||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::new(
|
HttpService::new(map_config(
|
||||||
App::new().service(
|
App::new().service(
|
||||||
web::resource("/")
|
web::resource("/")
|
||||||
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
|
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
|
||||||
),
|
),
|
||||||
)
|
|_| AppConfig::default(),
|
||||||
|
))
|
||||||
.tcp(),
|
.tcp(),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@ -499,9 +507,9 @@ async fn test_client_gzip_encoding_large_random() {
|
|||||||
async fn test_client_brotli_encoding() {
|
async fn test_client_brotli_encoding() {
|
||||||
let srv = test::start(|| {
|
let srv = test::start(|| {
|
||||||
App::new().service(web::resource("/").route(web::to(|data: Bytes| {
|
App::new().service(web::resource("/").route(web::to(|data: Bytes| {
|
||||||
let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
|
let mut e = BrotliEncoder::new(Vec::new(), 5);
|
||||||
e.write_all(&data).unwrap();
|
e.write_all(&data).unwrap();
|
||||||
let data = e.into_inner();
|
let data = e.finish().unwrap();
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.header("content-encoding", "br")
|
.header("content-encoding", "br")
|
||||||
.body(data)
|
.body(data)
|
||||||
@ -526,9 +534,9 @@ async fn test_client_brotli_encoding_large_random() {
|
|||||||
|
|
||||||
let srv = test::start(|| {
|
let srv = test::start(|| {
|
||||||
App::new().service(web::resource("/").route(web::to(|data: Bytes| {
|
App::new().service(web::resource("/").route(web::to(|data: Bytes| {
|
||||||
let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
|
let mut e = BrotliEncoder::new(Vec::new(), 5);
|
||||||
e.write_all(&data).unwrap();
|
e.write_all(&data).unwrap();
|
||||||
let data = e.into_inner();
|
let data = e.finish().unwrap();
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.header("content-encoding", "br")
|
.header("content-encoding", "br")
|
||||||
.body(data)
|
.body(data)
|
||||||
|
@ -4,9 +4,9 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::{pipeline_factory, ServiceFactory};
|
use actix_service::{map_config, pipeline_factory, ServiceFactory};
|
||||||
use actix_web::http::Version;
|
use actix_web::http::Version;
|
||||||
use actix_web::{web, App, HttpResponse};
|
use actix_web::{dev::AppConfig, web, App, HttpResponse};
|
||||||
use futures::future::ok;
|
use futures::future::ok;
|
||||||
use open_ssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
|
use open_ssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
|
||||||
use rust_tls::ClientConfig;
|
use rust_tls::ClientConfig;
|
||||||
@ -62,8 +62,12 @@ async fn _test_connection_reuse_h2() {
|
|||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(App::new()
|
.h2(map_config(
|
||||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
App::new().service(
|
||||||
|
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||||
|
),
|
||||||
|
|_| AppConfig::default(),
|
||||||
|
))
|
||||||
.openssl(ssl_acceptor())
|
.openssl(ssl_acceptor())
|
||||||
.map_err(|_| ()),
|
.map_err(|_| ()),
|
||||||
)
|
)
|
||||||
|
@ -4,9 +4,9 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::{pipeline_factory, ServiceFactory};
|
use actix_service::{map_config, pipeline_factory, ServiceFactory};
|
||||||
use actix_web::http::Version;
|
use actix_web::http::Version;
|
||||||
use actix_web::{web, App, HttpResponse};
|
use actix_web::{dev::AppConfig, web, App, HttpResponse};
|
||||||
use futures::future::ok;
|
use futures::future::ok;
|
||||||
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
|
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
|
||||||
|
|
||||||
@ -44,8 +44,12 @@ async fn test_connection_reuse_h2() {
|
|||||||
})
|
})
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(App::new()
|
.h2(map_config(
|
||||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
App::new().service(
|
||||||
|
web::resource("/").route(web::to(|| HttpResponse::Ok())),
|
||||||
|
),
|
||||||
|
|_| AppConfig::default(),
|
||||||
|
))
|
||||||
.openssl(ssl_acceptor())
|
.openssl(ssl_acceptor())
|
||||||
.map_err(|_| ()),
|
.map_err(|_| ()),
|
||||||
)
|
)
|
||||||
|
@ -42,6 +42,6 @@ async fn main() -> std::io::Result<()> {
|
|||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind("127.0.0.1:8080")?
|
||||||
.workers(1)
|
.workers(1)
|
||||||
.start()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
@ -45,7 +45,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
})
|
})
|
||||||
.bind_uds("/Users/fafhrd91/uds-test")?
|
.bind_uds("/Users/fafhrd91/uds-test")?
|
||||||
.workers(1)
|
.workers(1)
|
||||||
.start()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
57
src/app.rs
57
src/app.rs
@ -5,6 +5,7 @@ use std::marker::PhantomData;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::body::{Body, MessageBody};
|
use actix_http::body::{Body, MessageBody};
|
||||||
|
use actix_http::Extensions;
|
||||||
use actix_service::boxed::{self, BoxServiceFactory};
|
use actix_service::boxed::{self, BoxServiceFactory};
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
|
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
|
||||||
@ -12,7 +13,7 @@ use actix_service::{
|
|||||||
use futures::future::{FutureExt, LocalBoxFuture};
|
use futures::future::{FutureExt, LocalBoxFuture};
|
||||||
|
|
||||||
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
|
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
|
||||||
use crate::config::{AppConfig, AppConfigInner, ServiceConfig};
|
use crate::config::ServiceConfig;
|
||||||
use crate::data::{Data, DataFactory};
|
use crate::data::{Data, DataFactory};
|
||||||
use crate::dev::ResourceDef;
|
use crate::dev::ResourceDef;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
@ -36,8 +37,8 @@ pub struct App<T, B> {
|
|||||||
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||||
data: Vec<Box<dyn DataFactory>>,
|
data: Vec<Box<dyn DataFactory>>,
|
||||||
data_factories: Vec<FnDataFactory>,
|
data_factories: Vec<FnDataFactory>,
|
||||||
config: AppConfigInner,
|
|
||||||
external: Vec<ResourceDef>,
|
external: Vec<ResourceDef>,
|
||||||
|
extensions: Extensions,
|
||||||
_t: PhantomData<B>,
|
_t: PhantomData<B>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,8 +53,8 @@ impl App<AppEntry, Body> {
|
|||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
default: None,
|
default: None,
|
||||||
factory_ref: fref,
|
factory_ref: fref,
|
||||||
config: AppConfigInner::default(),
|
|
||||||
external: Vec::new(),
|
external: Vec::new(),
|
||||||
|
extensions: Extensions::new(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -77,8 +78,9 @@ where
|
|||||||
/// an application instance. Http server constructs an application
|
/// an application instance. Http server constructs an application
|
||||||
/// instance for each thread, thus application data must be constructed
|
/// instance for each thread, thus application data must be constructed
|
||||||
/// multiple times. If you want to share data between different
|
/// multiple times. If you want to share data between different
|
||||||
/// threads, a shared object should be used, e.g. `Arc`. Application
|
/// threads, a shared object should be used, e.g. `Arc`. Internally `Data` type
|
||||||
/// data does not need to be `Send` or `Sync`.
|
/// uses `Arc` so data could be created outside of app factory and clones could
|
||||||
|
/// be stored via `App::app_data()` method.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use std::cell::Cell;
|
/// use std::cell::Cell;
|
||||||
@ -135,10 +137,15 @@ where
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set application data. Application data could be accessed
|
/// Set application level arbitrary data item.
|
||||||
/// by using `Data<T>` extractor where `T` is data type.
|
///
|
||||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
/// Application data stored with `App::app_data()` method is available
|
||||||
self.data.push(Box::new(data));
|
/// via `HttpRequest::app_data()` method at runtime.
|
||||||
|
///
|
||||||
|
/// This method could be used for storing `Data<T>` as well, in that case
|
||||||
|
/// data could be accessed by using `Data<T>` extractor.
|
||||||
|
pub fn app_data<U: 'static>(mut self, ext: U) -> Self {
|
||||||
|
self.extensions.insert(ext);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -225,18 +232,6 @@ where
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set server host name.
|
|
||||||
///
|
|
||||||
/// Host name is used by application router as a hostname for url generation.
|
|
||||||
/// Check [ConnectionInfo](./dev/struct.ConnectionInfo.html#method.host)
|
|
||||||
/// documentation for more information.
|
|
||||||
///
|
|
||||||
/// By default host name is set to a "localhost" value.
|
|
||||||
pub fn hostname(mut self, val: &str) -> Self {
|
|
||||||
self.config.host = val.to_owned();
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Default service to be used if no matching resource could be found.
|
/// Default service to be used if no matching resource could be found.
|
||||||
///
|
///
|
||||||
/// It is possible to use services like `Resource`, `Route`.
|
/// It is possible to use services like `Resource`, `Route`.
|
||||||
@ -383,8 +378,8 @@ where
|
|||||||
services: self.services,
|
services: self.services,
|
||||||
default: self.default,
|
default: self.default,
|
||||||
factory_ref: self.factory_ref,
|
factory_ref: self.factory_ref,
|
||||||
config: self.config,
|
|
||||||
external: self.external,
|
external: self.external,
|
||||||
|
extensions: self.extensions,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -445,8 +440,8 @@ where
|
|||||||
services: self.services,
|
services: self.services,
|
||||||
default: self.default,
|
default: self.default,
|
||||||
factory_ref: self.factory_ref,
|
factory_ref: self.factory_ref,
|
||||||
config: self.config,
|
|
||||||
external: self.external,
|
external: self.external,
|
||||||
|
extensions: self.extensions,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -472,7 +467,7 @@ where
|
|||||||
external: RefCell::new(self.external),
|
external: RefCell::new(self.external),
|
||||||
default: self.default,
|
default: self.default,
|
||||||
factory_ref: self.factory_ref,
|
factory_ref: self.factory_ref,
|
||||||
config: RefCell::new(AppConfig(Rc::new(self.config))),
|
extensions: RefCell::new(Some(self.extensions)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -556,6 +551,20 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_extension() {
|
||||||
|
let mut srv = init_service(App::new().app_data(10usize).service(
|
||||||
|
web::resource("/").to(|req: HttpRequest| {
|
||||||
|
assert_eq!(*req.app_data::<usize>().unwrap(), 10);
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}),
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
let req = TestRequest::default().to_request();
|
||||||
|
let resp = srv.call(req).await.unwrap();
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_wrap() {
|
async fn test_wrap() {
|
||||||
let mut srv = init_service(
|
let mut srv = init_service(
|
||||||
|
@ -39,9 +39,9 @@ where
|
|||||||
>,
|
>,
|
||||||
{
|
{
|
||||||
pub(crate) endpoint: T,
|
pub(crate) endpoint: T,
|
||||||
|
pub(crate) extensions: RefCell<Option<Extensions>>,
|
||||||
pub(crate) data: Rc<Vec<Box<dyn DataFactory>>>,
|
pub(crate) data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||||
pub(crate) data_factories: Rc<Vec<FnDataFactory>>,
|
pub(crate) data_factories: Rc<Vec<FnDataFactory>>,
|
||||||
pub(crate) config: RefCell<AppConfig>,
|
|
||||||
pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>,
|
pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>,
|
||||||
pub(crate) default: Option<Rc<HttpNewService>>,
|
pub(crate) default: Option<Rc<HttpNewService>>,
|
||||||
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||||
@ -58,7 +58,7 @@ where
|
|||||||
InitError = (),
|
InitError = (),
|
||||||
>,
|
>,
|
||||||
{
|
{
|
||||||
type Config = ();
|
type Config = AppConfig;
|
||||||
type Request = Request;
|
type Request = Request;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
@ -66,7 +66,7 @@ where
|
|||||||
type Service = AppInitService<T::Service, B>;
|
type Service = AppInitService<T::Service, B>;
|
||||||
type Future = AppInitResult<T, B>;
|
type Future = AppInitResult<T, B>;
|
||||||
|
|
||||||
fn new_service(&self, _: ()) -> Self::Future {
|
fn new_service(&self, config: AppConfig) -> Self::Future {
|
||||||
// update resource default service
|
// update resource default service
|
||||||
let default = self.default.clone().unwrap_or_else(|| {
|
let default = self.default.clone().unwrap_or_else(|| {
|
||||||
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| {
|
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| {
|
||||||
@ -75,11 +75,7 @@ where
|
|||||||
});
|
});
|
||||||
|
|
||||||
// App config
|
// App config
|
||||||
let mut config = AppService::new(
|
let mut config = AppService::new(config, default.clone(), self.data.clone());
|
||||||
self.config.borrow().clone(),
|
|
||||||
default.clone(),
|
|
||||||
self.data.clone(),
|
|
||||||
);
|
|
||||||
|
|
||||||
// register services
|
// register services
|
||||||
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
|
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
|
||||||
@ -119,6 +115,12 @@ where
|
|||||||
data: self.data.clone(),
|
data: self.data.clone(),
|
||||||
data_factories: Vec::new(),
|
data_factories: Vec::new(),
|
||||||
data_factories_fut: self.data_factories.iter().map(|f| f()).collect(),
|
data_factories_fut: self.data_factories.iter().map(|f| f()).collect(),
|
||||||
|
extensions: Some(
|
||||||
|
self.extensions
|
||||||
|
.borrow_mut()
|
||||||
|
.take()
|
||||||
|
.unwrap_or_else(Extensions::new),
|
||||||
|
),
|
||||||
config,
|
config,
|
||||||
rmap,
|
rmap,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
@ -139,6 +141,7 @@ where
|
|||||||
data: Rc<Vec<Box<dyn DataFactory>>>,
|
data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||||
data_factories: Vec<Box<dyn DataFactory>>,
|
data_factories: Vec<Box<dyn DataFactory>>,
|
||||||
data_factories_fut: Vec<LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>,
|
data_factories_fut: Vec<LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>,
|
||||||
|
extensions: Option<Extensions>,
|
||||||
_t: PhantomData<B>,
|
_t: PhantomData<B>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -177,7 +180,7 @@ where
|
|||||||
|
|
||||||
if this.endpoint.is_some() && this.data_factories_fut.is_empty() {
|
if this.endpoint.is_some() && this.data_factories_fut.is_empty() {
|
||||||
// create app data container
|
// create app data container
|
||||||
let mut data = Extensions::new();
|
let mut data = this.extensions.take().unwrap();
|
||||||
for f in this.data.iter() {
|
for f in this.data.iter() {
|
||||||
f.create(&mut data);
|
f.create(&mut data);
|
||||||
}
|
}
|
||||||
|
@ -124,14 +124,20 @@ impl AppService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AppConfig(pub(crate) Rc<AppConfigInner>);
|
pub struct AppConfig(Rc<AppConfigInner>);
|
||||||
|
|
||||||
|
struct AppConfigInner {
|
||||||
|
secure: bool,
|
||||||
|
host: String,
|
||||||
|
addr: SocketAddr,
|
||||||
|
}
|
||||||
|
|
||||||
impl AppConfig {
|
impl AppConfig {
|
||||||
pub(crate) fn new(inner: AppConfigInner) -> Self {
|
pub(crate) fn new(secure: bool, addr: SocketAddr, host: String) -> Self {
|
||||||
AppConfig(Rc::new(inner))
|
AppConfig(Rc::new(AppConfigInner { secure, addr, host }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set server host name.
|
/// Server host name.
|
||||||
///
|
///
|
||||||
/// Host name is used by application router as a hostname for url generation.
|
/// Host name is used by application router as a hostname for url generation.
|
||||||
/// Check [ConnectionInfo](./struct.ConnectionInfo.html#method.host)
|
/// Check [ConnectionInfo](./struct.ConnectionInfo.html#method.host)
|
||||||
@ -153,19 +159,13 @@ impl AppConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct AppConfigInner {
|
impl Default for AppConfig {
|
||||||
pub(crate) secure: bool,
|
fn default() -> Self {
|
||||||
pub(crate) host: String,
|
AppConfig::new(
|
||||||
pub(crate) addr: SocketAddr,
|
false,
|
||||||
}
|
"127.0.0.1:8080".parse().unwrap(),
|
||||||
|
"localhost:8080".to_owned(),
|
||||||
impl Default for AppConfigInner {
|
)
|
||||||
fn default() -> AppConfigInner {
|
|
||||||
AppConfigInner {
|
|
||||||
secure: false,
|
|
||||||
addr: "127.0.0.1:8080".parse().unwrap(),
|
|
||||||
host: "localhost:8080".to_owned(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
78
src/data.rs
78
src/data.rs
@ -56,7 +56,7 @@ pub(crate) trait DataFactory {
|
|||||||
///
|
///
|
||||||
/// let app = App::new()
|
/// let app = App::new()
|
||||||
/// // Store `MyData` in application storage.
|
/// // Store `MyData` in application storage.
|
||||||
/// .register_data(data.clone())
|
/// .app_data(data.clone())
|
||||||
/// .service(
|
/// .service(
|
||||||
/// web::resource("/index.html").route(
|
/// web::resource("/index.html").route(
|
||||||
/// web::get().to(index)));
|
/// web::get().to(index)));
|
||||||
@ -87,10 +87,10 @@ impl<T> Data<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Deref for Data<T> {
|
impl<T> Deref for Data<T> {
|
||||||
type Target = T;
|
type Target = Arc<T>;
|
||||||
|
|
||||||
fn deref(&self) -> &T {
|
fn deref(&self) -> &Arc<T> {
|
||||||
self.0.as_ref()
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -107,8 +107,8 @@ impl<T: 'static> FromRequest for Data<T> {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||||
if let Some(st) = req.get_app_data::<T>() {
|
if let Some(st) = req.app_data::<Data<T>>() {
|
||||||
ok(st)
|
ok(st.clone())
|
||||||
} else {
|
} else {
|
||||||
log::debug!(
|
log::debug!(
|
||||||
"Failed to construct App-level Data extractor. \
|
"Failed to construct App-level Data extractor. \
|
||||||
@ -136,19 +136,22 @@ impl<T: 'static> DataFactory for Data<T> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::http::StatusCode;
|
use crate::http::StatusCode;
|
||||||
use crate::test::{init_service, TestRequest};
|
use crate::test::{self, init_service, TestRequest};
|
||||||
use crate::{web, App, HttpResponse};
|
use crate::{web, App, HttpResponse};
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_data_extractor() {
|
async fn test_data_extractor() {
|
||||||
let mut srv =
|
let mut srv = init_service(App::new().data("TEST".to_string()).service(
|
||||||
init_service(App::new().data(10usize).service(
|
web::resource("/").to(|data: web::Data<String>| {
|
||||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
assert_eq!(data.to_lowercase(), "test");
|
||||||
))
|
HttpResponse::Ok()
|
||||||
.await;
|
}),
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
|
||||||
let req = TestRequest::default().to_request();
|
let req = TestRequest::default().to_request();
|
||||||
let resp = srv.call(req).await.unwrap();
|
let resp = srv.call(req).await.unwrap();
|
||||||
@ -165,9 +168,9 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_register_data_extractor() {
|
async fn test_app_data_extractor() {
|
||||||
let mut srv =
|
let mut srv =
|
||||||
init_service(App::new().register_data(Data::new(10usize)).service(
|
init_service(App::new().app_data(Data::new(10usize)).service(
|
||||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||||
))
|
))
|
||||||
.await;
|
.await;
|
||||||
@ -177,7 +180,7 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let mut srv =
|
let mut srv =
|
||||||
init_service(App::new().register_data(Data::new(10u32)).service(
|
init_service(App::new().app_data(Data::new(10u32)).service(
|
||||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||||
))
|
))
|
||||||
.await;
|
.await;
|
||||||
@ -220,7 +223,7 @@ mod tests {
|
|||||||
let mut srv = init_service(App::new().data(1usize).service(
|
let mut srv = init_service(App::new().data(1usize).service(
|
||||||
web::resource("/").data(10usize).route(web::get().to(
|
web::resource("/").data(10usize).route(web::get().to(
|
||||||
|data: web::Data<usize>| {
|
|data: web::Data<usize>| {
|
||||||
assert_eq!(*data, 10);
|
assert_eq!(**data, 10);
|
||||||
let _ = data.clone();
|
let _ = data.clone();
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
},
|
},
|
||||||
@ -232,4 +235,47 @@ mod tests {
|
|||||||
let resp = srv.call(req).await.unwrap();
|
let resp = srv.call(req).await.unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_data_drop() {
|
||||||
|
struct TestData(Arc<AtomicUsize>);
|
||||||
|
|
||||||
|
impl TestData {
|
||||||
|
fn new(inner: Arc<AtomicUsize>) -> Self {
|
||||||
|
let _ = inner.fetch_add(1, Ordering::SeqCst);
|
||||||
|
Self(inner)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clone for TestData {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
let inner = self.0.clone();
|
||||||
|
let _ = inner.fetch_add(1, Ordering::SeqCst);
|
||||||
|
Self(inner)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TestData {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.0.fetch_sub(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let num = Arc::new(AtomicUsize::new(0));
|
||||||
|
let data = TestData::new(num.clone());
|
||||||
|
assert_eq!(num.load(Ordering::SeqCst), 1);
|
||||||
|
|
||||||
|
let srv = test::start(move || {
|
||||||
|
let data = data.clone();
|
||||||
|
|
||||||
|
App::new()
|
||||||
|
.data(data)
|
||||||
|
.service(web::resource("/").to(|_data: Data<TestData>| async { "ok" }))
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(srv.get("/").send().await.unwrap().status().is_success());
|
||||||
|
srv.stop().await;
|
||||||
|
|
||||||
|
assert_eq!(num.load(Ordering::SeqCst), 0);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ use url::ParseError as UrlParseError;
|
|||||||
|
|
||||||
use crate::http::StatusCode;
|
use crate::http::StatusCode;
|
||||||
use crate::HttpResponse;
|
use crate::HttpResponse;
|
||||||
use serde_urlencoded::de;
|
|
||||||
|
|
||||||
/// Errors which can occur when attempting to generate resource uri.
|
/// Errors which can occur when attempting to generate resource uri.
|
||||||
#[derive(Debug, PartialEq, Display, From)]
|
#[derive(Debug, PartialEq, Display, From)]
|
||||||
@ -97,7 +96,7 @@ impl ResponseError for JsonPayloadError {
|
|||||||
pub enum PathError {
|
pub enum PathError {
|
||||||
/// Deserialize error
|
/// Deserialize error
|
||||||
#[display(fmt = "Path deserialize error: {}", _0)]
|
#[display(fmt = "Path deserialize error: {}", _0)]
|
||||||
Deserialize(de::Error),
|
Deserialize(serde::de::value::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `PathError`
|
/// Return `BadRequest` for `PathError`
|
||||||
@ -112,7 +111,7 @@ impl ResponseError for PathError {
|
|||||||
pub enum QueryPayloadError {
|
pub enum QueryPayloadError {
|
||||||
/// Deserialize error
|
/// Deserialize error
|
||||||
#[display(fmt = "Query deserialize error: {}", _0)]
|
#[display(fmt = "Query deserialize error: {}", _0)]
|
||||||
Deserialize(de::Error),
|
Deserialize(serde::de::value::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `QueryPayloadError`
|
/// Return `BadRequest` for `QueryPayloadError`
|
||||||
|
60
src/lib.rs
60
src/lib.rs
@ -20,7 +20,7 @@
|
|||||||
//! web::resource("/{name}/{id}/index.html").to(index))
|
//! web::resource("/{name}/{id}/index.html").to(index))
|
||||||
//! )
|
//! )
|
||||||
//! .bind("127.0.0.1:8080")?
|
//! .bind("127.0.0.1:8080")?
|
||||||
//! .start()
|
//! .run()
|
||||||
//! .await
|
//! .await
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
@ -141,6 +141,7 @@ pub mod dev {
|
|||||||
pub use crate::types::readlines::Readlines;
|
pub use crate::types::readlines::Readlines;
|
||||||
|
|
||||||
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
|
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
pub use actix_http::encoding::Decoder as Decompress;
|
pub use actix_http::encoding::Decoder as Decompress;
|
||||||
pub use actix_http::ResponseBuilder as HttpResponseBuilder;
|
pub use actix_http::ResponseBuilder as HttpResponseBuilder;
|
||||||
pub use actix_http::{
|
pub use actix_http::{
|
||||||
@ -150,12 +151,57 @@ pub mod dev {
|
|||||||
pub use actix_server::Server;
|
pub use actix_server::Server;
|
||||||
pub use actix_service::{Service, Transform};
|
pub use actix_service::{Service, Transform};
|
||||||
|
|
||||||
pub(crate) fn insert_slash(path: &str) -> String {
|
pub(crate) fn insert_slash(mut patterns: Vec<String>) -> Vec<String> {
|
||||||
let mut path = path.to_owned();
|
for path in &mut patterns {
|
||||||
if !path.is_empty() && !path.starts_with('/') {
|
if !path.is_empty() && !path.starts_with('/') {
|
||||||
path.insert(0, '/');
|
path.insert(0, '/');
|
||||||
};
|
};
|
||||||
path
|
}
|
||||||
|
patterns
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::http::header::ContentEncoding;
|
||||||
|
use actix_http::{Response, ResponseBuilder};
|
||||||
|
|
||||||
|
struct Enc(ContentEncoding);
|
||||||
|
|
||||||
|
/// Helper trait that allows to set specific encoding for response.
|
||||||
|
pub trait BodyEncoding {
|
||||||
|
/// Get content encoding
|
||||||
|
fn get_encoding(&self) -> Option<ContentEncoding>;
|
||||||
|
|
||||||
|
/// Set content encoding
|
||||||
|
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BodyEncoding for ResponseBuilder {
|
||||||
|
fn get_encoding(&self) -> Option<ContentEncoding> {
|
||||||
|
if let Some(ref enc) = self.extensions().get::<Enc>() {
|
||||||
|
Some(enc.0)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
|
||||||
|
self.extensions_mut().insert(Enc(encoding));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<B> BodyEncoding for Response<B> {
|
||||||
|
fn get_encoding(&self) -> Option<ContentEncoding> {
|
||||||
|
if let Some(ref enc) = self.extensions().get::<Enc>() {
|
||||||
|
Some(enc.0)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
|
||||||
|
self.extensions_mut().insert(Enc(encoding));
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -9,34 +9,14 @@ use std::task::{Context, Poll};
|
|||||||
use actix_http::body::MessageBody;
|
use actix_http::body::MessageBody;
|
||||||
use actix_http::encoding::Encoder;
|
use actix_http::encoding::Encoder;
|
||||||
use actix_http::http::header::{ContentEncoding, ACCEPT_ENCODING};
|
use actix_http::http::header::{ContentEncoding, ACCEPT_ENCODING};
|
||||||
use actix_http::{Error, Response, ResponseBuilder};
|
use actix_http::Error;
|
||||||
use actix_service::{Service, Transform};
|
use actix_service::{Service, Transform};
|
||||||
use futures::future::{ok, Ready};
|
use futures::future::{ok, Ready};
|
||||||
use pin_project::pin_project;
|
use pin_project::pin_project;
|
||||||
|
|
||||||
|
use crate::dev::BodyEncoding;
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
use crate::service::{ServiceRequest, ServiceResponse};
|
||||||
|
|
||||||
struct Enc(ContentEncoding);
|
|
||||||
|
|
||||||
/// Helper trait that allows to set specific encoding for response.
|
|
||||||
pub trait BodyEncoding {
|
|
||||||
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BodyEncoding for ResponseBuilder {
|
|
||||||
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
|
|
||||||
self.extensions_mut().insert(Enc(encoding));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<B> BodyEncoding for Response<B> {
|
|
||||||
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
|
|
||||||
self.extensions_mut().insert(Enc(encoding));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
/// `Middleware` for compressing response body.
|
/// `Middleware` for compressing response body.
|
||||||
///
|
///
|
||||||
@ -155,8 +135,8 @@ where
|
|||||||
|
|
||||||
match futures::ready!(this.fut.poll(cx)) {
|
match futures::ready!(this.fut.poll(cx)) {
|
||||||
Ok(resp) => {
|
Ok(resp) => {
|
||||||
let enc = if let Some(enc) = resp.response().extensions().get::<Enc>() {
|
let enc = if let Some(enc) = resp.response().get_encoding() {
|
||||||
enc.0
|
enc
|
||||||
} else {
|
} else {
|
||||||
*this.encoding
|
*this.encoding
|
||||||
};
|
};
|
||||||
|
@ -150,7 +150,7 @@ where
|
|||||||
}
|
}
|
||||||
Ok(res)
|
Ok(res)
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -140,7 +140,7 @@ where
|
|||||||
Ok(res)
|
Ok(res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.boxed_local()
|
.boxed_local()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,6 +1,9 @@
|
|||||||
//! Middlewares
|
//! Middlewares
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
mod compress;
|
mod compress;
|
||||||
pub use self::compress::{BodyEncoding, Compress};
|
#[cfg(feature = "compress")]
|
||||||
|
pub use self::compress::Compress;
|
||||||
|
|
||||||
mod condition;
|
mod condition;
|
||||||
mod defaultheaders;
|
mod defaultheaders;
|
||||||
|
@ -8,7 +8,6 @@ use actix_router::{Path, Url};
|
|||||||
use futures::future::{ok, Ready};
|
use futures::future::{ok, Ready};
|
||||||
|
|
||||||
use crate::config::AppConfig;
|
use crate::config::AppConfig;
|
||||||
use crate::data::Data;
|
|
||||||
use crate::error::UrlGenerationError;
|
use crate::error::UrlGenerationError;
|
||||||
use crate::extract::FromRequest;
|
use crate::extract::FromRequest;
|
||||||
use crate::info::ConnectionInfo;
|
use crate::info::ConnectionInfo;
|
||||||
@ -207,25 +206,15 @@ impl HttpRequest {
|
|||||||
&self.0.config
|
&self.0.config
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get an application data stored with `App::data()` method during
|
/// Get an application data stored with `App::extension()` method during
|
||||||
/// application configuration.
|
/// application configuration.
|
||||||
pub fn app_data<T: 'static>(&self) -> Option<&T> {
|
pub fn app_data<T: 'static>(&self) -> Option<&T> {
|
||||||
if let Some(st) = self.0.app_data.get::<Data<T>>() {
|
if let Some(st) = self.0.app_data.get::<T>() {
|
||||||
Some(&st)
|
Some(&st)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get an application data stored with `App::data()` method during
|
|
||||||
/// application configuration.
|
|
||||||
pub fn get_app_data<T: 'static>(&self) -> Option<Data<T>> {
|
|
||||||
if let Some(st) = self.0.app_data.get::<Data<T>>() {
|
|
||||||
Some(st.clone())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpMessage for HttpRequest {
|
impl HttpMessage for HttpRequest {
|
||||||
@ -467,8 +456,8 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_app_data() {
|
async fn test_data() {
|
||||||
let mut srv = init_service(App::new().data(10usize).service(
|
let mut srv = init_service(App::new().app_data(10usize).service(
|
||||||
web::resource("/").to(|req: HttpRequest| {
|
web::resource("/").to(|req: HttpRequest| {
|
||||||
if req.app_data::<usize>().is_some() {
|
if req.app_data::<usize>().is_some() {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
@ -483,7 +472,7 @@ mod tests {
|
|||||||
let resp = call_service(&mut srv, req).await;
|
let resp = call_service(&mut srv, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let mut srv = init_service(App::new().data(10u32).service(
|
let mut srv = init_service(App::new().app_data(10u32).service(
|
||||||
web::resource("/").to(|req: HttpRequest| {
|
web::resource("/").to(|req: HttpRequest| {
|
||||||
if req.app_data::<usize>().is_some() {
|
if req.app_data::<usize>().is_some() {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
|
@ -6,6 +6,7 @@ use std::rc::Rc;
|
|||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_http::{Error, Extensions, Response};
|
use actix_http::{Error, Extensions, Response};
|
||||||
|
use actix_router::IntoPattern;
|
||||||
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
|
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform,
|
apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform,
|
||||||
@ -48,7 +49,7 @@ type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Err
|
|||||||
/// Default behavior could be overriden with `default_resource()` method.
|
/// Default behavior could be overriden with `default_resource()` method.
|
||||||
pub struct Resource<T = ResourceEndpoint> {
|
pub struct Resource<T = ResourceEndpoint> {
|
||||||
endpoint: T,
|
endpoint: T,
|
||||||
rdef: String,
|
rdef: Vec<String>,
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
routes: Vec<Route>,
|
routes: Vec<Route>,
|
||||||
data: Option<Extensions>,
|
data: Option<Extensions>,
|
||||||
@ -58,12 +59,12 @@ pub struct Resource<T = ResourceEndpoint> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Resource {
|
impl Resource {
|
||||||
pub fn new(path: &str) -> Resource {
|
pub fn new<T: IntoPattern>(path: T) -> Resource {
|
||||||
let fref = Rc::new(RefCell::new(None));
|
let fref = Rc::new(RefCell::new(None));
|
||||||
|
|
||||||
Resource {
|
Resource {
|
||||||
routes: Vec::new(),
|
routes: Vec::new(),
|
||||||
rdef: path.to_string(),
|
rdef: path.patterns(),
|
||||||
name: None,
|
name: None,
|
||||||
endpoint: ResourceEndpoint::new(fref.clone()),
|
endpoint: ResourceEndpoint::new(fref.clone()),
|
||||||
factory_ref: fref,
|
factory_ref: fref,
|
||||||
@ -192,16 +193,13 @@ where
|
|||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn data<U: 'static>(self, data: U) -> Self {
|
pub fn data<U: 'static>(self, data: U) -> Self {
|
||||||
self.register_data(Data::new(data))
|
self.app_data(Data::new(data))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set or override application data.
|
/// Set or override application data.
|
||||||
///
|
///
|
||||||
/// This method has the same effect as [`Resource::data`](#method.data),
|
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
|
||||||
/// except that instead of taking a value of some type `T`, it expects a
|
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
|
||||||
/// value of type `Data<T>`. Use a `Data<T>` extractor to retrieve its
|
|
||||||
/// value.
|
|
||||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
|
||||||
if self.data.is_none() {
|
if self.data.is_none() {
|
||||||
self.data = Some(Extensions::new());
|
self.data = Some(Extensions::new());
|
||||||
}
|
}
|
||||||
@ -384,9 +382,9 @@ where
|
|||||||
Some(std::mem::replace(&mut self.guards, Vec::new()))
|
Some(std::mem::replace(&mut self.guards, Vec::new()))
|
||||||
};
|
};
|
||||||
let mut rdef = if config.is_root() || !self.rdef.is_empty() {
|
let mut rdef = if config.is_root() || !self.rdef.is_empty() {
|
||||||
ResourceDef::new(&insert_slash(&self.rdef))
|
ResourceDef::new(insert_slash(self.rdef.clone()))
|
||||||
} else {
|
} else {
|
||||||
ResourceDef::new(&self.rdef)
|
ResourceDef::new(self.rdef.clone())
|
||||||
};
|
};
|
||||||
if let Some(ref name) = self.name {
|
if let Some(ref name) = self.name {
|
||||||
*rdef.name_mut() = name.clone();
|
*rdef.name_mut() = name.clone();
|
||||||
@ -663,6 +661,23 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_pattern() {
|
||||||
|
let mut srv = init_service(
|
||||||
|
App::new().service(
|
||||||
|
web::resource(["/test", "/test2"])
|
||||||
|
.to(|| async { Ok::<_, Error>(HttpResponse::Ok()) }),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let req = TestRequest::with_uri("/test").to_request();
|
||||||
|
let resp = call_service(&mut srv, req).await;
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
let req = TestRequest::with_uri("/test2").to_request();
|
||||||
|
let resp = call_service(&mut srv, req).await;
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_default_resource() {
|
async fn test_default_resource() {
|
||||||
let mut srv = init_service(
|
let mut srv = init_service(
|
||||||
@ -754,19 +769,19 @@ mod tests {
|
|||||||
App::new()
|
App::new()
|
||||||
.data(1.0f64)
|
.data(1.0f64)
|
||||||
.data(1usize)
|
.data(1usize)
|
||||||
.register_data(web::Data::new('-'))
|
.app_data(web::Data::new('-'))
|
||||||
.service(
|
.service(
|
||||||
web::resource("/test")
|
web::resource("/test")
|
||||||
.data(10usize)
|
.data(10usize)
|
||||||
.register_data(web::Data::new('*'))
|
.app_data(web::Data::new('*'))
|
||||||
.guard(guard::Get())
|
.guard(guard::Get())
|
||||||
.to(
|
.to(
|
||||||
|data1: web::Data<usize>,
|
|data1: web::Data<usize>,
|
||||||
data2: web::Data<char>,
|
data2: web::Data<char>,
|
||||||
data3: web::Data<f64>| {
|
data3: web::Data<f64>| {
|
||||||
assert_eq!(*data1, 10);
|
assert_eq!(**data1, 10);
|
||||||
assert_eq!(*data2, '*');
|
assert_eq!(**data2, '*');
|
||||||
assert_eq!(*data3, 1.0);
|
assert_eq!(**data3, 1.0);
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
34
src/scope.rs
34
src/scope.rs
@ -148,15 +148,13 @@ where
|
|||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn data<U: 'static>(self, data: U) -> Self {
|
pub fn data<U: 'static>(self, data: U) -> Self {
|
||||||
self.register_data(Data::new(data))
|
self.app_data(Data::new(data))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set or override application data.
|
/// Set or override application data.
|
||||||
///
|
///
|
||||||
/// This method has the same effect as [`Scope::data`](#method.data), except
|
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
|
||||||
/// that instead of taking a value of some type `T`, it expects a value of
|
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
|
||||||
/// type `Data<T>`. Use a `Data<T>` extractor to retrieve its value.
|
|
||||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
|
||||||
if self.data.is_none() {
|
if self.data.is_none() {
|
||||||
self.data = Some(Extensions::new());
|
self.data = Some(Extensions::new());
|
||||||
}
|
}
|
||||||
@ -1108,7 +1106,7 @@ mod tests {
|
|||||||
web::scope("app").data(10usize).route(
|
web::scope("app").data(10usize).route(
|
||||||
"/t",
|
"/t",
|
||||||
web::get().to(|data: web::Data<usize>| {
|
web::get().to(|data: web::Data<usize>| {
|
||||||
assert_eq!(*data, 10);
|
assert_eq!(**data, 10);
|
||||||
let _ = data.clone();
|
let _ = data.clone();
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
}),
|
}),
|
||||||
@ -1122,21 +1120,17 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_override_register_data() {
|
async fn test_override_app_data() {
|
||||||
let mut srv = init_service(
|
let mut srv = init_service(App::new().app_data(web::Data::new(1usize)).service(
|
||||||
App::new().register_data(web::Data::new(1usize)).service(
|
web::scope("app").app_data(web::Data::new(10usize)).route(
|
||||||
web::scope("app")
|
"/t",
|
||||||
.register_data(web::Data::new(10usize))
|
web::get().to(|data: web::Data<usize>| {
|
||||||
.route(
|
assert_eq!(**data, 10);
|
||||||
"/t",
|
let _ = data.clone();
|
||||||
web::get().to(|data: web::Data<usize>| {
|
HttpResponse::Ok()
|
||||||
assert_eq!(*data, 10);
|
}),
|
||||||
let _ = data.clone();
|
|
||||||
HttpResponse::Ok()
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
)
|
))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/app/t").to_request();
|
let req = TestRequest::with_uri("/app/t").to_request();
|
||||||
|
103
src/server.rs
103
src/server.rs
@ -2,26 +2,33 @@ use std::marker::PhantomData;
|
|||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::{fmt, io, net};
|
use std::{fmt, io, net};
|
||||||
|
|
||||||
use actix_http::{
|
use actix_http::{body::MessageBody, Error, HttpService, KeepAlive, Request, Response};
|
||||||
body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response,
|
|
||||||
};
|
|
||||||
use actix_server::{Server, ServerBuilder};
|
use actix_server::{Server, ServerBuilder};
|
||||||
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
|
use actix_service::{map_config, IntoServiceFactory, Service, ServiceFactory};
|
||||||
use futures::future::ok;
|
|
||||||
|
|
||||||
use net2::TcpBuilder;
|
use net2::TcpBuilder;
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
use actix_http::Protocol;
|
||||||
|
#[cfg(unix)]
|
||||||
|
use actix_service::pipeline_factory;
|
||||||
|
#[cfg(unix)]
|
||||||
|
use futures::future::ok;
|
||||||
|
|
||||||
#[cfg(feature = "openssl")]
|
#[cfg(feature = "openssl")]
|
||||||
use actix_tls::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
|
use actix_tls::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
|
||||||
#[cfg(feature = "rustls")]
|
#[cfg(feature = "rustls")]
|
||||||
use actix_tls::rustls::ServerConfig as RustlsServerConfig;
|
use actix_tls::rustls::ServerConfig as RustlsServerConfig;
|
||||||
|
|
||||||
|
use crate::config::AppConfig;
|
||||||
|
|
||||||
struct Socket {
|
struct Socket {
|
||||||
scheme: &'static str,
|
scheme: &'static str,
|
||||||
addr: net::SocketAddr,
|
addr: net::SocketAddr,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Config {
|
struct Config {
|
||||||
|
host: Option<String>,
|
||||||
keep_alive: KeepAlive,
|
keep_alive: KeepAlive,
|
||||||
client_timeout: u64,
|
client_timeout: u64,
|
||||||
client_shutdown: u64,
|
client_shutdown: u64,
|
||||||
@ -31,35 +38,30 @@ struct Config {
|
|||||||
///
|
///
|
||||||
/// Create new http server with application factory.
|
/// Create new http server with application factory.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust,no_run
|
||||||
/// use std::io;
|
|
||||||
/// use actix_web::{web, App, HttpResponse, HttpServer};
|
/// use actix_web::{web, App, HttpResponse, HttpServer};
|
||||||
///
|
///
|
||||||
/// fn main() -> io::Result<()> {
|
/// #[actix_rt::main]
|
||||||
/// let sys = actix_rt::System::new("example"); // <- create Actix runtime
|
/// async fn main() -> std::io::Result<()> {
|
||||||
///
|
|
||||||
/// HttpServer::new(
|
/// HttpServer::new(
|
||||||
/// || App::new()
|
/// || App::new()
|
||||||
/// .service(web::resource("/").to(|| HttpResponse::Ok())))
|
/// .service(web::resource("/").to(|| HttpResponse::Ok())))
|
||||||
/// .bind("127.0.0.1:59090")?
|
/// .bind("127.0.0.1:59090")?
|
||||||
/// .start();
|
/// .run()
|
||||||
///
|
/// .await
|
||||||
/// # actix_rt::System::current().stop();
|
|
||||||
/// sys.run()
|
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub struct HttpServer<F, I, S, B>
|
pub struct HttpServer<F, I, S, B>
|
||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoServiceFactory<S>,
|
I: IntoServiceFactory<S>,
|
||||||
S: ServiceFactory<Config = (), Request = Request>,
|
S: ServiceFactory<Config = AppConfig, 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,
|
||||||
{
|
{
|
||||||
pub(super) factory: F,
|
pub(super) factory: F,
|
||||||
pub(super) host: Option<String>,
|
|
||||||
config: Arc<Mutex<Config>>,
|
config: Arc<Mutex<Config>>,
|
||||||
backlog: i32,
|
backlog: i32,
|
||||||
sockets: Vec<Socket>,
|
sockets: Vec<Socket>,
|
||||||
@ -71,7 +73,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
|
|||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoServiceFactory<S>,
|
I: IntoServiceFactory<S>,
|
||||||
S: ServiceFactory<Config = (), Request = Request>,
|
S: ServiceFactory<Config = AppConfig, Request = Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
@ -82,8 +84,8 @@ where
|
|||||||
pub fn new(factory: F) -> Self {
|
pub fn new(factory: F) -> Self {
|
||||||
HttpServer {
|
HttpServer {
|
||||||
factory,
|
factory,
|
||||||
host: None,
|
|
||||||
config: Arc::new(Mutex::new(Config {
|
config: Arc::new(Mutex::new(Config {
|
||||||
|
host: None,
|
||||||
keep_alive: KeepAlive::Timeout(5),
|
keep_alive: KeepAlive::Timeout(5),
|
||||||
client_timeout: 5000,
|
client_timeout: 5000,
|
||||||
client_shutdown: 5000,
|
client_shutdown: 5000,
|
||||||
@ -184,8 +186,8 @@ where
|
|||||||
/// documentation for more information.
|
/// documentation for more information.
|
||||||
///
|
///
|
||||||
/// By default host name is set to a "localhost" value.
|
/// By default host name is set to a "localhost" value.
|
||||||
pub fn server_hostname<T: AsRef<str>>(mut self, val: T) -> Self {
|
pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
|
||||||
self.host = Some(val.as_ref().to_owned());
|
self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -246,11 +248,17 @@ where
|
|||||||
lst,
|
lst,
|
||||||
move || {
|
move || {
|
||||||
let c = cfg.lock().unwrap();
|
let c = cfg.lock().unwrap();
|
||||||
|
let cfg = AppConfig::new(
|
||||||
|
false,
|
||||||
|
addr,
|
||||||
|
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
|
||||||
|
);
|
||||||
|
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.keep_alive(c.keep_alive)
|
.keep_alive(c.keep_alive)
|
||||||
.client_timeout(c.client_timeout)
|
.client_timeout(c.client_timeout)
|
||||||
.local_addr(addr)
|
.local_addr(addr)
|
||||||
.finish(factory())
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
||||||
.tcp()
|
.tcp()
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
@ -288,11 +296,16 @@ where
|
|||||||
lst,
|
lst,
|
||||||
move || {
|
move || {
|
||||||
let c = cfg.lock().unwrap();
|
let c = cfg.lock().unwrap();
|
||||||
|
let cfg = AppConfig::new(
|
||||||
|
true,
|
||||||
|
addr,
|
||||||
|
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
|
||||||
|
);
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.keep_alive(c.keep_alive)
|
.keep_alive(c.keep_alive)
|
||||||
.client_timeout(c.client_timeout)
|
.client_timeout(c.client_timeout)
|
||||||
.client_disconnect(c.client_shutdown)
|
.client_disconnect(c.client_shutdown)
|
||||||
.finish(factory())
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
||||||
.openssl(acceptor.clone())
|
.openssl(acceptor.clone())
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
@ -330,11 +343,16 @@ where
|
|||||||
lst,
|
lst,
|
||||||
move || {
|
move || {
|
||||||
let c = cfg.lock().unwrap();
|
let c = cfg.lock().unwrap();
|
||||||
|
let cfg = AppConfig::new(
|
||||||
|
true,
|
||||||
|
addr,
|
||||||
|
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
|
||||||
|
);
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.keep_alive(c.keep_alive)
|
.keep_alive(c.keep_alive)
|
||||||
.client_timeout(c.client_timeout)
|
.client_timeout(c.client_timeout)
|
||||||
.client_disconnect(c.client_shutdown)
|
.client_disconnect(c.client_shutdown)
|
||||||
.finish(factory())
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
||||||
.rustls(config.clone())
|
.rustls(config.clone())
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
@ -435,24 +453,29 @@ where
|
|||||||
|
|
||||||
let cfg = self.config.clone();
|
let cfg = self.config.clone();
|
||||||
let factory = self.factory.clone();
|
let factory = self.factory.clone();
|
||||||
// todo duplicated:
|
let socket_addr = net::SocketAddr::new(
|
||||||
|
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
||||||
|
8080,
|
||||||
|
);
|
||||||
self.sockets.push(Socket {
|
self.sockets.push(Socket {
|
||||||
scheme: "http",
|
scheme: "http",
|
||||||
addr: net::SocketAddr::new(
|
addr: socket_addr,
|
||||||
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
|
||||||
8080,
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let addr = format!("actix-web-service-{:?}", lst.local_addr()?);
|
let addr = format!("actix-web-service-{:?}", lst.local_addr()?);
|
||||||
|
|
||||||
self.builder = self.builder.listen_uds(addr, lst, move || {
|
self.builder = self.builder.listen_uds(addr, lst, move || {
|
||||||
let c = cfg.lock().unwrap();
|
let c = cfg.lock().unwrap();
|
||||||
|
let config = AppConfig::new(
|
||||||
|
false,
|
||||||
|
socket_addr,
|
||||||
|
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
|
||||||
|
);
|
||||||
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None))).and_then(
|
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None))).and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.keep_alive(c.keep_alive)
|
.keep_alive(c.keep_alive)
|
||||||
.client_timeout(c.client_timeout)
|
.client_timeout(c.client_timeout)
|
||||||
.finish(factory()),
|
.finish(map_config(factory(), move |_| config.clone())),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
Ok(self)
|
Ok(self)
|
||||||
@ -470,12 +493,13 @@ where
|
|||||||
|
|
||||||
let cfg = self.config.clone();
|
let cfg = self.config.clone();
|
||||||
let factory = self.factory.clone();
|
let factory = self.factory.clone();
|
||||||
|
let socket_addr = net::SocketAddr::new(
|
||||||
|
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
||||||
|
8080,
|
||||||
|
);
|
||||||
self.sockets.push(Socket {
|
self.sockets.push(Socket {
|
||||||
scheme: "http",
|
scheme: "http",
|
||||||
addr: net::SocketAddr::new(
|
addr: socket_addr,
|
||||||
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
|
||||||
8080,
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
self.builder = self.builder.bind_uds(
|
self.builder = self.builder.bind_uds(
|
||||||
@ -483,12 +507,17 @@ where
|
|||||||
addr,
|
addr,
|
||||||
move || {
|
move || {
|
||||||
let c = cfg.lock().unwrap();
|
let c = cfg.lock().unwrap();
|
||||||
|
let config = AppConfig::new(
|
||||||
|
false,
|
||||||
|
socket_addr,
|
||||||
|
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
|
||||||
|
);
|
||||||
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None)))
|
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None)))
|
||||||
.and_then(
|
.and_then(
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.keep_alive(c.keep_alive)
|
.keep_alive(c.keep_alive)
|
||||||
.client_timeout(c.client_timeout)
|
.client_timeout(c.client_timeout)
|
||||||
.finish(factory()),
|
.finish(map_config(factory(), move |_| config.clone())),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
@ -500,7 +529,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
|
|||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoServiceFactory<S>,
|
I: IntoServiceFactory<S>,
|
||||||
S: ServiceFactory<Config = (), Request = Request>,
|
S: ServiceFactory<Config = AppConfig, 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>>,
|
||||||
@ -524,11 +553,11 @@ where
|
|||||||
/// async fn main() -> io::Result<()> {
|
/// async fn main() -> io::Result<()> {
|
||||||
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
|
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
|
||||||
/// .bind("127.0.0.1:0")?
|
/// .bind("127.0.0.1:0")?
|
||||||
/// .start()
|
/// .run()
|
||||||
/// .await
|
/// .await
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn start(self) -> Server {
|
pub fn run(self) -> Server {
|
||||||
self.builder.start()
|
self.builder.start()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ use actix_http::{
|
|||||||
Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response,
|
Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response,
|
||||||
ResponseHead,
|
ResponseHead,
|
||||||
};
|
};
|
||||||
use actix_router::{Path, Resource, ResourceDef, Url};
|
use actix_router::{IntoPattern, Path, Resource, ResourceDef, Url};
|
||||||
use actix_service::{IntoServiceFactory, ServiceFactory};
|
use actix_service::{IntoServiceFactory, ServiceFactory};
|
||||||
|
|
||||||
use crate::config::{AppConfig, AppService};
|
use crate::config::{AppConfig, AppService};
|
||||||
@ -422,16 +422,16 @@ impl<B: MessageBody> fmt::Debug for ServiceResponse<B> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct WebService {
|
pub struct WebService {
|
||||||
rdef: String,
|
rdef: Vec<String>,
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
guards: Vec<Box<dyn Guard>>,
|
guards: Vec<Box<dyn Guard>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WebService {
|
impl WebService {
|
||||||
/// Create new `WebService` instance.
|
/// Create new `WebService` instance.
|
||||||
pub fn new(path: &str) -> Self {
|
pub fn new<T: IntoPattern>(path: T) -> Self {
|
||||||
WebService {
|
WebService {
|
||||||
rdef: path.to_string(),
|
rdef: path.patterns(),
|
||||||
name: None,
|
name: None,
|
||||||
guards: Vec::new(),
|
guards: Vec::new(),
|
||||||
}
|
}
|
||||||
@ -491,7 +491,7 @@ impl WebService {
|
|||||||
|
|
||||||
struct WebServiceImpl<T> {
|
struct WebServiceImpl<T> {
|
||||||
srv: T,
|
srv: T,
|
||||||
rdef: String,
|
rdef: Vec<String>,
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
guards: Vec<Box<dyn Guard>>,
|
guards: Vec<Box<dyn Guard>>,
|
||||||
}
|
}
|
||||||
@ -514,9 +514,9 @@ where
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mut rdef = if config.is_root() || !self.rdef.is_empty() {
|
let mut rdef = if config.is_root() || !self.rdef.is_empty() {
|
||||||
ResourceDef::new(&insert_slash(&self.rdef))
|
ResourceDef::new(insert_slash(self.rdef))
|
||||||
} else {
|
} else {
|
||||||
ResourceDef::new(&self.rdef)
|
ResourceDef::new(self.rdef)
|
||||||
};
|
};
|
||||||
if let Some(ref name) = self.name {
|
if let Some(ref name) = self.name {
|
||||||
*rdef.name_mut() = name.clone();
|
*rdef.name_mut() = name.clone();
|
||||||
|
222
src/test.rs
222
src/test.rs
@ -1,5 +1,6 @@
|
|||||||
//! Various helpers for Actix applications to use during testing.
|
//! Various helpers for Actix applications to use during testing.
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
use std::net::SocketAddr;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
use std::{fmt, net, thread, time};
|
use std::{fmt, net, thread, time};
|
||||||
@ -10,9 +11,10 @@ use actix_http::http::{Error as HttpError, Method, StatusCode, Uri, Version};
|
|||||||
use actix_http::test::TestRequest as HttpTestRequest;
|
use actix_http::test::TestRequest as HttpTestRequest;
|
||||||
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
|
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
|
||||||
use actix_router::{Path, ResourceDef, Url};
|
use actix_router::{Path, ResourceDef, Url};
|
||||||
use actix_rt::System;
|
use actix_rt::{time::delay_for, System};
|
||||||
use actix_server::Server;
|
use actix_service::{
|
||||||
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
map_config, IntoService, IntoServiceFactory, Service, ServiceFactory,
|
||||||
|
};
|
||||||
use awc::error::PayloadError;
|
use awc::error::PayloadError;
|
||||||
use awc::{Client, ClientRequest, ClientResponse, Connector};
|
use awc::{Client, ClientRequest, ClientResponse, Connector};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
@ -25,9 +27,9 @@ use serde_json;
|
|||||||
|
|
||||||
pub use actix_http::test::TestBuffer;
|
pub use actix_http::test::TestBuffer;
|
||||||
|
|
||||||
use crate::config::{AppConfig, AppConfigInner};
|
use crate::config::AppConfig;
|
||||||
use crate::data::Data;
|
use crate::data::Data;
|
||||||
use crate::dev::{Body, MessageBody, Payload};
|
use crate::dev::{Body, MessageBody, Payload, Server};
|
||||||
use crate::request::HttpRequestPool;
|
use crate::request::HttpRequestPool;
|
||||||
use crate::rmap::ResourceMap;
|
use crate::rmap::ResourceMap;
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
use crate::service::{ServiceRequest, ServiceResponse};
|
||||||
@ -63,7 +65,7 @@ pub fn default_service(
|
|||||||
/// let mut app = test::init_service(
|
/// let mut app = test::init_service(
|
||||||
/// App::new()
|
/// App::new()
|
||||||
/// .service(web::resource("/test").to(|| async { HttpResponse::Ok() }))
|
/// .service(web::resource("/test").to(|| async { HttpResponse::Ok() }))
|
||||||
/// );
|
/// ).await;
|
||||||
///
|
///
|
||||||
/// // Create request object
|
/// // Create request object
|
||||||
/// let req = test::TestRequest::with_uri("/test").to_request();
|
/// let req = test::TestRequest::with_uri("/test").to_request();
|
||||||
@ -79,7 +81,7 @@ pub async fn init_service<R, S, B, E>(
|
|||||||
where
|
where
|
||||||
R: IntoServiceFactory<S>,
|
R: IntoServiceFactory<S>,
|
||||||
S: ServiceFactory<
|
S: ServiceFactory<
|
||||||
Config = (),
|
Config = AppConfig,
|
||||||
Request = Request,
|
Request = Request,
|
||||||
Response = ServiceResponse<B>,
|
Response = ServiceResponse<B>,
|
||||||
Error = E,
|
Error = E,
|
||||||
@ -87,7 +89,7 @@ where
|
|||||||
S::InitError: std::fmt::Debug,
|
S::InitError: std::fmt::Debug,
|
||||||
{
|
{
|
||||||
let srv = app.into_factory();
|
let srv = app.into_factory();
|
||||||
srv.new_service(()).await.unwrap()
|
srv.new_service(AppConfig::default()).await.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls service and waits for response future completion.
|
/// Calls service and waits for response future completion.
|
||||||
@ -296,8 +298,9 @@ where
|
|||||||
pub struct TestRequest {
|
pub struct TestRequest {
|
||||||
req: HttpTestRequest,
|
req: HttpTestRequest,
|
||||||
rmap: ResourceMap,
|
rmap: ResourceMap,
|
||||||
config: AppConfigInner,
|
config: AppConfig,
|
||||||
path: Path<Url>,
|
path: Path<Url>,
|
||||||
|
peer_addr: Option<SocketAddr>,
|
||||||
app_data: Extensions,
|
app_data: Extensions,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -306,8 +309,9 @@ impl Default for TestRequest {
|
|||||||
TestRequest {
|
TestRequest {
|
||||||
req: HttpTestRequest::default(),
|
req: HttpTestRequest::default(),
|
||||||
rmap: ResourceMap::new(ResourceDef::new("")),
|
rmap: ResourceMap::new(ResourceDef::new("")),
|
||||||
config: AppConfigInner::default(),
|
config: AppConfig::default(),
|
||||||
path: Path::new(Url::new(Uri::default())),
|
path: Path::new(Url::new(Uri::default())),
|
||||||
|
peer_addr: None,
|
||||||
app_data: Extensions::new(),
|
app_data: Extensions::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -407,6 +411,12 @@ impl TestRequest {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set peer addr
|
||||||
|
pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
|
||||||
|
self.peer_addr = Some(addr);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Set request payload
|
/// Set request payload
|
||||||
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
|
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
|
||||||
self.req.set_payload(data);
|
self.req.set_payload(data);
|
||||||
@ -440,6 +450,13 @@ impl TestRequest {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set application data. This is equivalent of `App::app_data()` method
|
||||||
|
/// for testing purpose.
|
||||||
|
pub fn app_data<T: 'static>(mut self, data: T) -> Self {
|
||||||
|
self.app_data.insert(data);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
/// Set request config
|
/// Set request config
|
||||||
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
|
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
|
||||||
@ -449,12 +466,15 @@ impl TestRequest {
|
|||||||
|
|
||||||
/// Complete request creation and generate `Request` instance
|
/// Complete request creation and generate `Request` instance
|
||||||
pub fn to_request(mut self) -> Request {
|
pub fn to_request(mut self) -> Request {
|
||||||
self.req.finish()
|
let mut req = self.req.finish();
|
||||||
|
req.head_mut().peer_addr = self.peer_addr;
|
||||||
|
req
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Complete request creation and generate `ServiceRequest` instance
|
/// Complete request creation and generate `ServiceRequest` instance
|
||||||
pub fn to_srv_request(mut self) -> ServiceRequest {
|
pub fn to_srv_request(mut self) -> ServiceRequest {
|
||||||
let (head, payload) = self.req.finish().into_parts();
|
let (mut head, payload) = self.req.finish().into_parts();
|
||||||
|
head.peer_addr = self.peer_addr;
|
||||||
self.path.get_mut().update(&head.uri);
|
self.path.get_mut().update(&head.uri);
|
||||||
|
|
||||||
ServiceRequest::new(HttpRequest::new(
|
ServiceRequest::new(HttpRequest::new(
|
||||||
@ -462,7 +482,7 @@ impl TestRequest {
|
|||||||
head,
|
head,
|
||||||
payload,
|
payload,
|
||||||
Rc::new(self.rmap),
|
Rc::new(self.rmap),
|
||||||
AppConfig::new(self.config),
|
self.config.clone(),
|
||||||
Rc::new(self.app_data),
|
Rc::new(self.app_data),
|
||||||
HttpRequestPool::create(),
|
HttpRequestPool::create(),
|
||||||
))
|
))
|
||||||
@ -475,7 +495,8 @@ impl TestRequest {
|
|||||||
|
|
||||||
/// Complete request creation and generate `HttpRequest` instance
|
/// Complete request creation and generate `HttpRequest` instance
|
||||||
pub fn to_http_request(mut self) -> HttpRequest {
|
pub fn to_http_request(mut self) -> HttpRequest {
|
||||||
let (head, payload) = self.req.finish().into_parts();
|
let (mut head, payload) = self.req.finish().into_parts();
|
||||||
|
head.peer_addr = self.peer_addr;
|
||||||
self.path.get_mut().update(&head.uri);
|
self.path.get_mut().update(&head.uri);
|
||||||
|
|
||||||
HttpRequest::new(
|
HttpRequest::new(
|
||||||
@ -483,7 +504,7 @@ impl TestRequest {
|
|||||||
head,
|
head,
|
||||||
payload,
|
payload,
|
||||||
Rc::new(self.rmap),
|
Rc::new(self.rmap),
|
||||||
AppConfig::new(self.config),
|
self.config.clone(),
|
||||||
Rc::new(self.app_data),
|
Rc::new(self.app_data),
|
||||||
HttpRequestPool::create(),
|
HttpRequestPool::create(),
|
||||||
)
|
)
|
||||||
@ -491,7 +512,8 @@ impl TestRequest {
|
|||||||
|
|
||||||
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
||||||
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
||||||
let (head, payload) = self.req.finish().into_parts();
|
let (mut head, payload) = self.req.finish().into_parts();
|
||||||
|
head.peer_addr = self.peer_addr;
|
||||||
self.path.get_mut().update(&head.uri);
|
self.path.get_mut().update(&head.uri);
|
||||||
|
|
||||||
let req = HttpRequest::new(
|
let req = HttpRequest::new(
|
||||||
@ -499,7 +521,7 @@ impl TestRequest {
|
|||||||
head,
|
head,
|
||||||
Payload::None,
|
Payload::None,
|
||||||
Rc::new(self.rmap),
|
Rc::new(self.rmap),
|
||||||
AppConfig::new(self.config),
|
self.config.clone(),
|
||||||
Rc::new(self.app_data),
|
Rc::new(self.app_data),
|
||||||
HttpRequestPool::create(),
|
HttpRequestPool::create(),
|
||||||
);
|
);
|
||||||
@ -538,7 +560,7 @@ pub fn start<F, I, S, B>(factory: F) -> TestServer
|
|||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoServiceFactory<S>,
|
I: IntoServiceFactory<S>,
|
||||||
S: ServiceFactory<Config = (), Request = Request> + 'static,
|
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<HttpResponse<B>> + 'static,
|
S::Response: Into<HttpResponse<B>> + 'static,
|
||||||
@ -577,7 +599,7 @@ pub fn start_with<F, I, S, B>(cfg: TestServerConfig, factory: F) -> TestServer
|
|||||||
where
|
where
|
||||||
F: Fn() -> I + Send + Clone + 'static,
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
I: IntoServiceFactory<S>,
|
I: IntoServiceFactory<S>,
|
||||||
S: ServiceFactory<Config = (), Request = Request> + 'static,
|
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
S::Response: Into<HttpResponse<B>> + 'static,
|
S::Response: Into<HttpResponse<B>> + 'static,
|
||||||
@ -604,66 +626,84 @@ where
|
|||||||
let ctimeout = cfg.client_timeout;
|
let ctimeout = cfg.client_timeout;
|
||||||
let builder = Server::build().workers(1).disable_signals();
|
let builder = Server::build().workers(1).disable_signals();
|
||||||
|
|
||||||
match cfg.stream {
|
let srv = match cfg.stream {
|
||||||
StreamType::Tcp => match cfg.tp {
|
StreamType::Tcp => match cfg.tp {
|
||||||
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(false, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.h1(factory())
|
.h1(map_config(factory(), move |_| cfg.clone()))
|
||||||
.tcp()
|
.tcp()
|
||||||
}),
|
}),
|
||||||
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(false, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.h2(factory())
|
.h2(map_config(factory(), move |_| cfg.clone()))
|
||||||
.tcp()
|
.tcp()
|
||||||
}),
|
}),
|
||||||
HttpVer::Both => builder.listen("test", tcp, move || {
|
HttpVer::Both => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(false, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.finish(factory())
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
||||||
.tcp()
|
.tcp()
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
#[cfg(feature = "openssl")]
|
#[cfg(feature = "openssl")]
|
||||||
StreamType::Openssl(acceptor) => match cfg.tp {
|
StreamType::Openssl(acceptor) => match cfg.tp {
|
||||||
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.h1(factory())
|
.h1(map_config(factory(), move |_| cfg.clone()))
|
||||||
.openssl(acceptor.clone())
|
.openssl(acceptor.clone())
|
||||||
}),
|
}),
|
||||||
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.h2(factory())
|
.h2(map_config(factory(), move |_| cfg.clone()))
|
||||||
.openssl(acceptor.clone())
|
.openssl(acceptor.clone())
|
||||||
}),
|
}),
|
||||||
HttpVer::Both => builder.listen("test", tcp, move || {
|
HttpVer::Both => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.finish(factory())
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
||||||
.openssl(acceptor.clone())
|
.openssl(acceptor.clone())
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
#[cfg(feature = "rustls")]
|
#[cfg(feature = "rustls")]
|
||||||
StreamType::Rustls(config) => match cfg.tp {
|
StreamType::Rustls(config) => match cfg.tp {
|
||||||
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.h1(factory())
|
.h1(map_config(factory(), move |_| cfg.clone()))
|
||||||
.rustls(config.clone())
|
.rustls(config.clone())
|
||||||
}),
|
}),
|
||||||
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.h2(factory())
|
.h2(map_config(factory(), move |_| cfg.clone()))
|
||||||
.rustls(config.clone())
|
.rustls(config.clone())
|
||||||
}),
|
}),
|
||||||
HttpVer::Both => builder.listen("test", tcp, move || {
|
HttpVer::Both => builder.listen("test", tcp, move || {
|
||||||
|
let cfg =
|
||||||
|
AppConfig::new(true, local_addr, format!("{}", local_addr));
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(ctimeout)
|
.client_timeout(ctimeout)
|
||||||
.finish(factory())
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
||||||
.rustls(config.clone())
|
.rustls(config.clone())
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
@ -671,11 +711,11 @@ where
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.start();
|
.start();
|
||||||
|
|
||||||
tx.send((System::current(), local_addr)).unwrap();
|
tx.send((System::current(), srv, local_addr)).unwrap();
|
||||||
sys.run()
|
sys.run()
|
||||||
});
|
});
|
||||||
|
|
||||||
let (system, addr) = rx.recv().unwrap();
|
let (system, server, addr) = rx.recv().unwrap();
|
||||||
|
|
||||||
let client = {
|
let client = {
|
||||||
let connector = {
|
let connector = {
|
||||||
@ -711,6 +751,7 @@ where
|
|||||||
addr,
|
addr,
|
||||||
client,
|
client,
|
||||||
system,
|
system,
|
||||||
|
server,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -807,6 +848,7 @@ pub struct TestServer {
|
|||||||
client: awc::Client,
|
client: awc::Client,
|
||||||
system: actix_rt::System,
|
system: actix_rt::System,
|
||||||
ssl: bool,
|
ssl: bool,
|
||||||
|
server: Server,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TestServer {
|
impl TestServer {
|
||||||
@ -895,26 +937,29 @@ impl TestServer {
|
|||||||
self.ws_at("/").await
|
self.ws_at("/").await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stop http server
|
/// Gracefully stop http server
|
||||||
fn stop(&mut self) {
|
pub async fn stop(self) {
|
||||||
|
self.server.stop(true).await;
|
||||||
self.system.stop();
|
self.system.stop();
|
||||||
|
delay_for(time::Duration::from_millis(100)).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for TestServer {
|
impl Drop for TestServer {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.stop()
|
self.system.stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_http::httpmessage::HttpMessage;
|
use actix_http::httpmessage::HttpMessage;
|
||||||
|
use futures::FutureExt;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::{http::header, web, App, HttpResponse};
|
use crate::{http::header, web, App, HttpResponse, Responder};
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_basics() {
|
async fn test_basics() {
|
||||||
@ -923,19 +968,24 @@ mod tests {
|
|||||||
.set(header::Date(SystemTime::now().into()))
|
.set(header::Date(SystemTime::now().into()))
|
||||||
.param("test", "123")
|
.param("test", "123")
|
||||||
.data(10u32)
|
.data(10u32)
|
||||||
|
.app_data(20u64)
|
||||||
|
.peer_addr("127.0.0.1:8081".parse().unwrap())
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
||||||
assert!(req.headers().contains_key(header::DATE));
|
assert!(req.headers().contains_key(header::DATE));
|
||||||
|
assert_eq!(
|
||||||
|
req.head().peer_addr,
|
||||||
|
Some("127.0.0.1:8081".parse().unwrap())
|
||||||
|
);
|
||||||
assert_eq!(&req.match_info()["test"], "123");
|
assert_eq!(&req.match_info()["test"], "123");
|
||||||
assert_eq!(req.version(), Version::HTTP_2);
|
assert_eq!(req.version(), Version::HTTP_2);
|
||||||
let data = req.get_app_data::<u32>().unwrap();
|
let data = req.app_data::<Data<u32>>().unwrap();
|
||||||
assert!(req.get_app_data::<u64>().is_none());
|
assert!(req.app_data::<Data<u64>>().is_none());
|
||||||
assert_eq!(*data, 10);
|
|
||||||
assert_eq!(*data.get_ref(), 10);
|
assert_eq!(*data.get_ref(), 10);
|
||||||
|
|
||||||
assert!(req.app_data::<u64>().is_none());
|
assert!(req.app_data::<u32>().is_none());
|
||||||
let data = req.app_data::<u32>().unwrap();
|
let data = req.app_data::<u64>().unwrap();
|
||||||
assert_eq!(*data, 10);
|
assert_eq!(*data, 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
@ -1095,41 +1145,65 @@ mod tests {
|
|||||||
assert!(res.status().is_success());
|
assert!(res.status().is_success());
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[actix_rt::test]
|
#[actix_rt::test]
|
||||||
// fn test_actor() {
|
async fn test_server_data() {
|
||||||
// use actix::Actor;
|
async fn handler(data: web::Data<usize>) -> impl Responder {
|
||||||
|
assert_eq!(**data, 10);
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
// struct MyActor;
|
let mut app = init_service(
|
||||||
|
App::new()
|
||||||
|
.data(10usize)
|
||||||
|
.service(web::resource("/index.html").to(handler)),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
// struct Num(usize);
|
let req = TestRequest::post().uri("/index.html").to_request();
|
||||||
// impl actix::Message for Num {
|
let res = app.call(req).await.unwrap();
|
||||||
// type Result = usize;
|
assert!(res.status().is_success());
|
||||||
// }
|
}
|
||||||
// impl actix::Actor for MyActor {
|
|
||||||
// type Context = actix::Context<Self>;
|
|
||||||
// }
|
|
||||||
// impl actix::Handler<Num> for MyActor {
|
|
||||||
// type Result = usize;
|
|
||||||
// fn handle(&mut self, msg: Num, _: &mut Self::Context) -> Self::Result {
|
|
||||||
// msg.0
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// let addr = run_on(|| MyActor.start());
|
#[actix_rt::test]
|
||||||
// let mut app = init_service(App::new().service(
|
async fn test_actor() {
|
||||||
// web::resource("/index.html").to(move || {
|
use actix::Actor;
|
||||||
// addr.send(Num(1)).from_err().and_then(|res| {
|
|
||||||
// if res == 1 {
|
|
||||||
// HttpResponse::Ok()
|
|
||||||
// } else {
|
|
||||||
// HttpResponse::BadRequest()
|
|
||||||
// }
|
|
||||||
// })
|
|
||||||
// }),
|
|
||||||
// ));
|
|
||||||
|
|
||||||
// let req = TestRequest::post().uri("/index.html").to_request();
|
struct MyActor;
|
||||||
// let res = block_fn(|| app.call(req)).unwrap();
|
|
||||||
// assert!(res.status().is_success());
|
struct Num(usize);
|
||||||
// }
|
impl actix::Message for Num {
|
||||||
|
type Result = usize;
|
||||||
|
}
|
||||||
|
impl actix::Actor for MyActor {
|
||||||
|
type Context = actix::Context<Self>;
|
||||||
|
}
|
||||||
|
impl actix::Handler<Num> for MyActor {
|
||||||
|
type Result = usize;
|
||||||
|
fn handle(&mut self, msg: Num, _: &mut Self::Context) -> Self::Result {
|
||||||
|
msg.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let addr = MyActor.start();
|
||||||
|
|
||||||
|
let mut app = init_service(App::new().service(web::resource("/index.html").to(
|
||||||
|
move || {
|
||||||
|
addr.send(Num(1)).map(|res| match res {
|
||||||
|
Ok(res) => {
|
||||||
|
if res == 1 {
|
||||||
|
Ok(HttpResponse::Ok())
|
||||||
|
} else {
|
||||||
|
Ok(HttpResponse::BadRequest())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => Err(err),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let req = TestRequest::post().uri("/index.html").to_request();
|
||||||
|
let res = app.call(req).await.unwrap();
|
||||||
|
assert!(res.status().is_success());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,6 +14,7 @@ use futures::StreamExt;
|
|||||||
use serde::de::DeserializeOwned;
|
use serde::de::DeserializeOwned;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
use crate::dev::Decompress;
|
use crate::dev::Decompress;
|
||||||
use crate::error::UrlencodedError;
|
use crate::error::UrlencodedError;
|
||||||
use crate::extract::FromRequest;
|
use crate::extract::FromRequest;
|
||||||
@ -189,7 +190,7 @@ impl<T: Serialize> Responder for Form<T> {
|
|||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/index.html")
|
/// web::resource("/index.html")
|
||||||
/// // change `Form` extractor configuration
|
/// // change `Form` extractor configuration
|
||||||
/// .data(
|
/// .app_data(
|
||||||
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
|
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
|
||||||
/// )
|
/// )
|
||||||
/// .route(web::get().to(index))
|
/// .route(web::get().to(index))
|
||||||
@ -240,7 +241,10 @@ impl Default for FormConfig {
|
|||||||
/// * content-length is greater than 32k
|
/// * content-length is greater than 32k
|
||||||
///
|
///
|
||||||
pub struct UrlEncoded<U> {
|
pub struct UrlEncoded<U> {
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
stream: Option<Decompress<Payload>>,
|
stream: Option<Decompress<Payload>>,
|
||||||
|
#[cfg(not(feature = "compress"))]
|
||||||
|
stream: Option<Payload>,
|
||||||
limit: usize,
|
limit: usize,
|
||||||
length: Option<usize>,
|
length: Option<usize>,
|
||||||
encoding: &'static Encoding,
|
encoding: &'static Encoding,
|
||||||
@ -273,7 +277,11 @@ impl<U> UrlEncoded<U> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
let payload = Decompress::from_headers(payload.take(), req.headers());
|
let payload = Decompress::from_headers(payload.take(), req.headers());
|
||||||
|
#[cfg(not(feature = "compress"))]
|
||||||
|
let payload = payload.take();
|
||||||
|
|
||||||
UrlEncoded {
|
UrlEncoded {
|
||||||
encoding,
|
encoding,
|
||||||
stream: Some(payload),
|
stream: Some(payload),
|
||||||
@ -357,7 +365,7 @@ where
|
|||||||
.map_err(|_| UrlencodedError::Parse)
|
.map_err(|_| UrlencodedError::Parse)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.boxed_local(),
|
.boxed_local(),
|
||||||
);
|
);
|
||||||
self.poll(cx)
|
self.poll(cx)
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@ use serde_json;
|
|||||||
use actix_http::http::{header::CONTENT_LENGTH, StatusCode};
|
use actix_http::http::{header::CONTENT_LENGTH, StatusCode};
|
||||||
use actix_http::{HttpMessage, Payload, Response};
|
use actix_http::{HttpMessage, Payload, Response};
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
use crate::dev::Decompress;
|
use crate::dev::Decompress;
|
||||||
use crate::error::{Error, JsonPayloadError};
|
use crate::error::{Error, JsonPayloadError};
|
||||||
use crate::extract::FromRequest;
|
use crate::extract::FromRequest;
|
||||||
@ -223,17 +224,18 @@ where
|
|||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/index.html").data(
|
/// web::resource("/index.html")
|
||||||
/// // change json extractor configuration
|
/// .app_data(
|
||||||
/// web::Json::<Info>::configure(|cfg| {
|
/// // change json extractor configuration
|
||||||
/// cfg.limit(4096)
|
/// web::Json::<Info>::configure(|cfg| {
|
||||||
/// .content_type(|mime| { // <- accept text/plain content type
|
/// cfg.limit(4096)
|
||||||
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
/// .content_type(|mime| { // <- accept text/plain content type
|
||||||
/// })
|
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||||
/// .error_handler(|err, req| { // <- create custom error response
|
/// })
|
||||||
/// error::InternalError::from_response(
|
/// .error_handler(|err, req| { // <- create custom error response
|
||||||
/// err, HttpResponse::Conflict().finish()).into()
|
/// error::InternalError::from_response(
|
||||||
/// })
|
/// err, HttpResponse::Conflict().finish()).into()
|
||||||
|
/// })
|
||||||
/// }))
|
/// }))
|
||||||
/// .route(web::post().to(index))
|
/// .route(web::post().to(index))
|
||||||
/// );
|
/// );
|
||||||
@ -293,7 +295,10 @@ impl Default for JsonConfig {
|
|||||||
pub struct JsonBody<U> {
|
pub struct JsonBody<U> {
|
||||||
limit: usize,
|
limit: usize,
|
||||||
length: Option<usize>,
|
length: Option<usize>,
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
stream: Option<Decompress<Payload>>,
|
stream: Option<Decompress<Payload>>,
|
||||||
|
#[cfg(not(feature = "compress"))]
|
||||||
|
stream: Option<Payload>,
|
||||||
err: Option<JsonPayloadError>,
|
err: Option<JsonPayloadError>,
|
||||||
fut: Option<LocalBoxFuture<'static, Result<U, JsonPayloadError>>>,
|
fut: Option<LocalBoxFuture<'static, Result<U, JsonPayloadError>>>,
|
||||||
}
|
}
|
||||||
@ -332,7 +337,11 @@ where
|
|||||||
.get(&CONTENT_LENGTH)
|
.get(&CONTENT_LENGTH)
|
||||||
.and_then(|l| l.to_str().ok())
|
.and_then(|l| l.to_str().ok())
|
||||||
.and_then(|s| s.parse::<usize>().ok());
|
.and_then(|s| s.parse::<usize>().ok());
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
let payload = Decompress::from_headers(payload.take(), req.headers());
|
let payload = Decompress::from_headers(payload.take(), req.headers());
|
||||||
|
#[cfg(not(feature = "compress"))]
|
||||||
|
let payload = payload.take();
|
||||||
|
|
||||||
JsonBody {
|
JsonBody {
|
||||||
limit: 262_144,
|
limit: 262_144,
|
||||||
@ -387,7 +396,7 @@ where
|
|||||||
}
|
}
|
||||||
Ok(serde_json::from_slice::<U>(&body)?)
|
Ok(serde_json::from_slice::<U>(&body)?)
|
||||||
}
|
}
|
||||||
.boxed_local(),
|
.boxed_local(),
|
||||||
);
|
);
|
||||||
|
|
||||||
self.poll(cx)
|
self.poll(cx)
|
||||||
@ -454,7 +463,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
||||||
let msg = MyObject {
|
let msg = MyObject {
|
||||||
name: "invalid request".to_string(),
|
name: "invalid request".to_string(),
|
||||||
};
|
};
|
||||||
@ -506,7 +515,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.data(JsonConfig::default().limit(10))
|
.app_data(JsonConfig::default().limit(10))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||||
@ -523,7 +532,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.data(
|
.app_data(
|
||||||
JsonConfig::default()
|
JsonConfig::default()
|
||||||
.limit(10)
|
.limit(10)
|
||||||
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
|
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
|
||||||
@ -596,7 +605,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.data(JsonConfig::default().limit(4096))
|
.app_data(JsonConfig::default().limit(4096))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||||
@ -614,7 +623,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||||
}))
|
}))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
@ -634,7 +643,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||||
}))
|
}))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
@ -15,6 +15,8 @@ use crate::FromRequest;
|
|||||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||||
/// Extract typed information from the request's path.
|
/// Extract typed information from the request's path.
|
||||||
///
|
///
|
||||||
|
/// [**PathConfig**](struct.PathConfig.html) allows to configure extraction process.
|
||||||
|
///
|
||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
@ -212,7 +214,7 @@ where
|
|||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/messages/{folder}")
|
/// web::resource("/messages/{folder}")
|
||||||
/// .data(PathConfig::default().error_handler(|err, req| {
|
/// .app_data(PathConfig::default().error_handler(|err, req| {
|
||||||
/// error::InternalError::from_response(
|
/// error::InternalError::from_response(
|
||||||
/// err,
|
/// err,
|
||||||
/// HttpResponse::Conflict().finish(),
|
/// HttpResponse::Conflict().finish(),
|
||||||
@ -358,7 +360,7 @@ mod tests {
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_custom_err_handler() {
|
async fn test_custom_err_handler() {
|
||||||
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
|
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
|
||||||
.data(PathConfig::default().error_handler(|err, _| {
|
.app_data(PathConfig::default().error_handler(|err, _| {
|
||||||
error::InternalError::from_response(
|
error::InternalError::from_response(
|
||||||
err,
|
err,
|
||||||
HttpResponse::Conflict().finish(),
|
HttpResponse::Conflict().finish(),
|
||||||
|
@ -176,7 +176,7 @@ impl FromRequest for Bytes {
|
|||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/index.html")
|
/// web::resource("/index.html")
|
||||||
/// .data(String::configure(|cfg| { // <- limit size of the payload
|
/// .app_data(String::configure(|cfg| { // <- limit size of the payload
|
||||||
/// cfg.limit(4096)
|
/// cfg.limit(4096)
|
||||||
/// }))
|
/// }))
|
||||||
/// .route(web::get().to(index)) // <- register handler with extractor params
|
/// .route(web::get().to(index)) // <- register handler with extractor params
|
||||||
@ -229,7 +229,7 @@ impl FromRequest for String {
|
|||||||
.ok_or_else(|| ErrorBadRequest("Can not decode body"))?)
|
.ok_or_else(|| ErrorBadRequest("Can not decode body"))?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.boxed_local(),
|
.boxed_local(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -301,7 +301,10 @@ impl Default for PayloadConfig {
|
|||||||
pub struct HttpMessageBody {
|
pub struct HttpMessageBody {
|
||||||
limit: usize,
|
limit: usize,
|
||||||
length: Option<usize>,
|
length: Option<usize>,
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
stream: Option<dev::Decompress<dev::Payload>>,
|
stream: Option<dev::Decompress<dev::Payload>>,
|
||||||
|
#[cfg(not(feature = "compress"))]
|
||||||
|
stream: Option<dev::Payload>,
|
||||||
err: Option<PayloadError>,
|
err: Option<PayloadError>,
|
||||||
fut: Option<LocalBoxFuture<'static, Result<Bytes, PayloadError>>>,
|
fut: Option<LocalBoxFuture<'static, Result<Bytes, PayloadError>>>,
|
||||||
}
|
}
|
||||||
@ -322,8 +325,13 @@ impl HttpMessageBody {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "compress")]
|
||||||
|
let stream = Some(dev::Decompress::from_headers(payload.take(), req.headers()));
|
||||||
|
#[cfg(not(feature = "compress"))]
|
||||||
|
let stream = Some(payload.take());
|
||||||
|
|
||||||
HttpMessageBody {
|
HttpMessageBody {
|
||||||
stream: Some(dev::Decompress::from_headers(payload.take(), req.headers())),
|
stream,
|
||||||
limit: 262_144,
|
limit: 262_144,
|
||||||
length: len,
|
length: len,
|
||||||
fut: None,
|
fut: None,
|
||||||
@ -383,7 +391,7 @@ impl Future for HttpMessageBody {
|
|||||||
}
|
}
|
||||||
Ok(body.freeze())
|
Ok(body.freeze())
|
||||||
}
|
}
|
||||||
.boxed_local(),
|
.boxed_local(),
|
||||||
);
|
);
|
||||||
self.poll(cx)
|
self.poll(cx)
|
||||||
}
|
}
|
||||||
|
@ -19,6 +19,8 @@ use crate::request::HttpRequest;
|
|||||||
/// be decoded into any type which depends upon data ordering e.g. tuples or tuple-structs.
|
/// be decoded into any type which depends upon data ordering e.g. tuples or tuple-structs.
|
||||||
/// Attempts to do so will *fail at runtime*.
|
/// Attempts to do so will *fail at runtime*.
|
||||||
///
|
///
|
||||||
|
/// [**QueryConfig**](struct.QueryConfig.html) allows to configure extraction process.
|
||||||
|
///
|
||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
@ -185,7 +187,7 @@ where
|
|||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/index.html").data(
|
/// web::resource("/index.html").app_data(
|
||||||
/// // change query extractor configuration
|
/// // change query extractor configuration
|
||||||
/// web::Query::<Info>::configure(|cfg| {
|
/// web::Query::<Info>::configure(|cfg| {
|
||||||
/// cfg.error_handler(|err, req| { // <- create custom error response
|
/// cfg.error_handler(|err, req| { // <- create custom error response
|
||||||
@ -273,7 +275,7 @@ mod tests {
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_custom_error_responder() {
|
async fn test_custom_error_responder() {
|
||||||
let req = TestRequest::with_uri("/name/user1/")
|
let req = TestRequest::with_uri("/name/user1/")
|
||||||
.data(QueryConfig::default().error_handler(|e, _| {
|
.app_data(QueryConfig::default().error_handler(|e, _| {
|
||||||
let resp = HttpResponse::UnprocessableEntity().finish();
|
let resp = HttpResponse::UnprocessableEntity().finish();
|
||||||
InternalError::from_response(e, resp).into()
|
InternalError::from_response(e, resp).into()
|
||||||
}))
|
}))
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
//! Essentials helper functions and types for application registration.
|
//! Essentials helper functions and types for application registration.
|
||||||
use actix_http::http::Method;
|
use actix_http::http::Method;
|
||||||
|
use actix_router::IntoPattern;
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
|
|
||||||
pub use actix_http::Response as HttpResponse;
|
pub use actix_http::Response as HttpResponse;
|
||||||
@ -50,7 +51,7 @@ pub use crate::types::*;
|
|||||||
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
|
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
pub fn resource(path: &str) -> Resource {
|
pub fn resource<T: IntoPattern>(path: T) -> Resource {
|
||||||
Resource::new(path)
|
Resource::new(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -249,7 +250,7 @@ where
|
|||||||
/// .finish(my_service)
|
/// .finish(my_service)
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
pub fn service(path: &str) -> WebService {
|
pub fn service<T: IntoPattern>(path: T) -> WebService {
|
||||||
WebService::new(path)
|
WebService::new(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,5 +1,12 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-12-13
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Replaced `TestServer::start()` with `test_server()`
|
||||||
|
|
||||||
|
|
||||||
## [1.0.0-alpha.3] - 2019-12-07
|
## [1.0.0-alpha.3] - 2019-12-07
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@ -30,7 +30,7 @@ default = []
|
|||||||
openssl = ["open-ssl", "awc/openssl"]
|
openssl = ["open-ssl", "awc/openssl"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "1.0.0"
|
actix-service = "1.0.1"
|
||||||
actix-codec = "0.2.0"
|
actix-codec = "0.2.0"
|
||||||
actix-connect = "1.0.0"
|
actix-connect = "1.0.0"
|
||||||
actix-utils = "1.0.3"
|
actix-utils = "1.0.3"
|
||||||
@ -40,7 +40,7 @@ actix-testing = "1.0.0"
|
|||||||
awc = "1.0.0"
|
awc = "1.0.0"
|
||||||
|
|
||||||
base64 = "0.11"
|
base64 = "0.11"
|
||||||
bytes = "0.5.2"
|
bytes = "0.5.3"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
http = "0.2.0"
|
http = "0.2.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
@ -55,5 +55,5 @@ time = "0.1"
|
|||||||
open-ssl = { version="0.10", package="openssl", optional = true }
|
open-ssl = { version="0.10", package="openssl", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = "2.0.0-alpha.4"
|
actix-web = "2.0.0-rc"
|
||||||
actix-http = "1.0.0"
|
actix-http = "1.0.1"
|
||||||
|
@ -5,8 +5,7 @@ use std::{net, thread, time::Duration};
|
|||||||
#[cfg(feature = "openssl")]
|
#[cfg(feature = "openssl")]
|
||||||
use open_ssl::ssl::SslAcceptorBuilder;
|
use open_ssl::ssl::SslAcceptorBuilder;
|
||||||
|
|
||||||
use actix_http::Response;
|
use actix_web::{web, App, HttpResponse, HttpServer};
|
||||||
use actix_web::{web, App, HttpServer};
|
|
||||||
|
|
||||||
fn unused_addr() -> net::SocketAddr {
|
fn unused_addr() -> net::SocketAddr {
|
||||||
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
||||||
@ -28,7 +27,7 @@ async fn test_start() {
|
|||||||
|
|
||||||
let srv = HttpServer::new(|| {
|
let srv = HttpServer::new(|| {
|
||||||
App::new().service(
|
App::new().service(
|
||||||
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
|
web::resource("/").route(web::to(|| HttpResponse::Ok().body("test"))),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.workers(1)
|
.workers(1)
|
||||||
@ -43,7 +42,7 @@ async fn test_start() {
|
|||||||
.disable_signals()
|
.disable_signals()
|
||||||
.bind(format!("{}", addr))
|
.bind(format!("{}", addr))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.start();
|
.run();
|
||||||
|
|
||||||
let _ = tx.send((srv, actix_rt::System::current()));
|
let _ = tx.send((srv, actix_rt::System::current()));
|
||||||
let _ = sys.run();
|
let _ = sys.run();
|
||||||
@ -91,6 +90,8 @@ fn ssl_acceptor() -> std::io::Result<SslAcceptorBuilder> {
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
#[cfg(feature = "openssl")]
|
#[cfg(feature = "openssl")]
|
||||||
async fn test_start_ssl() {
|
async fn test_start_ssl() {
|
||||||
|
use actix_web::HttpRequest;
|
||||||
|
|
||||||
let addr = unused_addr();
|
let addr = unused_addr();
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
@ -99,9 +100,10 @@ async fn test_start_ssl() {
|
|||||||
let builder = ssl_acceptor().unwrap();
|
let builder = ssl_acceptor().unwrap();
|
||||||
|
|
||||||
let srv = HttpServer::new(|| {
|
let srv = HttpServer::new(|| {
|
||||||
App::new().service(
|
App::new().service(web::resource("/").route(web::to(|req: HttpRequest| {
|
||||||
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
|
assert!(req.app_config().secure());
|
||||||
)
|
HttpResponse::Ok().body("test")
|
||||||
|
})))
|
||||||
})
|
})
|
||||||
.workers(1)
|
.workers(1)
|
||||||
.shutdown_timeout(1)
|
.shutdown_timeout(1)
|
||||||
@ -109,7 +111,7 @@ async fn test_start_ssl() {
|
|||||||
.disable_signals()
|
.disable_signals()
|
||||||
.bind_openssl(format!("{}", addr), builder)
|
.bind_openssl(format!("{}", addr), builder)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.start();
|
.run();
|
||||||
|
|
||||||
let _ = tx.send((srv, actix_rt::System::current()));
|
let _ = tx.send((srv, actix_rt::System::current()));
|
||||||
let _ = sys.run();
|
let _ = sys.run();
|
||||||
|
@ -1,19 +1,22 @@
|
|||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_http::http::header::{
|
use actix_http::http::header::{
|
||||||
ContentEncoding, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH,
|
ContentEncoding, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH,
|
||||||
TRANSFER_ENCODING,
|
TRANSFER_ENCODING,
|
||||||
};
|
};
|
||||||
use brotli::{CompressorWriter, DecompressorWriter};
|
use brotli2::write::{BrotliDecoder, BrotliEncoder};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use flate2::read::GzDecoder;
|
use flate2::read::GzDecoder;
|
||||||
use flate2::write::{GzEncoder, ZlibDecoder, ZlibEncoder};
|
use flate2::write::{GzEncoder, ZlibDecoder, ZlibEncoder};
|
||||||
use flate2::Compression;
|
use flate2::Compression;
|
||||||
use futures::{future::ok, stream::once};
|
use futures::{ready, Future};
|
||||||
use rand::{distributions::Alphanumeric, Rng};
|
use rand::{distributions::Alphanumeric, Rng};
|
||||||
|
|
||||||
use actix_web::middleware::{BodyEncoding, Compress};
|
use actix_web::dev::BodyEncoding;
|
||||||
use actix_web::{dev, http, test, web, App, Error, HttpResponse};
|
use actix_web::middleware::Compress;
|
||||||
|
use actix_web::{dev, test, web, App, Error, HttpResponse};
|
||||||
|
|
||||||
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||||
Hello World Hello World Hello World Hello World Hello World \
|
Hello World Hello World Hello World Hello World Hello World \
|
||||||
@ -37,6 +40,42 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
|||||||
Hello World Hello World Hello World Hello World Hello World \
|
Hello World Hello World Hello World Hello World Hello World \
|
||||||
Hello World Hello World Hello World Hello World Hello World";
|
Hello World Hello World Hello World Hello World Hello World";
|
||||||
|
|
||||||
|
struct TestBody {
|
||||||
|
data: Bytes,
|
||||||
|
chunk_size: usize,
|
||||||
|
delay: actix_rt::time::Delay,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestBody {
|
||||||
|
fn new(data: Bytes, chunk_size: usize) -> Self {
|
||||||
|
TestBody {
|
||||||
|
data,
|
||||||
|
chunk_size,
|
||||||
|
delay: actix_rt::time::delay_for(std::time::Duration::from_millis(10)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl futures::Stream for TestBody {
|
||||||
|
type Item = Result<Bytes, Error>;
|
||||||
|
|
||||||
|
fn poll_next(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Self::Item>> {
|
||||||
|
ready!(Pin::new(&mut self.delay).poll(cx));
|
||||||
|
|
||||||
|
self.delay = actix_rt::time::delay_for(std::time::Duration::from_millis(10));
|
||||||
|
let chunk_size = std::cmp::min(self.chunk_size, self.data.len());
|
||||||
|
let chunk = self.data.split_to(chunk_size);
|
||||||
|
if chunk.is_empty() {
|
||||||
|
Poll::Ready(None)
|
||||||
|
} else {
|
||||||
|
Poll::Ready(Some(Ok(chunk)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_body() {
|
async fn test_body() {
|
||||||
let srv = test::start(|| {
|
let srv = test::start(|| {
|
||||||
@ -247,7 +286,7 @@ async fn test_body_chunked_implicit() {
|
|||||||
.wrap(Compress::new(ContentEncoding::Gzip))
|
.wrap(Compress::new(ContentEncoding::Gzip))
|
||||||
.service(web::resource("/").route(web::get().to(move || {
|
.service(web::resource("/").route(web::get().to(move || {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
|
.streaming(TestBody::new(Bytes::from_static(STR.as_ref()), 24))
|
||||||
})))
|
})))
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -280,7 +319,7 @@ async fn test_body_br_streaming() {
|
|||||||
App::new().wrap(Compress::new(ContentEncoding::Br)).service(
|
App::new().wrap(Compress::new(ContentEncoding::Br)).service(
|
||||||
web::resource("/").route(web::to(move || {
|
web::resource("/").route(web::to(move || {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
|
.streaming(TestBody::new(Bytes::from_static(STR.as_ref()), 24))
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@ -296,11 +335,13 @@ async fn test_body_br_streaming() {
|
|||||||
|
|
||||||
// read response
|
// read response
|
||||||
let bytes = response.body().await.unwrap();
|
let bytes = response.body().await.unwrap();
|
||||||
|
println!("TEST: {:?}", bytes.len());
|
||||||
|
|
||||||
// decode br
|
// decode br
|
||||||
let mut e = DecompressorWriter::new(Vec::with_capacity(2048), 0);
|
let mut e = BrotliDecoder::new(Vec::with_capacity(2048));
|
||||||
e.write_all(bytes.as_ref()).unwrap();
|
e.write_all(bytes.as_ref()).unwrap();
|
||||||
let dec = e.into_inner().unwrap();
|
let dec = e.finish().unwrap();
|
||||||
|
println!("T: {:?}", Bytes::copy_from_slice(&dec));
|
||||||
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -332,7 +373,7 @@ async fn test_no_chunking() {
|
|||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.no_chunking()
|
.no_chunking()
|
||||||
.content_length(STR.len() as u64)
|
.content_length(STR.len() as u64)
|
||||||
.streaming(once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))))
|
.streaming(TestBody::new(Bytes::from_static(STR.as_ref()), 24))
|
||||||
})))
|
})))
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -396,9 +437,9 @@ async fn test_body_brotli() {
|
|||||||
let bytes = response.body().await.unwrap();
|
let bytes = response.body().await.unwrap();
|
||||||
|
|
||||||
// decode brotli
|
// decode brotli
|
||||||
let mut e = DecompressorWriter::new(Vec::with_capacity(2048), 0);
|
let mut e = BrotliDecoder::new(Vec::with_capacity(2048));
|
||||||
e.write_all(bytes.as_ref()).unwrap();
|
e.write_all(bytes.as_ref()).unwrap();
|
||||||
let dec = e.into_inner().unwrap();
|
let dec = e.finish().unwrap();
|
||||||
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -607,9 +648,9 @@ async fn test_brotli_encoding() {
|
|||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut e = CompressorWriter::new(Vec::new(), 0, 3, 0);
|
let mut e = BrotliEncoder::new(Vec::new(), 5);
|
||||||
e.write_all(STR.as_ref()).unwrap();
|
e.write_all(STR.as_ref()).unwrap();
|
||||||
let enc = e.into_inner();
|
let enc = e.finish().unwrap();
|
||||||
|
|
||||||
// client request
|
// client request
|
||||||
let request = srv
|
let request = srv
|
||||||
@ -626,17 +667,24 @@ async fn test_brotli_encoding() {
|
|||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_brotli_encoding_large() {
|
async fn test_brotli_encoding_large() {
|
||||||
let data = STR.repeat(10);
|
let data = rand::thread_rng()
|
||||||
|
.sample_iter(&Alphanumeric)
|
||||||
|
.take(320_000)
|
||||||
|
.collect::<String>();
|
||||||
|
|
||||||
let srv = test::start_with(test::config().h1(), || {
|
let srv = test::start_with(test::config().h1(), || {
|
||||||
App::new().service(
|
App::new().service(
|
||||||
web::resource("/")
|
web::resource("/")
|
||||||
.route(web::to(move |body: Bytes| HttpResponse::Ok().body(body))),
|
.app_data(web::PayloadConfig::new(320_000))
|
||||||
|
.route(web::to(move |body: Bytes| {
|
||||||
|
HttpResponse::Ok().streaming(TestBody::new(body, 10240))
|
||||||
|
})),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut e = CompressorWriter::new(Vec::new(), 0, 3, 0);
|
let mut e = BrotliEncoder::new(Vec::new(), 5);
|
||||||
e.write_all(data.as_ref()).unwrap();
|
e.write_all(data.as_ref()).unwrap();
|
||||||
let enc = e.into_inner();
|
let enc = e.finish().unwrap();
|
||||||
|
|
||||||
// client request
|
// client request
|
||||||
let request = srv
|
let request = srv
|
||||||
@ -647,7 +695,7 @@ async fn test_brotli_encoding_large() {
|
|||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
// read response
|
||||||
let bytes = response.body().await.unwrap();
|
let bytes = response.body().limit(320_000).await.unwrap();
|
||||||
assert_eq!(bytes, Bytes::from(data));
|
assert_eq!(bytes, Bytes::from(data));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -668,20 +716,20 @@ async fn test_brotli_encoding_large_openssl() {
|
|||||||
let srv = test::start_with(test::config().openssl(builder.build()), move || {
|
let srv = test::start_with(test::config().openssl(builder.build()), move || {
|
||||||
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| {
|
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.encoding(http::ContentEncoding::Identity)
|
.encoding(actix_web::http::ContentEncoding::Identity)
|
||||||
.body(bytes)
|
.body(bytes)
|
||||||
})))
|
})))
|
||||||
});
|
});
|
||||||
|
|
||||||
// body
|
// body
|
||||||
let mut e = CompressorWriter::new(Vec::new(), 0, 3, 0);
|
let mut e = BrotliEncoder::new(Vec::new(), 3);
|
||||||
e.write_all(data.as_ref()).unwrap();
|
e.write_all(data.as_ref()).unwrap();
|
||||||
let enc = e.into_inner();
|
let enc = e.finish().unwrap();
|
||||||
|
|
||||||
// client request
|
// client request
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(http::header::CONTENT_ENCODING, "br")
|
.header(actix_web::http::header::CONTENT_ENCODING, "br")
|
||||||
.send_body(enc)
|
.send_body(enc)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@ -716,7 +764,7 @@ async fn test_reading_deflate_encoding_large_random_rustls() {
|
|||||||
let srv = test::start_with(test::config().rustls(config), || {
|
let srv = test::start_with(test::config().rustls(config), || {
|
||||||
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| {
|
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.encoding(http::ContentEncoding::Identity)
|
.encoding(actix_web::http::ContentEncoding::Identity)
|
||||||
.body(bytes)
|
.body(bytes)
|
||||||
})))
|
})))
|
||||||
});
|
});
|
||||||
@ -729,8 +777,8 @@ async fn test_reading_deflate_encoding_large_random_rustls() {
|
|||||||
// client request
|
// client request
|
||||||
let req = srv
|
let req = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(http::header::CONTENT_ENCODING, "deflate")
|
.header(actix_web::http::header::CONTENT_ENCODING, "deflate")
|
||||||
.send_body(enc);
|
.send_stream(TestBody::new(Bytes::from(enc), 1024));
|
||||||
|
|
||||||
let mut response = req.await.unwrap();
|
let mut response = req.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
@ -741,93 +789,6 @@ async fn test_reading_deflate_encoding_large_random_rustls() {
|
|||||||
assert_eq!(bytes, Bytes::from(data));
|
assert_eq!(bytes, Bytes::from(data));
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[cfg(all(feature = "tls", feature = "ssl"))]
|
|
||||||
// #[test]
|
|
||||||
// fn test_reading_deflate_encoding_large_random_nativetls() {
|
|
||||||
// use native_tls::{Identity, TlsAcceptor};
|
|
||||||
// use openssl::ssl::{
|
|
||||||
// SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode,
|
|
||||||
// };
|
|
||||||
// use std::fs::File;
|
|
||||||
// use std::sync::mpsc;
|
|
||||||
|
|
||||||
// use actix::{Actor, System};
|
|
||||||
// let (tx, rx) = mpsc::channel();
|
|
||||||
|
|
||||||
// // load ssl keys
|
|
||||||
// let mut file = File::open("tests/identity.pfx").unwrap();
|
|
||||||
// let mut identity = vec![];
|
|
||||||
// file.read_to_end(&mut identity).unwrap();
|
|
||||||
// let identity = Identity::from_pkcs12(&identity, "1").unwrap();
|
|
||||||
// let acceptor = TlsAcceptor::new(identity).unwrap();
|
|
||||||
|
|
||||||
// // load ssl keys
|
|
||||||
// let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
|
||||||
// builder
|
|
||||||
// .set_private_key_file("tests/key.pem", SslFiletype::PEM)
|
|
||||||
// .unwrap();
|
|
||||||
// builder
|
|
||||||
// .set_certificate_chain_file("tests/cert.pem")
|
|
||||||
// .unwrap();
|
|
||||||
|
|
||||||
// let data = rand::thread_rng()
|
|
||||||
// .sample_iter(&Alphanumeric)
|
|
||||||
// .take(160_000)
|
|
||||||
// .collect::<String>();
|
|
||||||
|
|
||||||
// let addr = test::TestServer::unused_addr();
|
|
||||||
// thread::spawn(move || {
|
|
||||||
// System::run(move || {
|
|
||||||
// server::new(|| {
|
|
||||||
// App::new().handler("/", |req: &HttpRequest| {
|
|
||||||
// req.body()
|
|
||||||
// .and_then(|bytes: Bytes| {
|
|
||||||
// Ok(HttpResponse::Ok()
|
|
||||||
// .content_encoding(http::ContentEncoding::Identity)
|
|
||||||
// .body(bytes))
|
|
||||||
// })
|
|
||||||
// .responder()
|
|
||||||
// })
|
|
||||||
// })
|
|
||||||
// .bind_tls(addr, acceptor)
|
|
||||||
// .unwrap()
|
|
||||||
// .start();
|
|
||||||
// let _ = tx.send(System::current());
|
|
||||||
// });
|
|
||||||
// });
|
|
||||||
// let sys = rx.recv().unwrap();
|
|
||||||
|
|
||||||
// let mut rt = System::new("test");
|
|
||||||
|
|
||||||
// // client connector
|
|
||||||
// let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
|
||||||
// builder.set_verify(SslVerifyMode::NONE);
|
|
||||||
// let conn = client::ClientConnector::with_connector(builder.build()).start();
|
|
||||||
|
|
||||||
// // encode data
|
|
||||||
// let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
|
|
||||||
// e.write_all(data.as_ref()).unwrap();
|
|
||||||
// let enc = e.finish().unwrap();
|
|
||||||
|
|
||||||
// // client request
|
|
||||||
// let request = client::ClientRequest::build()
|
|
||||||
// .uri(format!("https://{}/", addr))
|
|
||||||
// .method(http::Method::POST)
|
|
||||||
// .header(http::header::CONTENT_ENCODING, "deflate")
|
|
||||||
// .with_connector(conn)
|
|
||||||
// .body(enc)
|
|
||||||
// .unwrap();
|
|
||||||
// let response = rt.block_on(request.send()).unwrap();
|
|
||||||
// assert!(response.status().is_success());
|
|
||||||
|
|
||||||
// // read response
|
|
||||||
// let bytes = rt.block_on(response.body()).unwrap();
|
|
||||||
// assert_eq!(bytes.len(), data.len());
|
|
||||||
// assert_eq!(bytes, Bytes::from(data));
|
|
||||||
|
|
||||||
// let _ = sys.stop();
|
|
||||||
// }
|
|
||||||
|
|
||||||
// #[test]
|
// #[test]
|
||||||
// fn test_server_cookies() {
|
// fn test_server_cookies() {
|
||||||
// use actix_web::http;
|
// use actix_web::http;
|
||||||
|
Reference in New Issue
Block a user