mirror of
https://github.com/fafhrd91/actix-web
synced 2024-11-27 17:52:56 +01:00
Merge branch 'master' into origin/feature/awc-retry-middleware
This commit is contained in:
commit
58dfc3ba22
@ -1,3 +1,7 @@
|
|||||||
[alias]
|
[alias]
|
||||||
chk = "hack check --workspace --all-features --tests --examples"
|
chk = "hack check --workspace --all-features --tests --examples"
|
||||||
lint = "hack --clean-per-run clippy --workspace --tests --examples"
|
lint = "hack --clean-per-run clippy --workspace --tests --examples"
|
||||||
|
ci-min = "hack check --workspace --no-default-features"
|
||||||
|
ci-min-test = "hack check --workspace --no-default-features --tests --examples"
|
||||||
|
ci-default = "hack check --workspace"
|
||||||
|
ci-full = "check --workspace --bins --examples --tests"
|
||||||
|
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@ -86,7 +86,7 @@ jobs:
|
|||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: test
|
command: test
|
||||||
args: -v --workspace --all-features --no-fail-fast -- --nocapture
|
args: --workspace --all-features --no-fail-fast -- --nocapture
|
||||||
--skip=test_h2_content_length
|
--skip=test_h2_content_length
|
||||||
--skip=test_reading_deflate_encoding_large_random_rustls
|
--skip=test_reading_deflate_encoding_large_random_rustls
|
||||||
|
|
||||||
|
27
CHANGES.md
27
CHANGES.md
@ -1,6 +1,33 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
### Added
|
||||||
|
* `HttpServer::worker_max_blocking_threads` for setting block thread pool. [#2200]
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
* `ServiceResponse::error_response` now uses body type of `Body`. [#2201]
|
||||||
|
* `ServiceResponse::checked_expr` now returns a `Result`. [#2201]
|
||||||
|
* Update `language-tags` to `0.3`.
|
||||||
|
* `ServiceResponse::take_body`. [#2201]
|
||||||
|
* `ServiceResponse::map_body` closure receives and returns `B` instead of `ResponseBody<B>` types. [#2201]
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
* `HttpResponse::take_body` and old `HttpResponse::into_body` method that casted body type. [#2201]
|
||||||
|
|
||||||
|
[#2200]: https://github.com/actix/actix-web/pull/2200
|
||||||
|
[#2201]: https://github.com/actix/actix-web/pull/2201
|
||||||
|
|
||||||
|
|
||||||
|
## 4.0.0-beta.6 - 2021-04-17
|
||||||
|
### Added
|
||||||
|
* `HttpResponse` and `HttpResponseBuilder` structs. [#2065]
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
* Most error types are now marked `#[non_exhaustive]`. [#2148]
|
||||||
|
* Methods on `ContentDisposition` that took `T: AsRef<str>` now take `impl AsRef<str>`.
|
||||||
|
|
||||||
|
[#2065]: https://github.com/actix/actix-web/pull/2065
|
||||||
|
[#2148]: https://github.com/actix/actix-web/pull/2148
|
||||||
|
|
||||||
|
|
||||||
## 4.0.0-beta.5 - 2021-04-02
|
## 4.0.0-beta.5 - 2021-04-02
|
||||||
|
94
Cargo.toml
94
Cargo.toml
@ -1,26 +1,23 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web"
|
name = "actix-web"
|
||||||
version = "4.0.0-beta.5"
|
version = "4.0.0-beta.6"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
|
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
|
||||||
readme = "README.md"
|
|
||||||
keywords = ["actix", "http", "web", "framework", "async"]
|
keywords = ["actix", "http", "web", "framework", "async"]
|
||||||
|
categories = [
|
||||||
|
"network-programming",
|
||||||
|
"asynchronous",
|
||||||
|
"web-programming::http-server",
|
||||||
|
"web-programming::websocket"
|
||||||
|
]
|
||||||
homepage = "https://actix.rs"
|
homepage = "https://actix.rs"
|
||||||
repository = "https://github.com/actix/actix-web.git"
|
repository = "https://github.com/actix/actix-web"
|
||||||
documentation = "https://docs.rs/actix-web/"
|
|
||||||
categories = ["network-programming", "asynchronous",
|
|
||||||
"web-programming::http-server",
|
|
||||||
"web-programming::websocket"]
|
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
# features that docs.rs will build with
|
# features that docs.rs will build with
|
||||||
features = ["openssl", "rustls", "compress", "secure-cookies"]
|
features = ["openssl", "rustls", "compress", "cookies", "secure-cookies"]
|
||||||
|
|
||||||
[badges]
|
|
||||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
|
||||||
codecov = { repository = "actix/actix-web", branch = "master", service = "github" }
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_web"
|
name = "actix_web"
|
||||||
@ -28,16 +25,18 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
".",
|
".",
|
||||||
"awc",
|
"awc",
|
||||||
"actix-http",
|
"actix-http",
|
||||||
"actix-files",
|
"actix-files",
|
||||||
"actix-multipart",
|
"actix-multipart",
|
||||||
"actix-web-actors",
|
"actix-web-actors",
|
||||||
"actix-web-codegen",
|
"actix-web-codegen",
|
||||||
"actix-http-test",
|
"actix-http-test",
|
||||||
"actix-test",
|
"actix-test",
|
||||||
]
|
]
|
||||||
|
# enable when MSRV is 1.51+
|
||||||
|
# resolver = "2"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["compress", "cookies"]
|
default = ["compress", "cookies"]
|
||||||
@ -46,10 +45,10 @@ default = ["compress", "cookies"]
|
|||||||
compress = ["actix-http/compress"]
|
compress = ["actix-http/compress"]
|
||||||
|
|
||||||
# support for cookies
|
# support for cookies
|
||||||
cookies = ["actix-http/cookies"]
|
cookies = ["cookie"]
|
||||||
|
|
||||||
# secure cookies feature
|
# secure cookies feature
|
||||||
secure-cookies = ["actix-http/secure-cookies"]
|
secure-cookies = ["cookie/secure"]
|
||||||
|
|
||||||
# openssl
|
# openssl
|
||||||
openssl = ["actix-http/openssl", "actix-tls/accept", "actix-tls/openssl"]
|
openssl = ["actix-http/openssl", "actix-tls/accept", "actix-tls/openssl"]
|
||||||
@ -57,46 +56,33 @@ openssl = ["actix-http/openssl", "actix-tls/accept", "actix-tls/openssl"]
|
|||||||
# rustls
|
# rustls
|
||||||
rustls = ["actix-http/rustls", "actix-tls/accept", "actix-tls/rustls"]
|
rustls = ["actix-http/rustls", "actix-tls/accept", "actix-tls/rustls"]
|
||||||
|
|
||||||
[[example]]
|
|
||||||
name = "basic"
|
|
||||||
required-features = ["compress"]
|
|
||||||
|
|
||||||
[[example]]
|
|
||||||
name = "uds"
|
|
||||||
required-features = ["compress"]
|
|
||||||
|
|
||||||
[[test]]
|
|
||||||
name = "test_server"
|
|
||||||
required-features = ["compress", "cookies"]
|
|
||||||
|
|
||||||
[[example]]
|
|
||||||
name = "on_connect"
|
|
||||||
required-features = []
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0"
|
||||||
actix-macros = "0.2.0"
|
actix-macros = "0.2.0"
|
||||||
actix-router = "0.2.7"
|
actix-router = "0.2.7"
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-server = "2.0.0-beta.3"
|
actix-server = "2.0.0-beta.3"
|
||||||
actix-service = "2.0.0-beta.4"
|
actix-service = "2.0.0"
|
||||||
actix-utils = "3.0.0-beta.4"
|
actix-utils = "3.0.0"
|
||||||
actix-tls = { version = "3.0.0-beta.5", default-features = false, optional = true }
|
actix-tls = { version = "3.0.0-beta.5", default-features = false, optional = true }
|
||||||
|
|
||||||
actix-web-codegen = "0.5.0-beta.2"
|
actix-web-codegen = "0.5.0-beta.2"
|
||||||
actix-http = "3.0.0-beta.5"
|
actix-http = "3.0.0-beta.6"
|
||||||
|
|
||||||
ahash = "0.7"
|
ahash = "0.7"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
|
cookie = { version = "0.15", features = ["percent-encode"], optional = true }
|
||||||
derive_more = "0.99.5"
|
derive_more = "0.99.5"
|
||||||
either = "1.5.3"
|
either = "1.5.3"
|
||||||
encoding_rs = "0.8"
|
encoding_rs = "0.8"
|
||||||
futures-core = { version = "0.3.7", default-features = false }
|
futures-core = { version = "0.3.7", default-features = false }
|
||||||
futures-util = { version = "0.3.7", default-features = false }
|
futures-util = { version = "0.3.7", default-features = false }
|
||||||
language-tags = "0.2"
|
itoa = "0.4"
|
||||||
|
language-tags = "0.3"
|
||||||
once_cell = "1.5"
|
once_cell = "1.5"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
|
paste = "1"
|
||||||
pin-project = "1.0.0"
|
pin-project = "1.0.0"
|
||||||
regex = "1.4"
|
regex = "1.4"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
@ -108,8 +94,8 @@ time = { version = "0.2.23", default-features = false, features = ["std"] }
|
|||||||
url = "2.1"
|
url = "2.1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-test = { version = "0.1.0-beta.1", features = ["openssl", "rustls"] }
|
actix-test = { version = "0.1.0-beta.2", features = ["openssl", "rustls"] }
|
||||||
awc = { version = "3.0.0-beta.4", features = ["openssl"] }
|
awc = { version = "3.0.0-beta.5", features = ["openssl"] }
|
||||||
|
|
||||||
brotli2 = "0.3.2"
|
brotli2 = "0.3.2"
|
||||||
criterion = "0.3"
|
criterion = "0.3"
|
||||||
@ -137,6 +123,22 @@ actix-web-actors = { path = "actix-web-actors" }
|
|||||||
actix-web-codegen = { path = "actix-web-codegen" }
|
actix-web-codegen = { path = "actix-web-codegen" }
|
||||||
awc = { path = "awc" }
|
awc = { path = "awc" }
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "test_server"
|
||||||
|
required-features = ["compress", "cookies"]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "basic"
|
||||||
|
required-features = ["compress"]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "uds"
|
||||||
|
required-features = ["compress"]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "on_connect"
|
||||||
|
required-features = []
|
||||||
|
|
||||||
[[bench]]
|
[[bench]]
|
||||||
name = "server"
|
name = "server"
|
||||||
harness = false
|
harness = false
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
Copyright (c) 2017 Actix Team
|
Copyright (c) 2017-NOW Actix Team
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any
|
Permission is hereby granted, free of charge, to any
|
||||||
person obtaining a copy of this software and associated
|
person obtaining a copy of this software and associated
|
||||||
|
@ -31,7 +31,7 @@
|
|||||||
* Static assets
|
* Static assets
|
||||||
* SSL support using OpenSSL or Rustls
|
* SSL support using OpenSSL or Rustls
|
||||||
* Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
|
* Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
|
||||||
* Includes an async [HTTP client](https://docs.rs/actix-web/latest/actix_web/client/index.html)
|
* Includes an async [HTTP client](https://docs.rs/awc/)
|
||||||
* Runs on stable Rust 1.46+
|
* Runs on stable Rust 1.46+
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
@ -90,7 +90,7 @@ You may consider checking out
|
|||||||
## Benchmarks
|
## Benchmarks
|
||||||
|
|
||||||
One of the fastest web frameworks available according to the
|
One of the fastest web frameworks available according to the
|
||||||
[TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r19).
|
[TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r20&test=composite).
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -1,11 +1,21 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
* `NamedFile` now implements `ServiceFactory` and `HttpServiceFactory` making it much more useful in routing. For example, it can be used directly as a default service. [#2135]
|
||||||
|
* For symbolic links, `Content-Disposition` header no longer shows the filename of the original file. [#2156]
|
||||||
|
* `Files::redirect_to_slash_directory()` now works as expected when used with `Files::show_files_listing()`. [#2225]
|
||||||
|
|
||||||
|
[#2135]: https://github.com/actix/actix-web/pull/2135
|
||||||
|
[#2156]: https://github.com/actix/actix-web/pull/2156
|
||||||
|
[#2225]: https://github.com/actix/actix-web/pull/2225
|
||||||
|
|
||||||
|
|
||||||
## 0.6.0-beta.4 - 2021-04-02
|
## 0.6.0-beta.4 - 2021-04-02
|
||||||
* No notable changes.
|
* No notable changes.
|
||||||
|
|
||||||
|
* Add support for `.guard` in `Files` to selectively filter `Files` services. [#2046]
|
||||||
|
|
||||||
|
[#2046]: https://github.com/actix/actix-web/pull/2046
|
||||||
|
|
||||||
## 0.6.0-beta.3 - 2021-03-09
|
## 0.6.0-beta.3 - 2021-03-09
|
||||||
* No notable changes.
|
* No notable changes.
|
||||||
|
@ -17,9 +17,9 @@ name = "actix_files"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "4.0.0-beta.5", default-features = false }
|
actix-web = { version = "4.0.0-beta.6", default-features = false }
|
||||||
actix-service = "2.0.0-beta.4"
|
actix-service = "2.0.0"
|
||||||
actix-utils = "3.0.0-beta.4"
|
actix-utils = "3.0.0"
|
||||||
|
|
||||||
askama_escape = "0.10"
|
askama_escape = "0.10"
|
||||||
bitflags = "1"
|
bitflags = "1"
|
||||||
@ -34,5 +34,5 @@ percent-encoding = "2.1"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-web = "4.0.0-beta.5"
|
actix-web = "4.0.0-beta.6"
|
||||||
actix-test = "0.1.0-beta.1"
|
actix-test = "0.1.0-beta.2"
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use actix_web::{http::StatusCode, HttpResponse, ResponseError};
|
use actix_web::{http::StatusCode, ResponseError};
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
|
|
||||||
/// Errors which can occur when serving static files.
|
/// Errors which can occur when serving static files.
|
||||||
@ -16,8 +16,8 @@ pub enum FilesError {
|
|||||||
|
|
||||||
/// Return `NotFound` for `FilesError`
|
/// Return `NotFound` for `FilesError`
|
||||||
impl ResponseError for FilesError {
|
impl ResponseError for FilesError {
|
||||||
fn error_response(&self) -> HttpResponse {
|
fn status_code(&self) -> StatusCode {
|
||||||
HttpResponse::new(StatusCode::NOT_FOUND)
|
StatusCode::NOT_FOUND
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -37,7 +37,8 @@ pub struct Files {
|
|||||||
renderer: Rc<DirectoryRenderer>,
|
renderer: Rc<DirectoryRenderer>,
|
||||||
mime_override: Option<Rc<MimeOverride>>,
|
mime_override: Option<Rc<MimeOverride>>,
|
||||||
file_flags: named::Flags,
|
file_flags: named::Flags,
|
||||||
guards: Option<Rc<dyn Guard>>,
|
use_guards: Option<Rc<dyn Guard>>,
|
||||||
|
guards: Vec<Rc<dyn Guard>>,
|
||||||
hidden_files: bool,
|
hidden_files: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,6 +60,7 @@ impl Clone for Files {
|
|||||||
file_flags: self.file_flags,
|
file_flags: self.file_flags,
|
||||||
path: self.path.clone(),
|
path: self.path.clone(),
|
||||||
mime_override: self.mime_override.clone(),
|
mime_override: self.mime_override.clone(),
|
||||||
|
use_guards: self.use_guards.clone(),
|
||||||
guards: self.guards.clone(),
|
guards: self.guards.clone(),
|
||||||
hidden_files: self.hidden_files,
|
hidden_files: self.hidden_files,
|
||||||
}
|
}
|
||||||
@ -80,10 +82,9 @@ impl Files {
|
|||||||
/// If the mount path is set as the root path `/`, services registered after this one will
|
/// If the mount path is set as the root path `/`, services registered after this one will
|
||||||
/// be inaccessible. Register more specific handlers and services first.
|
/// be inaccessible. Register more specific handlers and services first.
|
||||||
///
|
///
|
||||||
/// `Files` uses a threadpool for blocking filesystem operations. By default, the pool uses a
|
/// `Files` utilizes the existing Tokio thread-pool for blocking filesystem operations.
|
||||||
/// max number of threads equal to `512 * HttpServer::worker`. Real time thread count are
|
/// The number of running threads is adjusted over time as needed, up to a maximum of 512 times
|
||||||
/// adjusted with work load. More threads would spawn when need and threads goes idle for a
|
/// the number of server [workers](actix_web::HttpServer::workers), by default.
|
||||||
/// period of time would be de-spawned.
|
|
||||||
pub fn new<T: Into<PathBuf>>(mount_path: &str, serve_from: T) -> Files {
|
pub fn new<T: Into<PathBuf>>(mount_path: &str, serve_from: T) -> Files {
|
||||||
let orig_dir = serve_from.into();
|
let orig_dir = serve_from.into();
|
||||||
let dir = match orig_dir.canonicalize() {
|
let dir = match orig_dir.canonicalize() {
|
||||||
@ -104,7 +105,8 @@ impl Files {
|
|||||||
renderer: Rc::new(directory_listing),
|
renderer: Rc::new(directory_listing),
|
||||||
mime_override: None,
|
mime_override: None,
|
||||||
file_flags: named::Flags::default(),
|
file_flags: named::Flags::default(),
|
||||||
guards: None,
|
use_guards: None,
|
||||||
|
guards: Vec::new(),
|
||||||
hidden_files: false,
|
hidden_files: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -156,7 +158,6 @@ impl Files {
|
|||||||
/// Specifies whether to use ETag or not.
|
/// Specifies whether to use ETag or not.
|
||||||
///
|
///
|
||||||
/// Default is true.
|
/// Default is true.
|
||||||
#[inline]
|
|
||||||
pub fn use_etag(mut self, value: bool) -> Self {
|
pub fn use_etag(mut self, value: bool) -> Self {
|
||||||
self.file_flags.set(named::Flags::ETAG, value);
|
self.file_flags.set(named::Flags::ETAG, value);
|
||||||
self
|
self
|
||||||
@ -165,7 +166,6 @@ impl Files {
|
|||||||
/// Specifies whether to use Last-Modified or not.
|
/// Specifies whether to use Last-Modified or not.
|
||||||
///
|
///
|
||||||
/// Default is true.
|
/// Default is true.
|
||||||
#[inline]
|
|
||||||
pub fn use_last_modified(mut self, value: bool) -> Self {
|
pub fn use_last_modified(mut self, value: bool) -> Self {
|
||||||
self.file_flags.set(named::Flags::LAST_MD, value);
|
self.file_flags.set(named::Flags::LAST_MD, value);
|
||||||
self
|
self
|
||||||
@ -174,31 +174,74 @@ impl Files {
|
|||||||
/// Specifies whether text responses should signal a UTF-8 encoding.
|
/// Specifies whether text responses should signal a UTF-8 encoding.
|
||||||
///
|
///
|
||||||
/// Default is false (but will default to true in a future version).
|
/// Default is false (but will default to true in a future version).
|
||||||
#[inline]
|
|
||||||
pub fn prefer_utf8(mut self, value: bool) -> Self {
|
pub fn prefer_utf8(mut self, value: bool) -> Self {
|
||||||
self.file_flags.set(named::Flags::PREFER_UTF8, value);
|
self.file_flags.set(named::Flags::PREFER_UTF8, value);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specifies custom guards to use for directory listings and files.
|
/// Adds a routing guard.
|
||||||
///
|
///
|
||||||
/// Default behaviour allows GET and HEAD.
|
/// Use this to allow multiple chained file services that respond to strictly different
|
||||||
#[inline]
|
/// properties of a request. Due to the way routing works, if a guard check returns true and the
|
||||||
pub fn use_guards<G: Guard + 'static>(mut self, guards: G) -> Self {
|
/// request starts being handled by the file service, it will not be able to back-out and try
|
||||||
self.guards = Some(Rc::new(guards));
|
/// the next service, you will simply get a 404 (or 405) error response.
|
||||||
|
///
|
||||||
|
/// To allow `POST` requests to retrieve files, see [`Files::use_guards`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::{guard::Header, App};
|
||||||
|
/// use actix_files::Files;
|
||||||
|
///
|
||||||
|
/// App::new().service(
|
||||||
|
/// Files::new("/","/my/site/files")
|
||||||
|
/// .guard(Header("Host", "example.com"))
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
|
||||||
|
self.guards.push(Rc::new(guard));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Specifies guard to check before fetching directory listings or files.
|
||||||
|
///
|
||||||
|
/// Note that this guard has no effect on routing; it's main use is to guard on the request's
|
||||||
|
/// method just before serving the file, only allowing `GET` and `HEAD` requests by default.
|
||||||
|
/// See [`Files::guard`] for routing guards.
|
||||||
|
pub fn method_guard<G: Guard + 'static>(mut self, guard: G) -> Self {
|
||||||
|
self.use_guards = Some(Rc::new(guard));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
#[deprecated(since = "0.6.0", note = "Renamed to `method_guard`.")]
|
||||||
|
/// See [`Files::method_guard`].
|
||||||
|
pub fn use_guards<G: Guard + 'static>(self, guard: G) -> Self {
|
||||||
|
self.method_guard(guard)
|
||||||
|
}
|
||||||
|
|
||||||
/// Disable `Content-Disposition` header.
|
/// Disable `Content-Disposition` header.
|
||||||
///
|
///
|
||||||
/// By default Content-Disposition` header is enabled.
|
/// By default Content-Disposition` header is enabled.
|
||||||
#[inline]
|
|
||||||
pub fn disable_content_disposition(mut self) -> Self {
|
pub fn disable_content_disposition(mut self) -> Self {
|
||||||
self.file_flags.remove(named::Flags::CONTENT_DISPOSITION);
|
self.file_flags.remove(named::Flags::CONTENT_DISPOSITION);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets default handler which is used when no matched file could be found.
|
/// Sets default handler which is used when no matched file could be found.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// Setting a fallback static file handler:
|
||||||
|
/// ```
|
||||||
|
/// use actix_files::{Files, NamedFile};
|
||||||
|
///
|
||||||
|
/// # fn run() -> Result<(), actix_web::Error> {
|
||||||
|
/// let files = Files::new("/", "./static")
|
||||||
|
/// .index_file("index.html")
|
||||||
|
/// .default_handler(NamedFile::open("./static/404.html")?);
|
||||||
|
/// # Ok(())
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
pub fn default_handler<F, U>(mut self, f: F) -> Self
|
pub fn default_handler<F, U>(mut self, f: F) -> Self
|
||||||
where
|
where
|
||||||
F: IntoServiceFactory<U, ServiceRequest>,
|
F: IntoServiceFactory<U, ServiceRequest>,
|
||||||
@ -218,7 +261,6 @@ impl Files {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Enables serving hidden files and directories, allowing a leading dots in url fragments.
|
/// Enables serving hidden files and directories, allowing a leading dots in url fragments.
|
||||||
#[inline]
|
|
||||||
pub fn use_hidden_files(mut self) -> Self {
|
pub fn use_hidden_files(mut self) -> Self {
|
||||||
self.hidden_files = true;
|
self.hidden_files = true;
|
||||||
self
|
self
|
||||||
@ -226,7 +268,19 @@ impl Files {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl HttpServiceFactory for Files {
|
impl HttpServiceFactory for Files {
|
||||||
fn register(self, config: &mut AppService) {
|
fn register(mut self, config: &mut AppService) {
|
||||||
|
let guards = if self.guards.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let guards = std::mem::take(&mut self.guards);
|
||||||
|
Some(
|
||||||
|
guards
|
||||||
|
.into_iter()
|
||||||
|
.map(|guard| -> Box<dyn Guard> { Box::new(guard) })
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
if self.default.borrow().is_none() {
|
if self.default.borrow().is_none() {
|
||||||
*self.default.borrow_mut() = Some(config.default_service());
|
*self.default.borrow_mut() = Some(config.default_service());
|
||||||
}
|
}
|
||||||
@ -237,7 +291,7 @@ impl HttpServiceFactory for Files {
|
|||||||
ResourceDef::prefix(&self.path)
|
ResourceDef::prefix(&self.path)
|
||||||
};
|
};
|
||||||
|
|
||||||
config.register_service(rdef, None, self, None)
|
config.register_service(rdef, guards, self, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -259,7 +313,7 @@ impl ServiceFactory<ServiceRequest> for Files {
|
|||||||
renderer: self.renderer.clone(),
|
renderer: self.renderer.clone(),
|
||||||
mime_override: self.mime_override.clone(),
|
mime_override: self.mime_override.clone(),
|
||||||
file_flags: self.file_flags,
|
file_flags: self.file_flags,
|
||||||
guards: self.guards.clone(),
|
guards: self.use_guards.clone(),
|
||||||
hidden_files: self.hidden_files,
|
hidden_files: self.hidden_files,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -532,7 +532,7 @@ mod tests {
|
|||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_files_guards() {
|
async fn test_files_guards() {
|
||||||
let srv = test::init_service(
|
let srv = test::init_service(
|
||||||
App::new().service(Files::new("/", ".").use_guards(guard::Post())),
|
App::new().service(Files::new("/", ".").method_guard(guard::Post())),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
@ -632,7 +632,7 @@ mod tests {
|
|||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_redirect_to_slash_directory() {
|
async fn test_redirect_to_slash_directory() {
|
||||||
// should not redirect if no index
|
// should not redirect if no index and files listing is disabled
|
||||||
let srv = test::init_service(
|
let srv = test::init_service(
|
||||||
App::new().service(Files::new("/", ".").redirect_to_slash_directory()),
|
App::new().service(Files::new("/", ".").redirect_to_slash_directory()),
|
||||||
)
|
)
|
||||||
@ -654,6 +654,19 @@ mod tests {
|
|||||||
let resp = test::call_service(&srv, req).await;
|
let resp = test::call_service(&srv, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::FOUND);
|
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||||
|
|
||||||
|
// should redirect if files listing is enabled
|
||||||
|
let srv = test::init_service(
|
||||||
|
App::new().service(
|
||||||
|
Files::new("/", ".")
|
||||||
|
.show_files_listing()
|
||||||
|
.redirect_to_slash_directory(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let req = TestRequest::with_uri("/tests").to_request();
|
||||||
|
let resp = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||||
|
|
||||||
// should not redirect if the path is wrong
|
// should not redirect if the path is wrong
|
||||||
let req = TestRequest::with_uri("/not_existing").to_request();
|
let req = TestRequest::with_uri("/not_existing").to_request();
|
||||||
let resp = test::call_service(&srv, req).await;
|
let resp = test::call_service(&srv, req).await;
|
||||||
@ -754,4 +767,93 @@ mod tests {
|
|||||||
let res = test::call_service(&srv, req).await;
|
let res = test::call_service(&srv, req).await;
|
||||||
assert_eq!(res.status(), StatusCode::OK);
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_serve_named_file() {
|
||||||
|
let srv =
|
||||||
|
test::init_service(App::new().service(NamedFile::open("Cargo.toml").unwrap()))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let req = TestRequest::get().uri("/Cargo.toml").to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
|
||||||
|
let bytes = test::read_body(res).await;
|
||||||
|
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
|
||||||
|
assert_eq!(bytes, data);
|
||||||
|
|
||||||
|
let req = TestRequest::get().uri("/test/unknown").to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_serve_named_file_prefix() {
|
||||||
|
let srv = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.service(web::scope("/test").service(NamedFile::open("Cargo.toml").unwrap())),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let req = TestRequest::get().uri("/test/Cargo.toml").to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
|
||||||
|
let bytes = test::read_body(res).await;
|
||||||
|
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
|
||||||
|
assert_eq!(bytes, data);
|
||||||
|
|
||||||
|
let req = TestRequest::get().uri("/Cargo.toml").to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_named_file_default_service() {
|
||||||
|
let srv = test::init_service(
|
||||||
|
App::new().default_service(NamedFile::open("Cargo.toml").unwrap()),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
for route in ["/foobar", "/baz", "/"].iter() {
|
||||||
|
let req = TestRequest::get().uri(route).to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
|
||||||
|
let bytes = test::read_body(res).await;
|
||||||
|
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
|
||||||
|
assert_eq!(bytes, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_default_handler_named_file() {
|
||||||
|
let st = Files::new("/", ".")
|
||||||
|
.default_handler(NamedFile::open("Cargo.toml").unwrap())
|
||||||
|
.new_service(())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let req = TestRequest::with_uri("/missing").to_srv_request();
|
||||||
|
let resp = test::call_service(&st, req).await;
|
||||||
|
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
let bytes = test::read_body(resp).await;
|
||||||
|
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
|
||||||
|
assert_eq!(bytes, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_symlinks() {
|
||||||
|
let srv = test::init_service(App::new().service(Files::new("test", "."))).await;
|
||||||
|
|
||||||
|
let req = TestRequest::get()
|
||||||
|
.uri("/test/tests/symlink-test.png")
|
||||||
|
.to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert_eq!(
|
||||||
|
res.headers().get(header::CONTENT_DISPOSITION).unwrap(),
|
||||||
|
"inline; filename=\"symlink-test.png\""
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,6 @@
|
|||||||
|
use actix_service::{Service, ServiceFactory};
|
||||||
|
use actix_utils::future::{ok, ready, Ready};
|
||||||
|
use actix_web::dev::{AppService, HttpServiceFactory, ResourceDef};
|
||||||
use std::fs::{File, Metadata};
|
use std::fs::{File, Metadata};
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::ops::{Deref, DerefMut};
|
use std::ops::{Deref, DerefMut};
|
||||||
@ -8,14 +11,14 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
|||||||
use std::os::unix::fs::MetadataExt;
|
use std::os::unix::fs::MetadataExt;
|
||||||
|
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::{BodyEncoding, SizedStream},
|
dev::{BodyEncoding, ServiceRequest, ServiceResponse, SizedStream},
|
||||||
http::{
|
http::{
|
||||||
header::{
|
header::{
|
||||||
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
|
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
|
||||||
},
|
},
|
||||||
ContentEncoding, StatusCode,
|
ContentEncoding, StatusCode,
|
||||||
},
|
},
|
||||||
HttpMessage, HttpRequest, HttpResponse, Responder,
|
Error, HttpMessage, HttpRequest, HttpResponse, Responder,
|
||||||
};
|
};
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
use mime_guess::from_path;
|
use mime_guess::from_path;
|
||||||
@ -39,6 +42,29 @@ impl Default for Flags {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A file with an associated name.
|
/// A file with an associated name.
|
||||||
|
///
|
||||||
|
/// `NamedFile` can be registered as services:
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::App;
|
||||||
|
/// use actix_files::NamedFile;
|
||||||
|
///
|
||||||
|
/// # fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
/// let app = App::new()
|
||||||
|
/// .service(NamedFile::open("./static/index.html")?);
|
||||||
|
/// # Ok(())
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// They can also be returned from handlers:
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::{Responder, get};
|
||||||
|
/// use actix_files::NamedFile;
|
||||||
|
///
|
||||||
|
/// #[get("/")]
|
||||||
|
/// async fn index() -> impl Responder {
|
||||||
|
/// NamedFile::open("./static/index.html")
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct NamedFile {
|
pub struct NamedFile {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
@ -480,3 +506,53 @@ impl Responder for NamedFile {
|
|||||||
self.into_response(req)
|
self.into_response(req)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ServiceFactory<ServiceRequest> for NamedFile {
|
||||||
|
type Response = ServiceResponse;
|
||||||
|
type Error = Error;
|
||||||
|
type Config = ();
|
||||||
|
type InitError = ();
|
||||||
|
type Service = NamedFileService;
|
||||||
|
type Future = Ready<Result<Self::Service, ()>>;
|
||||||
|
|
||||||
|
fn new_service(&self, _: ()) -> Self::Future {
|
||||||
|
ok(NamedFileService {
|
||||||
|
path: self.path.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct NamedFileService {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service<ServiceRequest> for NamedFileService {
|
||||||
|
type Response = ServiceResponse;
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Ready<Result<Self::Response, Self::Error>>;
|
||||||
|
|
||||||
|
actix_service::always_ready!();
|
||||||
|
|
||||||
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||||
|
let (req, _) = req.into_parts();
|
||||||
|
ready(
|
||||||
|
NamedFile::open(&self.path)
|
||||||
|
.map_err(|e| e.into())
|
||||||
|
.map(|f| f.into_response(&req))
|
||||||
|
.map(|res| ServiceResponse::new(req, res)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HttpServiceFactory for NamedFile {
|
||||||
|
fn register(self, config: &mut AppService) {
|
||||||
|
config.register_service(
|
||||||
|
ResourceDef::root_prefix(self.path.to_string_lossy().as_ref()),
|
||||||
|
None,
|
||||||
|
self,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -83,24 +83,26 @@ impl Service<ServiceRequest> for FilesService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// full file path
|
// full file path
|
||||||
let path = match self.directory.join(&real_path).canonicalize() {
|
let path = self.directory.join(&real_path);
|
||||||
Ok(path) => path,
|
if let Err(err) = path.canonicalize() {
|
||||||
Err(err) => return Box::pin(self.handle_err(err, req)),
|
return Box::pin(self.handle_err(err, req));
|
||||||
};
|
}
|
||||||
|
|
||||||
if path.is_dir() {
|
if path.is_dir() {
|
||||||
|
if self.redirect_to_slash
|
||||||
|
&& !req.path().ends_with('/')
|
||||||
|
&& (self.index.is_some() || self.show_index)
|
||||||
|
{
|
||||||
|
let redirect_to = format!("{}/", req.path());
|
||||||
|
|
||||||
|
return Box::pin(ok(req.into_response(
|
||||||
|
HttpResponse::Found()
|
||||||
|
.insert_header((header::LOCATION, redirect_to))
|
||||||
|
.finish(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(ref redir_index) = self.index {
|
if let Some(ref redir_index) = self.index {
|
||||||
if self.redirect_to_slash && !req.path().ends_with('/') {
|
|
||||||
let redirect_to = format!("{}/", req.path());
|
|
||||||
|
|
||||||
return Box::pin(ok(req.into_response(
|
|
||||||
HttpResponse::Found()
|
|
||||||
.insert_header((header::LOCATION, redirect_to))
|
|
||||||
.body("")
|
|
||||||
.into_body(),
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
let path = path.join(redir_index);
|
let path = path.join(redir_index);
|
||||||
|
|
||||||
match NamedFile::open(path) {
|
match NamedFile::open(path) {
|
||||||
|
1
actix-files/tests/fixtures/guards/first/index.txt
vendored
Normal file
1
actix-files/tests/fixtures/guards/first/index.txt
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
first
|
1
actix-files/tests/fixtures/guards/second/index.txt
vendored
Normal file
1
actix-files/tests/fixtures/guards/second/index.txt
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
second
|
36
actix-files/tests/guard.rs
Normal file
36
actix-files/tests/guard.rs
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
use actix_files::Files;
|
||||||
|
use actix_web::{
|
||||||
|
guard::Host,
|
||||||
|
http::StatusCode,
|
||||||
|
test::{self, TestRequest},
|
||||||
|
App,
|
||||||
|
};
|
||||||
|
use bytes::Bytes;
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_guard_filter() {
|
||||||
|
let srv = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.service(Files::new("/", "./tests/fixtures/guards/first").guard(Host("first.com")))
|
||||||
|
.service(
|
||||||
|
Files::new("/", "./tests/fixtures/guards/second").guard(Host("second.com")),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/index.txt")
|
||||||
|
.append_header(("Host", "first.com"))
|
||||||
|
.to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert_eq!(test::read_body(res).await, Bytes::from("first"));
|
||||||
|
|
||||||
|
let req = TestRequest::with_uri("/index.txt")
|
||||||
|
.append_header(("Host", "second.com"))
|
||||||
|
.to_request();
|
||||||
|
let res = test::call_service(&srv, req).await;
|
||||||
|
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert_eq!(test::read_body(res).await, Bytes::from("second"));
|
||||||
|
}
|
1
actix-files/tests/symlink-test.png
Symbolic link
1
actix-files/tests/symlink-test.png
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
test.png
|
@ -29,13 +29,13 @@ default = []
|
|||||||
openssl = ["tls-openssl", "awc/openssl"]
|
openssl = ["tls-openssl", "awc/openssl"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "2.0.0-beta.4"
|
actix-service = "2.0.0"
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0"
|
||||||
actix-tls = "3.0.0-beta.5"
|
actix-tls = "3.0.0-beta.5"
|
||||||
actix-utils = "3.0.0-beta.4"
|
actix-utils = "3.0.0"
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-server = "2.0.0-beta.3"
|
actix-server = "2.0.0-beta.3"
|
||||||
awc = { version = "3.0.0-beta.4", default-features = false }
|
awc = { version = "3.0.0-beta.5", default-features = false }
|
||||||
|
|
||||||
base64 = "0.13"
|
base64 = "0.13"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
@ -51,5 +51,5 @@ time = { version = "0.2.23", default-features = false, features = ["std"] }
|
|||||||
tls-openssl = { version = "0.10.9", package = "openssl", optional = true }
|
tls-openssl = { version = "0.10.9", package = "openssl", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "4.0.0-beta.5", default-features = false, features = ["cookies"] }
|
actix-web = { version = "4.0.0-beta.6", default-features = false, features = ["cookies"] }
|
||||||
actix-http = "3.0.0-beta.5"
|
actix-http = "3.0.0-beta.6"
|
||||||
|
@ -1,6 +1,72 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
### Added
|
||||||
|
* Alias `body::Body` as `body::AnyBody`. [#2215]
|
||||||
|
* `BoxAnyBody`: a boxed message body with boxed errors. [#2183]
|
||||||
|
* Re-export `http` crate's `Error` type as `error::HttpError`. [#2171]
|
||||||
|
* Re-export `StatusCode`, `Method`, `Version` and `Uri` at the crate root. [#2171]
|
||||||
|
* Re-export `ContentEncoding` and `ConnectionType` at the crate root. [#2171]
|
||||||
|
* `Response::into_body` that consumes response and returns body type. [#2201]
|
||||||
|
* `impl Default` for `Response`. [#2201]
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
* The `MessageBody` trait now has an associated `Error` type. [#2183]
|
||||||
|
* Places in `Response` where `ResponseBody<B>` was received or returned now simply use `B`. [#2201]
|
||||||
|
* `header` mod is now public. [#2171]
|
||||||
|
* `uri` mod is now public. [#2171]
|
||||||
|
* Update `language-tags` to `0.3`.
|
||||||
|
* Reduce the level from `error` to `debug` for the log line that is emitted when a `500 Internal Server Error` is built using `HttpResponse::from_error`. [#2201]
|
||||||
|
* `ResponseBuilder::message_body` now returns a `Result`. [#2201]
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
* Stop re-exporting `http` crate's `HeaderMap` types in addition to ours. [#2171]
|
||||||
|
* Down-casting for `MessageBody` types. [#2183]
|
||||||
|
* `error::Result` alias. [#2201]
|
||||||
|
* Error field from `Response` and `Response::error`. [#2205]
|
||||||
|
* `impl Future` for `Response`. [#2201]
|
||||||
|
* `Response::take_body` and old `Response::into_body` method that casted body type. [#2201]
|
||||||
|
* `InternalError` and all the error types it constructed. [#2215]
|
||||||
|
* Conversion (`impl Into`) of `Response<Body>` and `ResponseBuilder` to `Error`. [#2215]
|
||||||
|
|
||||||
|
[#2171]: https://github.com/actix/actix-web/pull/2171
|
||||||
|
[#2183]: https://github.com/actix/actix-web/pull/2183
|
||||||
|
[#2196]: https://github.com/actix/actix-web/pull/2196
|
||||||
|
[#2201]: https://github.com/actix/actix-web/pull/2201
|
||||||
|
[#2205]: https://github.com/actix/actix-web/pull/2205
|
||||||
|
[#2215]: https://github.com/actix/actix-web/pull/2215
|
||||||
|
|
||||||
|
|
||||||
|
## 3.0.0-beta.6 - 2021-04-17
|
||||||
|
### Added
|
||||||
|
* `impl<T: MessageBody> MessageBody for Pin<Box<T>>`. [#2152]
|
||||||
|
* `Response::{ok, bad_request, not_found, internal_server_error}`. [#2159]
|
||||||
|
* Helper `body::to_bytes` for async collecting message body into Bytes. [#2158]
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
* The type parameter of `Response` no longer has a default. [#2152]
|
||||||
|
* The `Message` variant of `body::Body` is now `Pin<Box<dyn MessageBody>>`. [#2152]
|
||||||
|
* `BodyStream` and `SizedStream` are no longer restricted to Unpin types. [#2152]
|
||||||
|
* Error enum types are marked `#[non_exhaustive]`. [#2161]
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
* `cookies` feature flag. [#2065]
|
||||||
|
* Top-level `cookies` mod (re-export). [#2065]
|
||||||
|
* `HttpMessage` trait loses the `cookies` and `cookie` methods. [#2065]
|
||||||
|
* `impl ResponseError for CookieParseError`. [#2065]
|
||||||
|
* Deprecated methods on `ResponseBuilder`: `if_true`, `if_some`. [#2148]
|
||||||
|
* `ResponseBuilder::json`. [#2148]
|
||||||
|
* `ResponseBuilder::{set_header, header}`. [#2148]
|
||||||
|
* `impl From<serde_json::Value> for Body`. [#2148]
|
||||||
|
* `Response::build_from`. [#2159]
|
||||||
|
* Most of the status code builders on `Response`. [#2159]
|
||||||
|
|
||||||
|
[#2065]: https://github.com/actix/actix-web/pull/2065
|
||||||
|
[#2148]: https://github.com/actix/actix-web/pull/2148
|
||||||
|
[#2152]: https://github.com/actix/actix-web/pull/2152
|
||||||
|
[#2159]: https://github.com/actix/actix-web/pull/2159
|
||||||
|
[#2158]: https://github.com/actix/actix-web/pull/2158
|
||||||
|
[#2161]: https://github.com/actix/actix-web/pull/2161
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.5 - 2021-04-02
|
## 3.0.0-beta.5 - 2021-04-02
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http"
|
name = "actix-http"
|
||||||
version = "3.0.0-beta.5"
|
version = "3.0.0-beta.6"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "HTTP primitives for the Actix ecosystem"
|
description = "HTTP primitives for the Actix ecosystem"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -16,7 +16,7 @@ edition = "2018"
|
|||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
# features that docs.rs will build with
|
# features that docs.rs will build with
|
||||||
features = ["openssl", "rustls", "compress", "cookies", "secure-cookies"]
|
features = ["openssl", "rustls", "compress"]
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "actix_http"
|
name = "actix_http"
|
||||||
@ -34,19 +34,13 @@ rustls = ["actix-tls/rustls"]
|
|||||||
# enable compression support
|
# enable compression support
|
||||||
compress = ["flate2", "brotli2"]
|
compress = ["flate2", "brotli2"]
|
||||||
|
|
||||||
# support for cookies
|
|
||||||
cookies = ["cookie"]
|
|
||||||
|
|
||||||
# support for secure cookies
|
|
||||||
secure-cookies = ["cookies", "cookie/secure"]
|
|
||||||
|
|
||||||
# trust-dns as client dns resolver
|
# trust-dns as client dns resolver
|
||||||
trust-dns = ["trust-dns-resolver"]
|
trust-dns = ["trust-dns-resolver"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "2.0.0-beta.4"
|
actix-service = "2.0.0"
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0"
|
||||||
actix-utils = "3.0.0-beta.4"
|
actix-utils = "3.0.0"
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-tls = { version = "3.0.0-beta.5", features = ["accept", "connect"] }
|
actix-tls = { version = "3.0.0-beta.5", features = ["accept", "connect"] }
|
||||||
|
|
||||||
@ -55,7 +49,6 @@ base64 = "0.13"
|
|||||||
bitflags = "1.2"
|
bitflags = "1.2"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
bytestring = "1"
|
bytestring = "1"
|
||||||
cookie = { version = "0.14.1", features = ["percent-encode"], optional = true }
|
|
||||||
derive_more = "0.99.5"
|
derive_more = "0.99.5"
|
||||||
encoding_rs = "0.8"
|
encoding_rs = "0.8"
|
||||||
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||||
@ -64,7 +57,7 @@ h2 = "0.3.1"
|
|||||||
http = "0.2.2"
|
http = "0.2.2"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
itoa = "0.4"
|
itoa = "0.4"
|
||||||
language-tags = "0.2"
|
language-tags = "0.3"
|
||||||
local-channel = "0.1"
|
local-channel = "0.1"
|
||||||
once_cell = "1.5"
|
once_cell = "1.5"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
@ -75,8 +68,6 @@ pin-project-lite = "0.2"
|
|||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
regex = "1.3"
|
regex = "1.3"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
|
||||||
serde_urlencoded = "0.7"
|
|
||||||
sha-1 = "0.9"
|
sha-1 = "0.9"
|
||||||
smallvec = "1.6"
|
smallvec = "1.6"
|
||||||
time = { version = "0.2.23", default-features = false, features = ["std"] }
|
time = { version = "0.2.23", default-features = false, features = ["std"] }
|
||||||
@ -95,7 +86,8 @@ actix-tls = { version = "3.0.0-beta.5", features = ["openssl"] }
|
|||||||
criterion = "0.3"
|
criterion = "0.3"
|
||||||
env_logger = "0.8"
|
env_logger = "0.8"
|
||||||
rcgen = "0.8"
|
rcgen = "0.8"
|
||||||
serde_derive = "1.0"
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
tls-openssl = { version = "0.10", package = "openssl" }
|
tls-openssl = { version = "0.10", package = "openssl" }
|
||||||
tls-rustls = { version = "0.19", package = "rustls" }
|
tls-rustls = { version = "0.19", package = "rustls" }
|
||||||
|
|
||||||
|
@ -3,11 +3,11 @@
|
|||||||
> HTTP primitives for the Actix ecosystem.
|
> HTTP primitives for the Actix ecosystem.
|
||||||
|
|
||||||
[![crates.io](https://img.shields.io/crates/v/actix-http?label=latest)](https://crates.io/crates/actix-http)
|
[![crates.io](https://img.shields.io/crates/v/actix-http?label=latest)](https://crates.io/crates/actix-http)
|
||||||
[![Documentation](https://docs.rs/actix-http/badge.svg?version=3.0.0-beta.5)](https://docs.rs/actix-http/3.0.0-beta.5)
|
[![Documentation](https://docs.rs/actix-http/badge.svg?version=3.0.0-beta.6)](https://docs.rs/actix-http/3.0.0-beta.6)
|
||||||
[![Version](https://img.shields.io/badge/rustc-1.46+-ab6000.svg)](https://blog.rust-lang.org/2020/03/12/Rust-1.46.html)
|
[![Version](https://img.shields.io/badge/rustc-1.46+-ab6000.svg)](https://blog.rust-lang.org/2020/03/12/Rust-1.46.html)
|
||||||
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http.svg)
|
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http.svg)
|
||||||
<br />
|
<br />
|
||||||
[![dependency status](https://deps.rs/crate/actix-http/3.0.0-beta.5/status.svg)](https://deps.rs/crate/actix-http/3.0.0-beta.5)
|
[![dependency status](https://deps.rs/crate/actix-http/3.0.0-beta.6/status.svg)](https://deps.rs/crate/actix-http/3.0.0-beta.6)
|
||||||
[![Download](https://img.shields.io/crates/d/actix-http.svg)](https://crates.io/crates/actix-http)
|
[![Download](https://img.shields.io/crates/d/actix-http.svg)](https://crates.io/crates/actix-http)
|
||||||
[![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
[![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use std::{env, io};
|
use std::io;
|
||||||
|
|
||||||
use actix_http::{Error, HttpService, Request, Response};
|
use actix_http::{http::StatusCode, Error, HttpService, Request, Response};
|
||||||
use actix_server::Server;
|
use actix_server::Server;
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use futures_util::StreamExt as _;
|
use futures_util::StreamExt as _;
|
||||||
@ -9,8 +9,7 @@ use log::info;
|
|||||||
|
|
||||||
#[actix_rt::main]
|
#[actix_rt::main]
|
||||||
async fn main() -> io::Result<()> {
|
async fn main() -> io::Result<()> {
|
||||||
env::set_var("RUST_LOG", "echo=info");
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
Server::build()
|
Server::build()
|
||||||
.bind("echo", "127.0.0.1:8080", || {
|
.bind("echo", "127.0.0.1:8080", || {
|
||||||
@ -25,7 +24,7 @@ async fn main() -> io::Result<()> {
|
|||||||
|
|
||||||
info!("request body: {:?}", body);
|
info!("request body: {:?}", body);
|
||||||
Ok::<_, Error>(
|
Ok::<_, Error>(
|
||||||
Response::Ok()
|
Response::build(StatusCode::OK)
|
||||||
.insert_header((
|
.insert_header((
|
||||||
"x-head",
|
"x-head",
|
||||||
HeaderValue::from_static("dummy value!"),
|
HeaderValue::from_static("dummy value!"),
|
||||||
|
@ -1,28 +1,27 @@
|
|||||||
use std::{env, io};
|
use std::io;
|
||||||
|
|
||||||
use actix_http::http::HeaderValue;
|
use actix_http::{body::Body, http::HeaderValue, http::StatusCode};
|
||||||
use actix_http::{Error, HttpService, Request, Response};
|
use actix_http::{Error, HttpService, Request, Response};
|
||||||
use actix_server::Server;
|
use actix_server::Server;
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use futures_util::StreamExt as _;
|
use futures_util::StreamExt as _;
|
||||||
use log::info;
|
use log::info;
|
||||||
|
|
||||||
async fn handle_request(mut req: Request) -> Result<Response, Error> {
|
async fn handle_request(mut req: Request) -> Result<Response<Body>, Error> {
|
||||||
let mut body = BytesMut::new();
|
let mut body = BytesMut::new();
|
||||||
while let Some(item) = req.payload().next().await {
|
while let Some(item) = req.payload().next().await {
|
||||||
body.extend_from_slice(&item?)
|
body.extend_from_slice(&item?)
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("request body: {:?}", body);
|
info!("request body: {:?}", body);
|
||||||
Ok(Response::Ok()
|
Ok(Response::build(StatusCode::OK)
|
||||||
.insert_header(("x-head", HeaderValue::from_static("dummy value!")))
|
.insert_header(("x-head", HeaderValue::from_static("dummy value!")))
|
||||||
.body(body))
|
.body(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::main]
|
#[actix_rt::main]
|
||||||
async fn main() -> io::Result<()> {
|
async fn main() -> io::Result<()> {
|
||||||
env::set_var("RUST_LOG", "echo=info");
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
Server::build()
|
Server::build()
|
||||||
.bind("echo", "127.0.0.1:8080", || {
|
.bind("echo", "127.0.0.1:8080", || {
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use std::{env, io};
|
use std::io;
|
||||||
|
|
||||||
use actix_http::{HttpService, Response};
|
use actix_http::{http::StatusCode, HttpService, Response};
|
||||||
use actix_server::Server;
|
use actix_server::Server;
|
||||||
use actix_utils::future;
|
use actix_utils::future;
|
||||||
use http::header::HeaderValue;
|
use http::header::HeaderValue;
|
||||||
@ -8,8 +8,7 @@ use log::info;
|
|||||||
|
|
||||||
#[actix_rt::main]
|
#[actix_rt::main]
|
||||||
async fn main() -> io::Result<()> {
|
async fn main() -> io::Result<()> {
|
||||||
env::set_var("RUST_LOG", "hello_world=info");
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
Server::build()
|
Server::build()
|
||||||
.bind("hello-world", "127.0.0.1:8080", || {
|
.bind("hello-world", "127.0.0.1:8080", || {
|
||||||
@ -18,7 +17,7 @@ async fn main() -> io::Result<()> {
|
|||||||
.client_disconnect(1000)
|
.client_disconnect(1000)
|
||||||
.finish(|_req| {
|
.finish(|_req| {
|
||||||
info!("{:?}", _req);
|
info!("{:?}", _req);
|
||||||
let mut res = Response::Ok();
|
let mut res = Response::build(StatusCode::OK);
|
||||||
res.insert_header((
|
res.insert_header((
|
||||||
"x-head",
|
"x-head",
|
||||||
HeaderValue::from_static("dummy value!"),
|
HeaderValue::from_static("dummy value!"),
|
||||||
|
@ -4,14 +4,14 @@
|
|||||||
extern crate tls_rustls as rustls;
|
extern crate tls_rustls as rustls;
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
env, io,
|
io,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use actix_codec::Encoder;
|
use actix_codec::Encoder;
|
||||||
use actix_http::{error::Error, ws, HttpService, Request, Response};
|
use actix_http::{body::BodyStream, error::Error, ws, HttpService, Request, Response};
|
||||||
use actix_rt::time::{interval, Interval};
|
use actix_rt::time::{interval, Interval};
|
||||||
use actix_server::Server;
|
use actix_server::Server;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
@ -20,8 +20,7 @@ use futures_core::{ready, Stream};
|
|||||||
|
|
||||||
#[actix_rt::main]
|
#[actix_rt::main]
|
||||||
async fn main() -> io::Result<()> {
|
async fn main() -> io::Result<()> {
|
||||||
env::set_var("RUST_LOG", "actix=info,h2_ws=info");
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
Server::build()
|
Server::build()
|
||||||
.bind("tcp", ("127.0.0.1", 8080), || {
|
.bind("tcp", ("127.0.0.1", 8080), || {
|
||||||
@ -34,14 +33,14 @@ async fn main() -> io::Result<()> {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handler(req: Request) -> Result<Response, Error> {
|
async fn handler(req: Request) -> Result<Response<BodyStream<Heartbeat>>, Error> {
|
||||||
log::info!("handshaking");
|
log::info!("handshaking");
|
||||||
let mut res = ws::handshake(req.head())?;
|
let mut res = ws::handshake(req.head())?;
|
||||||
|
|
||||||
// handshake will always fail under HTTP/2
|
// handshake will always fail under HTTP/2
|
||||||
|
|
||||||
log::info!("responding");
|
log::info!("responding");
|
||||||
Ok(res.streaming(Heartbeat::new(ws::Codec::new())))
|
Ok(res.message_body(BodyStream::new(Heartbeat::new(ws::Codec::new())))?)
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Heartbeat {
|
struct Heartbeat {
|
||||||
|
@ -1,58 +1,71 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
borrow::Cow,
|
||||||
|
error::Error as StdError,
|
||||||
fmt, mem,
|
fmt, mem,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures_core::Stream;
|
use futures_core::{ready, Stream};
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
use super::{BodySize, BodyStream, MessageBody, SizedStream};
|
use super::{BodySize, BodyStream, MessageBody, MessageBodyMapErr, SizedStream};
|
||||||
|
|
||||||
|
pub type Body = AnyBody;
|
||||||
|
|
||||||
/// Represents various types of HTTP message body.
|
/// Represents various types of HTTP message body.
|
||||||
pub enum Body {
|
pub enum AnyBody {
|
||||||
/// Empty response. `Content-Length` header is not set.
|
/// Empty response. `Content-Length` header is not set.
|
||||||
None,
|
None,
|
||||||
|
|
||||||
/// Zero sized response body. `Content-Length` header is set to `0`.
|
/// Zero sized response body. `Content-Length` header is set to `0`.
|
||||||
Empty,
|
Empty,
|
||||||
|
|
||||||
/// Specific response body.
|
/// Specific response body.
|
||||||
Bytes(Bytes),
|
Bytes(Bytes),
|
||||||
|
|
||||||
/// Generic message body.
|
/// Generic message body.
|
||||||
Message(Box<dyn MessageBody + Unpin>),
|
Message(BoxAnyBody),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Body {
|
impl AnyBody {
|
||||||
/// Create body from slice (copy)
|
/// Create body from slice (copy)
|
||||||
pub fn from_slice(s: &[u8]) -> Body {
|
pub fn from_slice(s: &[u8]) -> Self {
|
||||||
Body::Bytes(Bytes::copy_from_slice(s))
|
Self::Bytes(Bytes::copy_from_slice(s))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create body from generic message body.
|
/// Create body from generic message body.
|
||||||
pub fn from_message<B: MessageBody + Unpin + 'static>(body: B) -> Body {
|
pub fn from_message<B>(body: B) -> Self
|
||||||
Body::Message(Box::new(body))
|
where
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Box<dyn StdError + 'static>>,
|
||||||
|
{
|
||||||
|
Self::Message(BoxAnyBody::from_body(body))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for Body {
|
impl MessageBody for AnyBody {
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
match self {
|
match self {
|
||||||
Body::None => BodySize::None,
|
AnyBody::None => BodySize::None,
|
||||||
Body::Empty => BodySize::Empty,
|
AnyBody::Empty => BodySize::Empty,
|
||||||
Body::Bytes(ref bin) => BodySize::Sized(bin.len() as u64),
|
AnyBody::Bytes(ref bin) => BodySize::Sized(bin.len() as u64),
|
||||||
Body::Message(ref body) => body.size(),
|
AnyBody::Message(ref body) => body.size(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
match self.get_mut() {
|
match self.get_mut() {
|
||||||
Body::None => Poll::Ready(None),
|
AnyBody::None => Poll::Ready(None),
|
||||||
Body::Empty => Poll::Ready(None),
|
AnyBody::Empty => Poll::Ready(None),
|
||||||
Body::Bytes(ref mut bin) => {
|
AnyBody::Bytes(ref mut bin) => {
|
||||||
let len = bin.len();
|
let len = bin.len();
|
||||||
if len == 0 {
|
if len == 0 {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
@ -60,99 +73,158 @@ impl MessageBody for Body {
|
|||||||
Poll::Ready(Some(Ok(mem::take(bin))))
|
Poll::Ready(Some(Ok(mem::take(bin))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Body::Message(body) => Pin::new(&mut **body).poll_next(cx),
|
|
||||||
|
// TODO: MSRV 1.51: poll_map_err
|
||||||
|
AnyBody::Message(body) => match ready!(body.as_pin_mut().poll_next(cx)) {
|
||||||
|
Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
|
||||||
|
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
|
||||||
|
None => Poll::Ready(None),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for Body {
|
impl PartialEq for AnyBody {
|
||||||
fn eq(&self, other: &Body) -> bool {
|
fn eq(&self, other: &Body) -> bool {
|
||||||
match *self {
|
match *self {
|
||||||
Body::None => matches!(*other, Body::None),
|
AnyBody::None => matches!(*other, AnyBody::None),
|
||||||
Body::Empty => matches!(*other, Body::Empty),
|
AnyBody::Empty => matches!(*other, AnyBody::Empty),
|
||||||
Body::Bytes(ref b) => match *other {
|
AnyBody::Bytes(ref b) => match *other {
|
||||||
Body::Bytes(ref b2) => b == b2,
|
AnyBody::Bytes(ref b2) => b == b2,
|
||||||
_ => false,
|
_ => false,
|
||||||
},
|
},
|
||||||
Body::Message(_) => false,
|
AnyBody::Message(_) => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for Body {
|
impl fmt::Debug for AnyBody {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match *self {
|
match *self {
|
||||||
Body::None => write!(f, "Body::None"),
|
AnyBody::None => write!(f, "AnyBody::None"),
|
||||||
Body::Empty => write!(f, "Body::Empty"),
|
AnyBody::Empty => write!(f, "AnyBody::Empty"),
|
||||||
Body::Bytes(ref b) => write!(f, "Body::Bytes({:?})", b),
|
AnyBody::Bytes(ref b) => write!(f, "AnyBody::Bytes({:?})", b),
|
||||||
Body::Message(_) => write!(f, "Body::Message(_)"),
|
AnyBody::Message(_) => write!(f, "AnyBody::Message(_)"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&'static str> for Body {
|
impl From<&'static str> for AnyBody {
|
||||||
fn from(s: &'static str) -> Body {
|
fn from(s: &'static str) -> Body {
|
||||||
Body::Bytes(Bytes::from_static(s.as_ref()))
|
AnyBody::Bytes(Bytes::from_static(s.as_ref()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&'static [u8]> for Body {
|
impl From<&'static [u8]> for AnyBody {
|
||||||
fn from(s: &'static [u8]) -> Body {
|
fn from(s: &'static [u8]) -> Body {
|
||||||
Body::Bytes(Bytes::from_static(s))
|
AnyBody::Bytes(Bytes::from_static(s))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Vec<u8>> for Body {
|
impl From<Vec<u8>> for AnyBody {
|
||||||
fn from(vec: Vec<u8>) -> Body {
|
fn from(vec: Vec<u8>) -> Body {
|
||||||
Body::Bytes(Bytes::from(vec))
|
AnyBody::Bytes(Bytes::from(vec))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<String> for Body {
|
impl From<String> for AnyBody {
|
||||||
fn from(s: String) -> Body {
|
fn from(s: String) -> Body {
|
||||||
s.into_bytes().into()
|
s.into_bytes().into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> From<&'a String> for Body {
|
impl From<&'_ String> for AnyBody {
|
||||||
fn from(s: &'a String) -> Body {
|
fn from(s: &String) -> Body {
|
||||||
Body::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&s)))
|
AnyBody::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&s)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Bytes> for Body {
|
impl From<Cow<'_, str>> for AnyBody {
|
||||||
|
fn from(s: Cow<'_, str>) -> Body {
|
||||||
|
match s {
|
||||||
|
Cow::Owned(s) => AnyBody::from(s),
|
||||||
|
Cow::Borrowed(s) => {
|
||||||
|
AnyBody::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(s)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Bytes> for AnyBody {
|
||||||
fn from(s: Bytes) -> Body {
|
fn from(s: Bytes) -> Body {
|
||||||
Body::Bytes(s)
|
AnyBody::Bytes(s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<BytesMut> for Body {
|
impl From<BytesMut> for AnyBody {
|
||||||
fn from(s: BytesMut) -> Body {
|
fn from(s: BytesMut) -> Body {
|
||||||
Body::Bytes(s.freeze())
|
AnyBody::Bytes(s.freeze())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<serde_json::Value> for Body {
|
impl<S> From<SizedStream<S>> for AnyBody
|
||||||
fn from(v: serde_json::Value) -> Body {
|
|
||||||
Body::Bytes(v.to_string().into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S> From<SizedStream<S>> for Body
|
|
||||||
where
|
where
|
||||||
S: Stream<Item = Result<Bytes, Error>> + Unpin + 'static,
|
S: Stream<Item = Result<Bytes, Error>> + 'static,
|
||||||
{
|
{
|
||||||
fn from(s: SizedStream<S>) -> Body {
|
fn from(s: SizedStream<S>) -> Body {
|
||||||
Body::from_message(s)
|
AnyBody::from_message(s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, E> From<BodyStream<S>> for Body
|
impl<S, E> From<BodyStream<S>> for AnyBody
|
||||||
where
|
where
|
||||||
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
|
S: Stream<Item = Result<Bytes, E>> + 'static,
|
||||||
E: Into<Error> + 'static,
|
E: Into<Error> + 'static,
|
||||||
{
|
{
|
||||||
fn from(s: BodyStream<S>) -> Body {
|
fn from(s: BodyStream<S>) -> Body {
|
||||||
Body::from_message(s)
|
AnyBody::from_message(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A boxed message body with boxed errors.
|
||||||
|
pub struct BoxAnyBody(Pin<Box<dyn MessageBody<Error = Box<dyn StdError + 'static>>>>);
|
||||||
|
|
||||||
|
impl BoxAnyBody {
|
||||||
|
/// Boxes a `MessageBody` and any errors it generates.
|
||||||
|
pub fn from_body<B>(body: B) -> Self
|
||||||
|
where
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Box<dyn StdError + 'static>>,
|
||||||
|
{
|
||||||
|
let body = MessageBodyMapErr::new(body, Into::into);
|
||||||
|
Self(Box::pin(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a mutable pinned reference to the inner message body type.
|
||||||
|
pub fn as_pin_mut(
|
||||||
|
&mut self,
|
||||||
|
) -> Pin<&mut (dyn MessageBody<Error = Box<dyn StdError + 'static>>)> {
|
||||||
|
self.0.as_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for BoxAnyBody {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("BoxAnyBody(dyn MessageBody)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MessageBody for BoxAnyBody {
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn size(&self) -> BodySize {
|
||||||
|
self.0.size()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_next(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
|
// TODO: MSRV 1.51: poll_map_err
|
||||||
|
match ready!(self.0.as_mut().poll_next(cx)) {
|
||||||
|
Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
|
||||||
|
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
|
||||||
|
None => Poll::Ready(None),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,21 +5,25 @@ use std::{
|
|||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures_core::{ready, Stream};
|
use futures_core::{ready, Stream};
|
||||||
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
use super::{BodySize, MessageBody};
|
use super::{BodySize, MessageBody};
|
||||||
|
|
||||||
/// Streaming response wrapper.
|
pin_project! {
|
||||||
///
|
/// Streaming response wrapper.
|
||||||
/// Response does not contain `Content-Length` header and appropriate transfer encoding is used.
|
///
|
||||||
pub struct BodyStream<S: Unpin> {
|
/// Response does not contain `Content-Length` header and appropriate transfer encoding is used.
|
||||||
stream: S,
|
pub struct BodyStream<S> {
|
||||||
|
#[pin]
|
||||||
|
stream: S,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, E> BodyStream<S>
|
impl<S, E> BodyStream<S>
|
||||||
where
|
where
|
||||||
S: Stream<Item = Result<Bytes, E>> + Unpin,
|
S: Stream<Item = Result<Bytes, E>>,
|
||||||
E: Into<Error>,
|
E: Into<Error>,
|
||||||
{
|
{
|
||||||
pub fn new(stream: S) -> Self {
|
pub fn new(stream: S) -> Self {
|
||||||
@ -29,9 +33,11 @@ where
|
|||||||
|
|
||||||
impl<S, E> MessageBody for BodyStream<S>
|
impl<S, E> MessageBody for BodyStream<S>
|
||||||
where
|
where
|
||||||
S: Stream<Item = Result<Bytes, E>> + Unpin,
|
S: Stream<Item = Result<Bytes, E>>,
|
||||||
E: Into<Error>,
|
E: Into<Error>,
|
||||||
{
|
{
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Stream
|
BodySize::Stream
|
||||||
}
|
}
|
||||||
@ -44,11 +50,11 @@ where
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
loop {
|
loop {
|
||||||
let stream = &mut self.as_mut().stream;
|
let stream = self.as_mut().project().stream;
|
||||||
|
|
||||||
let chunk = match ready!(Pin::new(stream).poll_next(cx)) {
|
let chunk = match ready!(stream.poll_next(cx)) {
|
||||||
Some(Ok(ref bytes)) if bytes.is_empty() => continue,
|
Some(Ok(ref bytes)) if bytes.is_empty() => continue,
|
||||||
opt => opt.map(|res| res.map_err(Into::into)),
|
opt => opt.map(|res| res.map_err(Into::into)),
|
||||||
};
|
};
|
||||||
@ -57,3 +63,49 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use actix_rt::pin;
|
||||||
|
use actix_utils::future::poll_fn;
|
||||||
|
use futures_util::stream;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::body::to_bytes;
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn skips_empty_chunks() {
|
||||||
|
let body = BodyStream::new(stream::iter(
|
||||||
|
["1", "", "2"]
|
||||||
|
.iter()
|
||||||
|
.map(|&v| Ok(Bytes::from(v)) as Result<Bytes, ()>),
|
||||||
|
));
|
||||||
|
pin!(body);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
poll_fn(|cx| body.as_mut().poll_next(cx))
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.ok(),
|
||||||
|
Some(Bytes::from("1")),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
poll_fn(|cx| body.as_mut().poll_next(cx))
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.ok(),
|
||||||
|
Some(Bytes::from("2")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn read_to_bytes() {
|
||||||
|
let body = BodyStream::new(stream::iter(
|
||||||
|
["1", "", "2"]
|
||||||
|
.iter()
|
||||||
|
.map(|&v| Ok(Bytes::from(v)) as Result<Bytes, ()>),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(to_bytes(body).await.ok(), Some(Bytes::from("12")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,32 +1,37 @@
|
|||||||
//! [`MessageBody`] trait and foreign implementations.
|
//! [`MessageBody`] trait and foreign implementations.
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
|
convert::Infallible,
|
||||||
mem,
|
mem,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
|
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use futures_core::ready;
|
||||||
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
use super::BodySize;
|
use super::BodySize;
|
||||||
|
|
||||||
/// Type that implement this trait can be streamed to a peer.
|
/// An interface for response bodies.
|
||||||
pub trait MessageBody {
|
pub trait MessageBody {
|
||||||
|
type Error;
|
||||||
|
|
||||||
|
/// Body size hint.
|
||||||
fn size(&self) -> BodySize;
|
fn size(&self) -> BodySize;
|
||||||
|
|
||||||
|
/// Attempt to pull out the next chunk of body bytes.
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>>;
|
) -> Poll<Option<Result<Bytes, Self::Error>>>;
|
||||||
|
|
||||||
downcast_get_type_id!();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
downcast!(MessageBody);
|
|
||||||
|
|
||||||
impl MessageBody for () {
|
impl MessageBody for () {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Empty
|
BodySize::Empty
|
||||||
}
|
}
|
||||||
@ -34,12 +39,18 @@ impl MessageBody for () {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: MessageBody + Unpin> MessageBody for Box<T> {
|
impl<B> MessageBody for Box<B>
|
||||||
|
where
|
||||||
|
B: MessageBody + Unpin,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
|
type Error = B::Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
self.as_ref().size()
|
self.as_ref().size()
|
||||||
}
|
}
|
||||||
@ -47,12 +58,33 @@ impl<T: MessageBody + Unpin> MessageBody for Box<T> {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
Pin::new(self.get_mut().as_mut()).poll_next(cx)
|
Pin::new(self.get_mut().as_mut()).poll_next(cx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<B> MessageBody for Pin<Box<B>>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
|
type Error = B::Error;
|
||||||
|
|
||||||
|
fn size(&self) -> BodySize {
|
||||||
|
self.as_ref().size()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_next(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
|
self.as_mut().poll_next(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl MessageBody for Bytes {
|
impl MessageBody for Bytes {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
@ -60,7 +92,7 @@ impl MessageBody for Bytes {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
@ -70,6 +102,8 @@ impl MessageBody for Bytes {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for BytesMut {
|
impl MessageBody for BytesMut {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
@ -77,7 +111,7 @@ impl MessageBody for BytesMut {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
@ -87,6 +121,8 @@ impl MessageBody for BytesMut {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for &'static str {
|
impl MessageBody for &'static str {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
@ -94,7 +130,7 @@ impl MessageBody for &'static str {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
@ -106,6 +142,8 @@ impl MessageBody for &'static str {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for Vec<u8> {
|
impl MessageBody for Vec<u8> {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
@ -113,7 +151,7 @@ impl MessageBody for Vec<u8> {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
@ -123,6 +161,8 @@ impl MessageBody for Vec<u8> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBody for String {
|
impl MessageBody for String {
|
||||||
|
type Error = Infallible;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len() as u64)
|
BodySize::Sized(self.len() as u64)
|
||||||
}
|
}
|
||||||
@ -130,7 +170,7 @@ impl MessageBody for String {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
_: &mut Context<'_>,
|
_: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
Poll::Ready(None)
|
Poll::Ready(None)
|
||||||
} else {
|
} else {
|
||||||
@ -140,3 +180,53 @@ impl MessageBody for String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pin_project! {
|
||||||
|
pub(crate) struct MessageBodyMapErr<B, F> {
|
||||||
|
#[pin]
|
||||||
|
body: B,
|
||||||
|
mapper: Option<F>,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<B, F, E> MessageBodyMapErr<B, F>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
F: FnOnce(B::Error) -> E,
|
||||||
|
{
|
||||||
|
pub(crate) fn new(body: B, mapper: F) -> Self {
|
||||||
|
Self {
|
||||||
|
body,
|
||||||
|
mapper: Some(mapper),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<B, F, E> MessageBody for MessageBodyMapErr<B, F>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
F: FnOnce(B::Error) -> E,
|
||||||
|
{
|
||||||
|
type Error = E;
|
||||||
|
|
||||||
|
fn size(&self) -> BodySize {
|
||||||
|
self.body.size()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_next(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
|
let this = self.as_mut().project();
|
||||||
|
|
||||||
|
match ready!(this.body.poll_next(cx)) {
|
||||||
|
Some(Err(err)) => {
|
||||||
|
let f = self.as_mut().project().mapper.take().unwrap();
|
||||||
|
let mapped_err = (f)(err);
|
||||||
|
Poll::Ready(Some(Err(mapped_err)))
|
||||||
|
}
|
||||||
|
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
|
||||||
|
None => Poll::Ready(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,5 +1,12 @@
|
|||||||
//! Traits and structures to aid consuming and writing HTTP payloads.
|
//! Traits and structures to aid consuming and writing HTTP payloads.
|
||||||
|
|
||||||
|
use std::task::Poll;
|
||||||
|
|
||||||
|
use actix_rt::pin;
|
||||||
|
use actix_utils::future::poll_fn;
|
||||||
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use futures_core::ready;
|
||||||
|
|
||||||
#[allow(clippy::module_inception)]
|
#[allow(clippy::module_inception)]
|
||||||
mod body;
|
mod body;
|
||||||
mod body_stream;
|
mod body_stream;
|
||||||
@ -8,13 +15,58 @@ mod response_body;
|
|||||||
mod size;
|
mod size;
|
||||||
mod sized_stream;
|
mod sized_stream;
|
||||||
|
|
||||||
pub use self::body::Body;
|
pub use self::body::{AnyBody, Body, BoxAnyBody};
|
||||||
pub use self::body_stream::BodyStream;
|
pub use self::body_stream::BodyStream;
|
||||||
pub use self::message_body::MessageBody;
|
pub use self::message_body::MessageBody;
|
||||||
|
pub(crate) use self::message_body::MessageBodyMapErr;
|
||||||
pub use self::response_body::ResponseBody;
|
pub use self::response_body::ResponseBody;
|
||||||
pub use self::size::BodySize;
|
pub use self::size::BodySize;
|
||||||
pub use self::sized_stream::SizedStream;
|
pub use self::sized_stream::SizedStream;
|
||||||
|
|
||||||
|
/// Collects the body produced by a `MessageBody` implementation into `Bytes`.
|
||||||
|
///
|
||||||
|
/// Any errors produced by the body stream are returned immediately.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_http::body::{Body, to_bytes};
|
||||||
|
/// use bytes::Bytes;
|
||||||
|
///
|
||||||
|
/// # async fn test_to_bytes() {
|
||||||
|
/// let body = Body::Empty;
|
||||||
|
/// let bytes = to_bytes(body).await.unwrap();
|
||||||
|
/// assert!(bytes.is_empty());
|
||||||
|
///
|
||||||
|
/// let body = Body::Bytes(Bytes::from_static(b"123"));
|
||||||
|
/// let bytes = to_bytes(body).await.unwrap();
|
||||||
|
/// assert_eq!(bytes, b"123"[..]);
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
pub async fn to_bytes<B: MessageBody>(body: B) -> Result<Bytes, B::Error> {
|
||||||
|
let cap = match body.size() {
|
||||||
|
BodySize::None | BodySize::Empty | BodySize::Sized(0) => return Ok(Bytes::new()),
|
||||||
|
BodySize::Sized(size) => size as usize,
|
||||||
|
BodySize::Stream => 32_768,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut buf = BytesMut::with_capacity(cap);
|
||||||
|
|
||||||
|
pin!(body);
|
||||||
|
|
||||||
|
poll_fn(|cx| loop {
|
||||||
|
let body = body.as_mut();
|
||||||
|
|
||||||
|
match ready!(body.poll_next(cx)) {
|
||||||
|
Some(Ok(bytes)) => buf.extend_from_slice(&*bytes),
|
||||||
|
None => return Poll::Ready(Ok(())),
|
||||||
|
Some(Err(err)) => return Poll::Ready(Err(err)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(buf.freeze())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
@ -22,7 +74,6 @@ mod tests {
|
|||||||
use actix_rt::pin;
|
use actix_rt::pin;
|
||||||
use actix_utils::future::poll_fn;
|
use actix_utils::future::poll_fn;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures_util::stream;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
@ -35,15 +86,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ResponseBody<Body> {
|
|
||||||
pub(crate) fn get_ref(&self) -> &[u8] {
|
|
||||||
match *self {
|
|
||||||
ResponseBody::Body(ref b) => b.get_ref(),
|
|
||||||
ResponseBody::Other(ref b) => b.get_ref(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_static_str() {
|
async fn test_static_str() {
|
||||||
assert_eq!(Body::from("").size(), BodySize::Sized(0));
|
assert_eq!(Body::from("").size(), BodySize::Sized(0));
|
||||||
@ -174,73 +216,26 @@ mod tests {
|
|||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_serde_json() {
|
async fn test_serde_json() {
|
||||||
use serde_json::json;
|
use serde_json::{json, Value};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Body::from(serde_json::Value::String("test".into())).size(),
|
Body::from(serde_json::to_vec(&Value::String("test".to_owned())).unwrap())
|
||||||
|
.size(),
|
||||||
BodySize::Sized(6)
|
BodySize::Sized(6)
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Body::from(json!({"test-key":"test-value"})).size(),
|
Body::from(serde_json::to_vec(&json!({"test-key":"test-value"})).unwrap())
|
||||||
|
.size(),
|
||||||
BodySize::Sized(25)
|
BodySize::Sized(25)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
// down-casting used to be done with a method on MessageBody trait
|
||||||
async fn body_stream_skips_empty_chunks() {
|
// test is kept to demonstrate equivalence of Any trait
|
||||||
let body = BodyStream::new(stream::iter(
|
|
||||||
["1", "", "2"]
|
|
||||||
.iter()
|
|
||||||
.map(|&v| Ok(Bytes::from(v)) as Result<Bytes, ()>),
|
|
||||||
));
|
|
||||||
pin!(body);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
poll_fn(|cx| body.as_mut().poll_next(cx))
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.ok(),
|
|
||||||
Some(Bytes::from("1")),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
poll_fn(|cx| body.as_mut().poll_next(cx))
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.ok(),
|
|
||||||
Some(Bytes::from("2")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
mod sized_stream {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
|
||||||
async fn skips_empty_chunks() {
|
|
||||||
let body = SizedStream::new(
|
|
||||||
2,
|
|
||||||
stream::iter(["1", "", "2"].iter().map(|&v| Ok(Bytes::from(v)))),
|
|
||||||
);
|
|
||||||
pin!(body);
|
|
||||||
assert_eq!(
|
|
||||||
poll_fn(|cx| body.as_mut().poll_next(cx))
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.ok(),
|
|
||||||
Some(Bytes::from("1")),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
poll_fn(|cx| body.as_mut().poll_next(cx))
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.ok(),
|
|
||||||
Some(Bytes::from("2")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_body_casting() {
|
async fn test_body_casting() {
|
||||||
let mut body = String::from("hello cast");
|
let mut body = String::from("hello cast");
|
||||||
let resp_body: &mut dyn MessageBody = &mut body;
|
// let mut resp_body: &mut dyn MessageBody<Error = Error> = &mut body;
|
||||||
|
let resp_body: &mut dyn std::any::Any = &mut body;
|
||||||
let body = resp_body.downcast_ref::<String>().unwrap();
|
let body = resp_body.downcast_ref::<String>().unwrap();
|
||||||
assert_eq!(body, "hello cast");
|
assert_eq!(body, "hello cast");
|
||||||
let body = &mut resp_body.downcast_mut::<String>().unwrap();
|
let body = &mut resp_body.downcast_mut::<String>().unwrap();
|
||||||
@ -250,4 +245,15 @@ mod tests {
|
|||||||
let not_body = resp_body.downcast_ref::<()>();
|
let not_body = resp_body.downcast_ref::<()>();
|
||||||
assert!(not_body.is_none());
|
assert!(not_body.is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn test_to_bytes() {
|
||||||
|
let body = Body::Empty;
|
||||||
|
let bytes = to_bytes(body).await.unwrap();
|
||||||
|
assert!(bytes.is_empty());
|
||||||
|
|
||||||
|
let body = Body::Bytes(Bytes::from_static(b"123"));
|
||||||
|
let bytes = to_bytes(body).await.unwrap();
|
||||||
|
assert_eq!(bytes, b"123"[..]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures_core::Stream;
|
use futures_core::{ready, Stream};
|
||||||
use pin_project::pin_project;
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
@ -43,7 +43,13 @@ impl<B: MessageBody> ResponseBody<B> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<B: MessageBody> MessageBody for ResponseBody<B> {
|
impl<B> MessageBody for ResponseBody<B>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
match self {
|
match self {
|
||||||
ResponseBody::Body(ref body) => body.size(),
|
ResponseBody::Body(ref body) => body.size(),
|
||||||
@ -54,15 +60,16 @@ impl<B: MessageBody> MessageBody for ResponseBody<B> {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
match self.project() {
|
Stream::poll_next(self, cx)
|
||||||
ResponseBodyProj::Body(body) => body.poll_next(cx),
|
|
||||||
ResponseBodyProj::Other(body) => Pin::new(body).poll_next(cx),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<B: MessageBody> Stream for ResponseBody<B> {
|
impl<B> Stream for ResponseBody<B>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
type Item = Result<Bytes, Error>;
|
type Item = Result<Bytes, Error>;
|
||||||
|
|
||||||
fn poll_next(
|
fn poll_next(
|
||||||
@ -70,7 +77,12 @@ impl<B: MessageBody> Stream for ResponseBody<B> {
|
|||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Self::Item>> {
|
) -> Poll<Option<Self::Item>> {
|
||||||
match self.project() {
|
match self.project() {
|
||||||
ResponseBodyProj::Body(body) => body.poll_next(cx),
|
// TODO: MSRV 1.51: poll_map_err
|
||||||
|
ResponseBodyProj::Body(body) => match ready!(body.poll_next(cx)) {
|
||||||
|
Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
|
||||||
|
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
|
||||||
|
None => Poll::Ready(None),
|
||||||
|
},
|
||||||
ResponseBodyProj::Other(body) => Pin::new(body).poll_next(cx),
|
ResponseBodyProj::Other(body) => Pin::new(body).poll_next(cx),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,23 +5,27 @@ use std::{
|
|||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures_core::{ready, Stream};
|
use futures_core::{ready, Stream};
|
||||||
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
use super::{BodySize, MessageBody};
|
use super::{BodySize, MessageBody};
|
||||||
|
|
||||||
/// Known sized streaming response wrapper.
|
pin_project! {
|
||||||
///
|
/// Known sized streaming response wrapper.
|
||||||
/// This body implementation should be used if total size of stream is known. Data get sent as is
|
///
|
||||||
/// without using transfer encoding.
|
/// This body implementation should be used if total size of stream is known. Data get sent as is
|
||||||
pub struct SizedStream<S: Unpin> {
|
/// without using transfer encoding.
|
||||||
size: u64,
|
pub struct SizedStream<S> {
|
||||||
stream: S,
|
size: u64,
|
||||||
|
#[pin]
|
||||||
|
stream: S,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> SizedStream<S>
|
impl<S> SizedStream<S>
|
||||||
where
|
where
|
||||||
S: Stream<Item = Result<Bytes, Error>> + Unpin,
|
S: Stream<Item = Result<Bytes, Error>>,
|
||||||
{
|
{
|
||||||
pub fn new(size: u64, stream: S) -> Self {
|
pub fn new(size: u64, stream: S) -> Self {
|
||||||
SizedStream { size, stream }
|
SizedStream { size, stream }
|
||||||
@ -30,8 +34,10 @@ where
|
|||||||
|
|
||||||
impl<S> MessageBody for SizedStream<S>
|
impl<S> MessageBody for SizedStream<S>
|
||||||
where
|
where
|
||||||
S: Stream<Item = Result<Bytes, Error>> + Unpin,
|
S: Stream<Item = Result<Bytes, Error>>,
|
||||||
{
|
{
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.size as u64)
|
BodySize::Sized(self.size as u64)
|
||||||
}
|
}
|
||||||
@ -44,11 +50,11 @@ where
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
mut self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
loop {
|
loop {
|
||||||
let stream = &mut self.as_mut().stream;
|
let stream = self.as_mut().project().stream;
|
||||||
|
|
||||||
let chunk = match ready!(Pin::new(stream).poll_next(cx)) {
|
let chunk = match ready!(stream.poll_next(cx)) {
|
||||||
Some(Ok(ref bytes)) if bytes.is_empty() => continue,
|
Some(Ok(ref bytes)) if bytes.is_empty() => continue,
|
||||||
val => val,
|
val => val,
|
||||||
};
|
};
|
||||||
@ -57,3 +63,49 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use actix_rt::pin;
|
||||||
|
use actix_utils::future::poll_fn;
|
||||||
|
use futures_util::stream;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::body::to_bytes;
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn skips_empty_chunks() {
|
||||||
|
let body = SizedStream::new(
|
||||||
|
2,
|
||||||
|
stream::iter(["1", "", "2"].iter().map(|&v| Ok(Bytes::from(v)))),
|
||||||
|
);
|
||||||
|
|
||||||
|
pin!(body);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
poll_fn(|cx| body.as_mut().poll_next(cx))
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.ok(),
|
||||||
|
Some(Bytes::from("1")),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
poll_fn(|cx| body.as_mut().poll_next(cx))
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.ok(),
|
||||||
|
Some(Bytes::from("2")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_rt::test]
|
||||||
|
async fn read_to_bytes() {
|
||||||
|
let body = SizedStream::new(
|
||||||
|
2,
|
||||||
|
stream::iter(["1", "", "2"].iter().map(|&v| Ok(Bytes::from(v)))),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(to_bytes(body).await.ok(), Some(Bytes::from("12")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -202,11 +202,13 @@ where
|
|||||||
/// Finish service configuration and create a HTTP service for HTTP/2 protocol.
|
/// Finish service configuration and create a HTTP service for HTTP/2 protocol.
|
||||||
pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
|
pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
|
||||||
F: IntoServiceFactory<S, Request>,
|
F: IntoServiceFactory<S, 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,
|
||||||
|
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let cfg = ServiceConfig::new(
|
let cfg = ServiceConfig::new(
|
||||||
self.keep_alive,
|
self.keep_alive,
|
||||||
@ -223,11 +225,13 @@ where
|
|||||||
/// Finish service configuration and create `HttpService` instance.
|
/// Finish service configuration and create `HttpService` instance.
|
||||||
pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U>
|
pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
B: MessageBody + 'static,
|
|
||||||
F: IntoServiceFactory<S, Request>,
|
F: IntoServiceFactory<S, 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,
|
||||||
|
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let cfg = ServiceConfig::new(
|
let cfg = ServiceConfig::new(
|
||||||
self.keep_alive,
|
self.keep_alive,
|
||||||
|
@ -12,10 +12,10 @@ use bytes::Bytes;
|
|||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
use h2::client::SendRequest;
|
use h2::client::SendRequest;
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
|
||||||
use crate::h1::ClientCodec;
|
use crate::h1::ClientCodec;
|
||||||
use crate::message::{RequestHeadType, ResponseHead};
|
use crate::message::{RequestHeadType, ResponseHead};
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
|
use crate::{body::MessageBody, Error};
|
||||||
|
|
||||||
use super::error::SendRequestError;
|
use super::error::SendRequestError;
|
||||||
use super::pool::Acquired;
|
use super::pool::Acquired;
|
||||||
@ -256,8 +256,9 @@ where
|
|||||||
body: RB,
|
body: RB,
|
||||||
) -> LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>>
|
) -> LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>>
|
||||||
where
|
where
|
||||||
RB: MessageBody + 'static,
|
|
||||||
H: Into<RequestHeadType> + 'static,
|
H: Into<RequestHeadType> + 'static,
|
||||||
|
RB: MessageBody + 'static,
|
||||||
|
RB::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
match self {
|
match self {
|
||||||
|
@ -11,7 +11,6 @@ use bytes::{Bytes, BytesMut};
|
|||||||
use futures_core::{ready, Stream};
|
use futures_core::{ready, Stream};
|
||||||
use futures_util::SinkExt as _;
|
use futures_util::SinkExt as _;
|
||||||
|
|
||||||
use crate::error::PayloadError;
|
|
||||||
use crate::h1;
|
use crate::h1;
|
||||||
use crate::http::{
|
use crate::http::{
|
||||||
header::{HeaderMap, IntoHeaderValue, EXPECT, HOST},
|
header::{HeaderMap, IntoHeaderValue, EXPECT, HOST},
|
||||||
@ -19,6 +18,7 @@ use crate::http::{
|
|||||||
};
|
};
|
||||||
use crate::message::{RequestHeadType, ResponseHead};
|
use crate::message::{RequestHeadType, ResponseHead};
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
|
use crate::{error::PayloadError, Error};
|
||||||
|
|
||||||
use super::connection::{ConnectionIo, H1Connection};
|
use super::connection::{ConnectionIo, H1Connection};
|
||||||
use super::error::{ConnectError, SendRequestError};
|
use super::error::{ConnectError, SendRequestError};
|
||||||
@ -32,6 +32,7 @@ pub(crate) async fn send_request<Io, B>(
|
|||||||
where
|
where
|
||||||
Io: ConnectionIo,
|
Io: ConnectionIo,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
// set request host header
|
// set request host header
|
||||||
if !head.as_ref().headers.contains_key(HOST)
|
if !head.as_ref().headers.contains_key(HOST)
|
||||||
@ -154,6 +155,7 @@ pub(crate) async fn send_body<Io, B>(
|
|||||||
where
|
where
|
||||||
Io: ConnectionIo,
|
Io: ConnectionIo,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
actix_rt::pin!(body);
|
actix_rt::pin!(body);
|
||||||
|
|
||||||
@ -161,9 +163,10 @@ where
|
|||||||
while !eof {
|
while !eof {
|
||||||
while !eof && !framed.as_ref().is_write_buf_full() {
|
while !eof && !framed.as_ref().is_write_buf_full() {
|
||||||
match poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
match poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
||||||
Some(result) => {
|
Some(Ok(chunk)) => {
|
||||||
framed.as_mut().write(h1::Message::Chunk(Some(result?)))?;
|
framed.as_mut().write(h1::Message::Chunk(Some(chunk)))?;
|
||||||
}
|
}
|
||||||
|
Some(Err(err)) => return Err(err.into().into()),
|
||||||
None => {
|
None => {
|
||||||
eof = true;
|
eof = true;
|
||||||
framed.as_mut().write(h1::Message::Chunk(None))?;
|
framed.as_mut().write(h1::Message::Chunk(None))?;
|
||||||
|
@ -9,14 +9,19 @@ use h2::{
|
|||||||
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
|
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
|
||||||
use http::{request::Request, Method, Version};
|
use http::{request::Request, Method, Version};
|
||||||
|
|
||||||
use crate::body::{BodySize, MessageBody};
|
use crate::{
|
||||||
use crate::header::HeaderMap;
|
body::{BodySize, MessageBody},
|
||||||
use crate::message::{RequestHeadType, ResponseHead};
|
header::HeaderMap,
|
||||||
use crate::payload::Payload;
|
message::{RequestHeadType, ResponseHead},
|
||||||
|
payload::Payload,
|
||||||
|
Error,
|
||||||
|
};
|
||||||
|
|
||||||
use super::config::ConnectorConfig;
|
use super::{
|
||||||
use super::connection::{ConnectionIo, H2Connection};
|
config::ConnectorConfig,
|
||||||
use super::error::SendRequestError;
|
connection::{ConnectionIo, H2Connection},
|
||||||
|
error::SendRequestError,
|
||||||
|
};
|
||||||
|
|
||||||
pub(crate) async fn send_request<Io, B>(
|
pub(crate) async fn send_request<Io, B>(
|
||||||
mut io: H2Connection<Io>,
|
mut io: H2Connection<Io>,
|
||||||
@ -26,6 +31,7 @@ pub(crate) async fn send_request<Io, B>(
|
|||||||
where
|
where
|
||||||
Io: ConnectionIo,
|
Io: ConnectionIo,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
trace!("Sending client request: {:?} {:?}", head, body.size());
|
trace!("Sending client request: {:?} {:?}", head, body.size());
|
||||||
|
|
||||||
@ -125,10 +131,14 @@ where
|
|||||||
Ok((head, payload))
|
Ok((head, payload))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_body<B: MessageBody>(
|
async fn send_body<B>(
|
||||||
body: B,
|
body: B,
|
||||||
mut send: SendStream<Bytes>,
|
mut send: SendStream<Bytes>,
|
||||||
) -> Result<(), SendRequestError> {
|
) -> Result<(), SendRequestError>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
let mut buf = None;
|
let mut buf = None;
|
||||||
actix_rt::pin!(body);
|
actix_rt::pin!(body);
|
||||||
loop {
|
loop {
|
||||||
@ -138,7 +148,7 @@ async fn send_body<B: MessageBody>(
|
|||||||
send.reserve_capacity(b.len());
|
send.reserve_capacity(b.len());
|
||||||
buf = Some(b);
|
buf = Some(b);
|
||||||
}
|
}
|
||||||
Some(Err(e)) => return Err(e.into()),
|
Some(Err(e)) => return Err(e.into().into()),
|
||||||
None => {
|
None => {
|
||||||
if let Err(e) = send.send_data(Bytes::new(), true) {
|
if let Err(e) = send.send_data(Bytes::new(), true) {
|
||||||
return Err(e.into());
|
return Err(e.into());
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
//! Stream encoders.
|
//! Stream encoders.
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
|
error::Error as StdError,
|
||||||
future::Future,
|
future::Future,
|
||||||
io::{self, Write as _},
|
io::{self, Write as _},
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
@ -10,12 +11,13 @@ use std::{
|
|||||||
use actix_rt::task::{spawn_blocking, JoinHandle};
|
use actix_rt::task::{spawn_blocking, JoinHandle};
|
||||||
use brotli2::write::BrotliEncoder;
|
use brotli2::write::BrotliEncoder;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
use derive_more::Display;
|
||||||
use flate2::write::{GzEncoder, ZlibEncoder};
|
use flate2::write::{GzEncoder, ZlibEncoder};
|
||||||
use futures_core::ready;
|
use futures_core::ready;
|
||||||
use pin_project::pin_project;
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
body::{Body, BodySize, MessageBody, ResponseBody},
|
body::{Body, BodySize, BoxAnyBody, MessageBody, ResponseBody},
|
||||||
http::{
|
http::{
|
||||||
header::{ContentEncoding, CONTENT_ENCODING},
|
header::{ContentEncoding, CONTENT_ENCODING},
|
||||||
HeaderValue, StatusCode,
|
HeaderValue, StatusCode,
|
||||||
@ -92,10 +94,16 @@ impl<B: MessageBody> Encoder<B> {
|
|||||||
enum EncoderBody<B> {
|
enum EncoderBody<B> {
|
||||||
Bytes(Bytes),
|
Bytes(Bytes),
|
||||||
Stream(#[pin] B),
|
Stream(#[pin] B),
|
||||||
BoxedStream(Box<dyn MessageBody + Unpin>),
|
BoxedStream(BoxAnyBody),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<B: MessageBody> MessageBody for EncoderBody<B> {
|
impl<B> MessageBody for EncoderBody<B>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
|
type Error = EncoderError<B::Error>;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
match self {
|
match self {
|
||||||
EncoderBody::Bytes(ref b) => b.size(),
|
EncoderBody::Bytes(ref b) => b.size(),
|
||||||
@ -107,7 +115,7 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
match self.project() {
|
match self.project() {
|
||||||
EncoderBodyProj::Bytes(b) => {
|
EncoderBodyProj::Bytes(b) => {
|
||||||
if b.is_empty() {
|
if b.is_empty() {
|
||||||
@ -116,15 +124,32 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
|
|||||||
Poll::Ready(Some(Ok(std::mem::take(b))))
|
Poll::Ready(Some(Ok(std::mem::take(b))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EncoderBodyProj::Stream(b) => b.poll_next(cx),
|
// TODO: MSRV 1.51: poll_map_err
|
||||||
|
EncoderBodyProj::Stream(b) => match ready!(b.poll_next(cx)) {
|
||||||
|
Some(Err(err)) => Poll::Ready(Some(Err(EncoderError::Body(err)))),
|
||||||
|
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
|
||||||
|
None => Poll::Ready(None),
|
||||||
|
},
|
||||||
EncoderBodyProj::BoxedStream(ref mut b) => {
|
EncoderBodyProj::BoxedStream(ref mut b) => {
|
||||||
Pin::new(b.as_mut()).poll_next(cx)
|
match ready!(b.as_pin_mut().poll_next(cx)) {
|
||||||
|
Some(Err(err)) => {
|
||||||
|
Poll::Ready(Some(Err(EncoderError::Boxed(err.into()))))
|
||||||
|
}
|
||||||
|
Some(Ok(val)) => Poll::Ready(Some(Ok(val))),
|
||||||
|
None => Poll::Ready(None),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<B: MessageBody> MessageBody for Encoder<B> {
|
impl<B> MessageBody for Encoder<B>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
|
type Error = EncoderError<B::Error>;
|
||||||
|
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
if self.encoder.is_none() {
|
if self.encoder.is_none() {
|
||||||
self.body.size()
|
self.body.size()
|
||||||
@ -136,7 +161,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
|||||||
fn poll_next(
|
fn poll_next(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||||
let mut this = self.project();
|
let mut this = self.project();
|
||||||
loop {
|
loop {
|
||||||
if *this.eof {
|
if *this.eof {
|
||||||
@ -144,8 +169,9 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ref mut fut) = this.fut {
|
if let Some(ref mut fut) = this.fut {
|
||||||
let mut encoder =
|
let mut encoder = ready!(Pin::new(fut).poll(cx))
|
||||||
ready!(Pin::new(fut).poll(cx)).map_err(|_| BlockingError)??;
|
.map_err(|_| EncoderError::Blocking(BlockingError))?
|
||||||
|
.map_err(EncoderError::Io)?;
|
||||||
|
|
||||||
let chunk = encoder.take();
|
let chunk = encoder.take();
|
||||||
*this.encoder = Some(encoder);
|
*this.encoder = Some(encoder);
|
||||||
@ -164,7 +190,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
|||||||
Some(Ok(chunk)) => {
|
Some(Ok(chunk)) => {
|
||||||
if let Some(mut encoder) = this.encoder.take() {
|
if let Some(mut encoder) = this.encoder.take() {
|
||||||
if chunk.len() < MAX_CHUNK_SIZE_ENCODE_IN_PLACE {
|
if chunk.len() < MAX_CHUNK_SIZE_ENCODE_IN_PLACE {
|
||||||
encoder.write(&chunk)?;
|
encoder.write(&chunk).map_err(EncoderError::Io)?;
|
||||||
let chunk = encoder.take();
|
let chunk = encoder.take();
|
||||||
*this.encoder = Some(encoder);
|
*this.encoder = Some(encoder);
|
||||||
|
|
||||||
@ -184,7 +210,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
|||||||
|
|
||||||
None => {
|
None => {
|
||||||
if let Some(encoder) = this.encoder.take() {
|
if let Some(encoder) = this.encoder.take() {
|
||||||
let chunk = encoder.finish()?;
|
let chunk = encoder.finish().map_err(EncoderError::Io)?;
|
||||||
if chunk.is_empty() {
|
if chunk.is_empty() {
|
||||||
return Poll::Ready(None);
|
return Poll::Ready(None);
|
||||||
} else {
|
} else {
|
||||||
@ -283,3 +309,36 @@ impl ContentEncoder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Display)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum EncoderError<E> {
|
||||||
|
#[display(fmt = "body")]
|
||||||
|
Body(E),
|
||||||
|
|
||||||
|
#[display(fmt = "boxed")]
|
||||||
|
Boxed(Error),
|
||||||
|
|
||||||
|
#[display(fmt = "blocking")]
|
||||||
|
Blocking(BlockingError),
|
||||||
|
|
||||||
|
#[display(fmt = "io")]
|
||||||
|
Io(io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E: StdError> StdError for EncoderError<E> {
|
||||||
|
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E: Into<Error>> From<EncoderError<E>> for Error {
|
||||||
|
fn from(err: EncoderError<E>) -> Self {
|
||||||
|
match err {
|
||||||
|
EncoderError::Body(err) => err.into(),
|
||||||
|
EncoderError::Boxed(err) => err,
|
||||||
|
EncoderError::Blocking(err) => err.into(),
|
||||||
|
EncoderError::Io(err) => err.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,33 +1,21 @@
|
|||||||
//! Error and Result module
|
//! Error and Result module
|
||||||
|
|
||||||
use std::cell::RefCell;
|
use std::{
|
||||||
use std::io::Write;
|
error::Error as StdError,
|
||||||
use std::str::Utf8Error;
|
fmt,
|
||||||
use std::string::FromUtf8Error;
|
io::{self, Write as _},
|
||||||
use std::{fmt, io, result};
|
str::Utf8Error,
|
||||||
|
string::FromUtf8Error,
|
||||||
|
};
|
||||||
|
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use derive_more::{Display, From};
|
use derive_more::{Display, Error, From};
|
||||||
use http::uri::InvalidUri;
|
use http::{header, uri::InvalidUri, StatusCode};
|
||||||
use http::{header, Error as HttpError, StatusCode};
|
|
||||||
use serde::de::value::Error as DeError;
|
use serde::de::value::Error as DeError;
|
||||||
use serde_json::error::Error as JsonError;
|
|
||||||
use serde_urlencoded::ser::Error as FormError;
|
|
||||||
|
|
||||||
use crate::body::Body;
|
use crate::{body::Body, helpers::Writer, Response};
|
||||||
use crate::helpers::Writer;
|
|
||||||
use crate::response::{Response, ResponseBuilder};
|
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
pub use http::Error as HttpError;
|
||||||
pub use crate::cookie::ParseError as CookieParseError;
|
|
||||||
|
|
||||||
/// A specialized [`std::result::Result`]
|
|
||||||
/// for actix web operations
|
|
||||||
///
|
|
||||||
/// This typedef is generally used to avoid writing out
|
|
||||||
/// `actix_http::error::Error` directly and is otherwise a direct mapping to
|
|
||||||
/// `Result`.
|
|
||||||
pub type Result<T, E = Error> = result::Result<T, E>;
|
|
||||||
|
|
||||||
/// General purpose actix web error.
|
/// General purpose actix web error.
|
||||||
///
|
///
|
||||||
@ -55,19 +43,21 @@ impl Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Error that can be converted to `Response`
|
/// Errors that can generate responses.
|
||||||
pub trait ResponseError: fmt::Debug + fmt::Display {
|
pub trait ResponseError: fmt::Debug + fmt::Display {
|
||||||
/// Response's status code
|
/// Returns appropriate status code for error.
|
||||||
///
|
///
|
||||||
/// Internal server error is generated by default.
|
/// A 500 Internal Server Error is used by default. If [error_response](Self::error_response) is
|
||||||
|
/// also implemented and does not call `self.status_code()`, then this will not be used.
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
StatusCode::INTERNAL_SERVER_ERROR
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create response for error
|
/// Creates full response for error.
|
||||||
///
|
///
|
||||||
/// Internal server error is generated by default.
|
/// By default, the generated response uses a 500 Internal Server Error status code, a
|
||||||
fn error_response(&self) -> Response {
|
/// `Content-Type` of `text/plain`, and the body is set to `Self`'s `Display` impl.
|
||||||
|
fn error_response(&self) -> Response<Body> {
|
||||||
let mut resp = Response::new(self.status_code());
|
let mut resp = Response::new(self.status_code());
|
||||||
let mut buf = BytesMut::new();
|
let mut buf = BytesMut::new();
|
||||||
let _ = write!(Writer(&mut buf), "{}", self);
|
let _ = write!(Writer(&mut buf), "{}", self);
|
||||||
@ -109,14 +99,13 @@ impl From<()> for Error {
|
|||||||
|
|
||||||
impl From<std::convert::Infallible> for Error {
|
impl From<std::convert::Infallible> for Error {
|
||||||
fn from(_: std::convert::Infallible) -> Self {
|
fn from(_: std::convert::Infallible) -> Self {
|
||||||
// `std::convert::Infallible` indicates an error
|
// hint that an error that will never happen
|
||||||
// that will never happen
|
|
||||||
unreachable!()
|
unreachable!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert `Error` to a `Response` instance
|
/// Convert `Error` to a `Response` instance
|
||||||
impl From<Error> for Response {
|
impl From<Error> for Response<Body> {
|
||||||
fn from(err: Error) -> Self {
|
fn from(err: Error) -> Self {
|
||||||
Response::from_error(err)
|
Response::from_error(err)
|
||||||
}
|
}
|
||||||
@ -131,35 +120,17 @@ impl<T: ResponseError + 'static> From<T> for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert Response to a Error
|
#[derive(Debug, Display, Error)]
|
||||||
impl From<Response> for Error {
|
#[display(fmt = "Unknown Error")]
|
||||||
fn from(res: Response) -> Error {
|
|
||||||
InternalError::from_response("", res).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convert ResponseBuilder to a Error
|
|
||||||
impl From<ResponseBuilder> for Error {
|
|
||||||
fn from(mut res: ResponseBuilder) -> Error {
|
|
||||||
InternalError::from_response("", res.finish()).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Display)]
|
|
||||||
#[display(fmt = "UnknownError")]
|
|
||||||
struct UnitError;
|
struct UnitError;
|
||||||
|
|
||||||
|
impl ResponseError for Box<dyn StdError + 'static> {}
|
||||||
|
|
||||||
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`UnitError`].
|
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`UnitError`].
|
||||||
impl ResponseError for UnitError {}
|
impl ResponseError for UnitError {}
|
||||||
|
|
||||||
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`JsonError`].
|
|
||||||
impl ResponseError for JsonError {}
|
|
||||||
|
|
||||||
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`FormError`].
|
|
||||||
impl ResponseError for FormError {}
|
|
||||||
|
|
||||||
#[cfg(feature = "openssl")]
|
|
||||||
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`actix_tls::accept::openssl::SslError`].
|
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] for [`actix_tls::accept::openssl::SslError`].
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
impl ResponseError for actix_tls::accept::openssl::SslError {}
|
impl ResponseError for actix_tls::accept::openssl::SslError {}
|
||||||
|
|
||||||
/// Returns [`StatusCode::BAD_REQUEST`] for [`DeError`].
|
/// Returns [`StatusCode::BAD_REQUEST`] for [`DeError`].
|
||||||
@ -201,38 +172,47 @@ impl ResponseError for header::InvalidHeaderValue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A set of errors that can occur during parsing HTTP streams
|
/// A set of errors that can occur during parsing HTTP streams.
|
||||||
#[derive(Debug, Display)]
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum ParseError {
|
pub enum ParseError {
|
||||||
/// An invalid `Method`, such as `GE.T`.
|
/// An invalid `Method`, such as `GE.T`.
|
||||||
#[display(fmt = "Invalid Method specified")]
|
#[display(fmt = "Invalid Method specified")]
|
||||||
Method,
|
Method,
|
||||||
|
|
||||||
/// An invalid `Uri`, such as `exam ple.domain`.
|
/// An invalid `Uri`, such as `exam ple.domain`.
|
||||||
#[display(fmt = "Uri error: {}", _0)]
|
#[display(fmt = "Uri error: {}", _0)]
|
||||||
Uri(InvalidUri),
|
Uri(InvalidUri),
|
||||||
|
|
||||||
/// An invalid `HttpVersion`, such as `HTP/1.1`
|
/// An invalid `HttpVersion`, such as `HTP/1.1`
|
||||||
#[display(fmt = "Invalid HTTP version specified")]
|
#[display(fmt = "Invalid HTTP version specified")]
|
||||||
Version,
|
Version,
|
||||||
|
|
||||||
/// An invalid `Header`.
|
/// An invalid `Header`.
|
||||||
#[display(fmt = "Invalid Header provided")]
|
#[display(fmt = "Invalid Header provided")]
|
||||||
Header,
|
Header,
|
||||||
|
|
||||||
/// A message head is too large to be reasonable.
|
/// A message head is too large to be reasonable.
|
||||||
#[display(fmt = "Message head is too large")]
|
#[display(fmt = "Message head is too large")]
|
||||||
TooLarge,
|
TooLarge,
|
||||||
|
|
||||||
/// A message reached EOF, but is not complete.
|
/// A message reached EOF, but is not complete.
|
||||||
#[display(fmt = "Message is incomplete")]
|
#[display(fmt = "Message is incomplete")]
|
||||||
Incomplete,
|
Incomplete,
|
||||||
|
|
||||||
/// An invalid `Status`, such as `1337 ELITE`.
|
/// An invalid `Status`, such as `1337 ELITE`.
|
||||||
#[display(fmt = "Invalid Status provided")]
|
#[display(fmt = "Invalid Status provided")]
|
||||||
Status,
|
Status,
|
||||||
|
|
||||||
/// A timeout occurred waiting for an IO event.
|
/// A timeout occurred waiting for an IO event.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[display(fmt = "Timeout")]
|
#[display(fmt = "Timeout")]
|
||||||
Timeout,
|
Timeout,
|
||||||
/// An `io::Error` that occurred while trying to read or write to a network
|
|
||||||
/// stream.
|
/// An `io::Error` that occurred while trying to read or write to a network stream.
|
||||||
#[display(fmt = "IO error: {}", _0)]
|
#[display(fmt = "IO error: {}", _0)]
|
||||||
Io(io::Error),
|
Io(io::Error),
|
||||||
|
|
||||||
/// Parsing a field as string failed
|
/// Parsing a field as string failed
|
||||||
#[display(fmt = "UTF8 error: {}", _0)]
|
#[display(fmt = "UTF8 error: {}", _0)]
|
||||||
Utf8(Utf8Error),
|
Utf8(Utf8Error),
|
||||||
@ -284,17 +264,16 @@ impl From<httparse::Error> for ParseError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A set of errors that can occur running blocking tasks in thread pool.
|
/// A set of errors that can occur running blocking tasks in thread pool.
|
||||||
#[derive(Debug, Display)]
|
#[derive(Debug, Display, Error)]
|
||||||
#[display(fmt = "Blocking thread pool is gone")]
|
#[display(fmt = "Blocking thread pool is gone")]
|
||||||
pub struct BlockingError;
|
pub struct BlockingError;
|
||||||
|
|
||||||
impl std::error::Error for BlockingError {}
|
|
||||||
|
|
||||||
/// `InternalServerError` for `BlockingError`
|
/// `InternalServerError` for `BlockingError`
|
||||||
impl ResponseError for BlockingError {}
|
impl ResponseError for BlockingError {}
|
||||||
|
|
||||||
#[derive(Display, Debug)]
|
/// A set of errors that can occur during payload parsing.
|
||||||
/// A set of errors that can occur during payload parsing
|
#[derive(Debug, Display)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum PayloadError {
|
pub enum PayloadError {
|
||||||
/// A payload reached EOF, but is not complete.
|
/// A payload reached EOF, but is not complete.
|
||||||
#[display(
|
#[display(
|
||||||
@ -378,16 +357,9 @@ impl ResponseError for PayloadError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `cookie::ParseError`
|
/// A set of errors that can occur during dispatching HTTP requests.
|
||||||
#[cfg(feature = "cookies")]
|
#[derive(Debug, Display, Error, From)]
|
||||||
impl ResponseError for crate::cookie::ParseError {
|
#[non_exhaustive]
|
||||||
fn status_code(&self) -> StatusCode {
|
|
||||||
StatusCode::BAD_REQUEST
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Display, From)]
|
|
||||||
/// A set of errors that can occur during dispatching HTTP requests
|
|
||||||
pub enum DispatchError {
|
pub enum DispatchError {
|
||||||
/// Service error
|
/// Service error
|
||||||
Service(Error),
|
Service(Error),
|
||||||
@ -433,516 +405,41 @@ pub enum DispatchError {
|
|||||||
Unknown,
|
Unknown,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A set of error that can occur during parsing content type
|
/// A set of error that can occur during parsing content type.
|
||||||
#[derive(PartialEq, Debug, Display)]
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum ContentTypeError {
|
pub enum ContentTypeError {
|
||||||
/// Can not parse content type
|
/// Can not parse content type
|
||||||
#[display(fmt = "Can not parse content type")]
|
#[display(fmt = "Can not parse content type")]
|
||||||
ParseError,
|
ParseError,
|
||||||
|
|
||||||
/// Unknown content encoding
|
/// Unknown content encoding
|
||||||
#[display(fmt = "Unknown content encoding")]
|
#[display(fmt = "Unknown content encoding")]
|
||||||
UnknownEncoding,
|
UnknownEncoding,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for ContentTypeError {}
|
#[cfg(test)]
|
||||||
|
mod content_type_test_impls {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl std::cmp::PartialEq for ContentTypeError {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::ParseError => matches!(other, ContentTypeError::ParseError),
|
||||||
|
Self::UnknownEncoding => {
|
||||||
|
matches!(other, ContentTypeError::UnknownEncoding)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `ContentTypeError`
|
|
||||||
impl ResponseError for ContentTypeError {
|
impl ResponseError for ContentTypeError {
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
StatusCode::BAD_REQUEST
|
StatusCode::BAD_REQUEST
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper type that can wrap any error and generate custom response.
|
|
||||||
///
|
|
||||||
/// In following example any `io::Error` will be converted into "BAD REQUEST"
|
|
||||||
/// response as opposite to *INTERNAL SERVER ERROR* which is defined by
|
|
||||||
/// default.
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # use std::io;
|
|
||||||
/// # use actix_http::*;
|
|
||||||
///
|
|
||||||
/// fn index(req: Request) -> Result<&'static str> {
|
|
||||||
/// Err(error::ErrorBadRequest(io::Error::new(io::ErrorKind::Other, "error")))
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub struct InternalError<T> {
|
|
||||||
cause: T,
|
|
||||||
status: InternalErrorType,
|
|
||||||
}
|
|
||||||
|
|
||||||
enum InternalErrorType {
|
|
||||||
Status(StatusCode),
|
|
||||||
Response(RefCell<Option<Response>>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> InternalError<T> {
|
|
||||||
/// Create `InternalError` instance
|
|
||||||
pub fn new(cause: T, status: StatusCode) -> Self {
|
|
||||||
InternalError {
|
|
||||||
cause,
|
|
||||||
status: InternalErrorType::Status(status),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create `InternalError` with predefined `Response`.
|
|
||||||
pub fn from_response(cause: T, response: Response) -> Self {
|
|
||||||
InternalError {
|
|
||||||
cause,
|
|
||||||
status: InternalErrorType::Response(RefCell::new(Some(response))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Debug for InternalError<T>
|
|
||||||
where
|
|
||||||
T: fmt::Debug + 'static,
|
|
||||||
{
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
fmt::Debug::fmt(&self.cause, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> fmt::Display for InternalError<T>
|
|
||||||
where
|
|
||||||
T: fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
fmt::Display::fmt(&self.cause, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> ResponseError for InternalError<T>
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
fn status_code(&self) -> StatusCode {
|
|
||||||
match self.status {
|
|
||||||
InternalErrorType::Status(st) => st,
|
|
||||||
InternalErrorType::Response(ref resp) => {
|
|
||||||
if let Some(resp) = resp.borrow().as_ref() {
|
|
||||||
resp.head().status
|
|
||||||
} else {
|
|
||||||
StatusCode::INTERNAL_SERVER_ERROR
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn error_response(&self) -> Response {
|
|
||||||
match self.status {
|
|
||||||
InternalErrorType::Status(st) => {
|
|
||||||
let mut res = Response::new(st);
|
|
||||||
let mut buf = BytesMut::new();
|
|
||||||
let _ = write!(Writer(&mut buf), "{}", self);
|
|
||||||
res.headers_mut().insert(
|
|
||||||
header::CONTENT_TYPE,
|
|
||||||
header::HeaderValue::from_static("text/plain; charset=utf-8"),
|
|
||||||
);
|
|
||||||
res.set_body(Body::from(buf))
|
|
||||||
}
|
|
||||||
InternalErrorType::Response(ref resp) => {
|
|
||||||
if let Some(resp) = resp.borrow_mut().take() {
|
|
||||||
resp
|
|
||||||
} else {
|
|
||||||
Response::new(StatusCode::INTERNAL_SERVER_ERROR)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *BAD
|
|
||||||
/// REQUEST* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorBadRequest<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::BAD_REQUEST).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *UNAUTHORIZED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorUnauthorized<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::UNAUTHORIZED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *PAYMENT_REQUIRED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorPaymentRequired<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::PAYMENT_REQUIRED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *FORBIDDEN*
|
|
||||||
/// response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorForbidden<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::FORBIDDEN).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *NOT FOUND*
|
|
||||||
/// response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorNotFound<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::NOT_FOUND).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *METHOD NOT
|
|
||||||
/// ALLOWED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorMethodNotAllowed<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::METHOD_NOT_ALLOWED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *NOT
|
|
||||||
/// ACCEPTABLE* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorNotAcceptable<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::NOT_ACCEPTABLE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *PROXY
|
|
||||||
/// AUTHENTICATION REQUIRED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorProxyAuthenticationRequired<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::PROXY_AUTHENTICATION_REQUIRED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *REQUEST
|
|
||||||
/// TIMEOUT* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorRequestTimeout<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::REQUEST_TIMEOUT).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *CONFLICT*
|
|
||||||
/// response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorConflict<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::CONFLICT).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *GONE*
|
|
||||||
/// response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorGone<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::GONE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate *LENGTH
|
|
||||||
/// REQUIRED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorLengthRequired<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::LENGTH_REQUIRED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *PAYLOAD TOO LARGE* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorPayloadTooLarge<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::PAYLOAD_TOO_LARGE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *URI TOO LONG* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorUriTooLong<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::URI_TOO_LONG).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *UNSUPPORTED MEDIA TYPE* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorUnsupportedMediaType<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::UNSUPPORTED_MEDIA_TYPE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *RANGE NOT SATISFIABLE* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorRangeNotSatisfiable<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::RANGE_NOT_SATISFIABLE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *IM A TEAPOT* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorImATeapot<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::IM_A_TEAPOT).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *MISDIRECTED REQUEST* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorMisdirectedRequest<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::MISDIRECTED_REQUEST).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *UNPROCESSABLE ENTITY* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorUnprocessableEntity<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::UNPROCESSABLE_ENTITY).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *LOCKED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorLocked<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::LOCKED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *FAILED DEPENDENCY* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorFailedDependency<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::FAILED_DEPENDENCY).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *UPGRADE REQUIRED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorUpgradeRequired<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::UPGRADE_REQUIRED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *PRECONDITION FAILED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorPreconditionFailed<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::PRECONDITION_FAILED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *PRECONDITION REQUIRED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorPreconditionRequired<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::PRECONDITION_REQUIRED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *TOO MANY REQUESTS* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorTooManyRequests<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::TOO_MANY_REQUESTS).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *REQUEST HEADER FIELDS TOO LARGE* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorRequestHeaderFieldsTooLarge<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *UNAVAILABLE FOR LEGAL REASONS* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorUnavailableForLegalReasons<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and generate
|
|
||||||
/// *EXPECTATION FAILED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorExpectationFailed<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::EXPECTATION_FAILED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *INTERNAL SERVER ERROR* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorInternalServerError<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::INTERNAL_SERVER_ERROR).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *NOT IMPLEMENTED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorNotImplemented<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::NOT_IMPLEMENTED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *BAD GATEWAY* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorBadGateway<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::BAD_GATEWAY).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *SERVICE UNAVAILABLE* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorServiceUnavailable<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::SERVICE_UNAVAILABLE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *GATEWAY TIMEOUT* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorGatewayTimeout<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::GATEWAY_TIMEOUT).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *HTTP VERSION NOT SUPPORTED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorHttpVersionNotSupported<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::HTTP_VERSION_NOT_SUPPORTED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *VARIANT ALSO NEGOTIATES* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorVariantAlsoNegotiates<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::VARIANT_ALSO_NEGOTIATES).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *INSUFFICIENT STORAGE* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorInsufficientStorage<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::INSUFFICIENT_STORAGE).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *LOOP DETECTED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorLoopDetected<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::LOOP_DETECTED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *NOT EXTENDED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorNotExtended<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::NOT_EXTENDED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function that creates wrapper of any error and
|
|
||||||
/// generate *NETWORK AUTHENTICATION REQUIRED* response.
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
pub fn ErrorNetworkAuthenticationRequired<T>(err: T) -> Error
|
|
||||||
where
|
|
||||||
T: fmt::Debug + fmt::Display + 'static,
|
|
||||||
{
|
|
||||||
InternalError::new(err, StatusCode::NETWORK_AUTHENTICATION_REQUIRED).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -951,21 +448,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_into_response() {
|
fn test_into_response() {
|
||||||
let resp: Response = ParseError::Incomplete.error_response();
|
let resp: Response<Body> = ParseError::Incomplete.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
|
let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
|
||||||
let resp: Response = err.error_response();
|
let resp: Response<Body> = err.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
#[test]
|
|
||||||
fn test_cookie_parse() {
|
|
||||||
let resp: Response = CookieParseError::EmptyName.error_response();
|
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_as_response() {
|
fn test_as_response() {
|
||||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||||
@ -993,7 +483,7 @@ mod tests {
|
|||||||
fn test_error_http_response() {
|
fn test_error_http_response() {
|
||||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||||
let e = Error::from(orig);
|
let e = Error::from(orig);
|
||||||
let resp: Response = e.into();
|
let resp: Response<Body> = e.into();
|
||||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1046,14 +536,6 @@ mod tests {
|
|||||||
from!(httparse::Error::Version => ParseError::Version);
|
from!(httparse::Error::Version => ParseError::Version);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_internal_error() {
|
|
||||||
let err =
|
|
||||||
InternalError::from_response(ParseError::Method, Response::Ok().into());
|
|
||||||
let resp: Response = err.error_response();
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_error_casting() {
|
fn test_error_casting() {
|
||||||
let err = PayloadError::Overflow;
|
let err = PayloadError::Overflow;
|
||||||
@ -1063,124 +545,4 @@ mod tests {
|
|||||||
let not_err = resp_err.downcast_ref::<ContentTypeError>();
|
let not_err = resp_err.downcast_ref::<ContentTypeError>();
|
||||||
assert!(not_err.is_none());
|
assert!(not_err.is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_error_helpers() {
|
|
||||||
let r: Response = ErrorBadRequest("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
|
|
||||||
|
|
||||||
let r: Response = ErrorUnauthorized("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
|
|
||||||
|
|
||||||
let r: Response = ErrorPaymentRequired("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::PAYMENT_REQUIRED);
|
|
||||||
|
|
||||||
let r: Response = ErrorForbidden("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::FORBIDDEN);
|
|
||||||
|
|
||||||
let r: Response = ErrorNotFound("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::NOT_FOUND);
|
|
||||||
|
|
||||||
let r: Response = ErrorMethodNotAllowed("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED);
|
|
||||||
|
|
||||||
let r: Response = ErrorNotAcceptable("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::NOT_ACCEPTABLE);
|
|
||||||
|
|
||||||
let r: Response = ErrorProxyAuthenticationRequired("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);
|
|
||||||
|
|
||||||
let r: Response = ErrorRequestTimeout("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::REQUEST_TIMEOUT);
|
|
||||||
|
|
||||||
let r: Response = ErrorConflict("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::CONFLICT);
|
|
||||||
|
|
||||||
let r: Response = ErrorGone("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::GONE);
|
|
||||||
|
|
||||||
let r: Response = ErrorLengthRequired("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::LENGTH_REQUIRED);
|
|
||||||
|
|
||||||
let r: Response = ErrorPreconditionFailed("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::PRECONDITION_FAILED);
|
|
||||||
|
|
||||||
let r: Response = ErrorPayloadTooLarge("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
|
||||||
|
|
||||||
let r: Response = ErrorUriTooLong("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::URI_TOO_LONG);
|
|
||||||
|
|
||||||
let r: Response = ErrorUnsupportedMediaType("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
|
||||||
|
|
||||||
let r: Response = ErrorRangeNotSatisfiable("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
|
||||||
|
|
||||||
let r: Response = ErrorExpectationFailed("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::EXPECTATION_FAILED);
|
|
||||||
|
|
||||||
let r: Response = ErrorImATeapot("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::IM_A_TEAPOT);
|
|
||||||
|
|
||||||
let r: Response = ErrorMisdirectedRequest("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::MISDIRECTED_REQUEST);
|
|
||||||
|
|
||||||
let r: Response = ErrorUnprocessableEntity("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
|
||||||
|
|
||||||
let r: Response = ErrorLocked("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::LOCKED);
|
|
||||||
|
|
||||||
let r: Response = ErrorFailedDependency("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::FAILED_DEPENDENCY);
|
|
||||||
|
|
||||||
let r: Response = ErrorUpgradeRequired("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::UPGRADE_REQUIRED);
|
|
||||||
|
|
||||||
let r: Response = ErrorPreconditionRequired("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::PRECONDITION_REQUIRED);
|
|
||||||
|
|
||||||
let r: Response = ErrorTooManyRequests("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
|
|
||||||
|
|
||||||
let r: Response = ErrorRequestHeaderFieldsTooLarge("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE);
|
|
||||||
|
|
||||||
let r: Response = ErrorUnavailableForLegalReasons("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS);
|
|
||||||
|
|
||||||
let r: Response = ErrorInternalServerError("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
|
||||||
|
|
||||||
let r: Response = ErrorNotImplemented("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::NOT_IMPLEMENTED);
|
|
||||||
|
|
||||||
let r: Response = ErrorBadGateway("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::BAD_GATEWAY);
|
|
||||||
|
|
||||||
let r: Response = ErrorServiceUnavailable("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
|
|
||||||
|
|
||||||
let r: Response = ErrorGatewayTimeout("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::GATEWAY_TIMEOUT);
|
|
||||||
|
|
||||||
let r: Response = ErrorHttpVersionNotSupported("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);
|
|
||||||
|
|
||||||
let r: Response = ErrorVariantAlsoNegotiates("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::VARIANT_ALSO_NEGOTIATES);
|
|
||||||
|
|
||||||
let r: Response = ErrorInsufficientStorage("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::INSUFFICIENT_STORAGE);
|
|
||||||
|
|
||||||
let r: Response = ErrorLoopDetected("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::LOOP_DETECTED);
|
|
||||||
|
|
||||||
let r: Response = ErrorNotExtended("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::NOT_EXTENDED);
|
|
||||||
|
|
||||||
let r: Response = ErrorNetworkAuthenticationRequired("err").into();
|
|
||||||
assert_eq!(r.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1213,8 +1213,9 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_parse_chunked_payload_chunk_extension() {
|
fn test_parse_chunked_payload_chunk_extension() {
|
||||||
let mut buf = BytesMut::from(
|
let mut buf = BytesMut::from(
|
||||||
&"GET /test HTTP/1.1\r\n\
|
"GET /test HTTP/1.1\r\n\
|
||||||
transfer-encoding: chunked\r\n\r\n"[..],
|
transfer-encoding: chunked\r\n\
|
||||||
|
\r\n",
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut reader = MessageDecoder::<Request>::default();
|
let mut reader = MessageDecoder::<Request>::default();
|
||||||
@ -1233,7 +1234,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_response_http10_read_until_eof() {
|
fn test_response_http10_read_until_eof() {
|
||||||
let mut buf = BytesMut::from(&"HTTP/1.0 200 Ok\r\n\r\ntest data"[..]);
|
let mut buf = BytesMut::from("HTTP/1.0 200 Ok\r\n\r\ntest data");
|
||||||
|
|
||||||
let mut reader = MessageDecoder::<ResponseHead>::default();
|
let mut reader = MessageDecoder::<ResponseHead>::default();
|
||||||
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
|
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
|
||||||
|
@ -17,10 +17,11 @@ use futures_core::ready;
|
|||||||
use log::{error, trace};
|
use log::{error, trace};
|
||||||
use pin_project::pin_project;
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
use crate::body::{Body, BodySize, MessageBody};
|
||||||
use crate::config::ServiceConfig;
|
use crate::config::ServiceConfig;
|
||||||
use crate::error::{DispatchError, Error};
|
use crate::error::{DispatchError, Error};
|
||||||
use crate::error::{ParseError, PayloadError};
|
use crate::error::{ParseError, PayloadError};
|
||||||
|
use crate::http::StatusCode;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
use crate::service::HttpFlow;
|
use crate::service::HttpFlow;
|
||||||
@ -50,9 +51,13 @@ pub struct Dispatcher<T, S, B, X, U>
|
|||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -68,9 +73,13 @@ enum DispatcherState<T, S, B, X, U>
|
|||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -83,9 +92,13 @@ struct InnerDispatcher<T, S, B, X, U>
|
|||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -121,19 +134,25 @@ enum State<S, B, X>
|
|||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
None,
|
None,
|
||||||
ExpectCall(#[pin] X::Future),
|
ExpectCall(#[pin] X::Future),
|
||||||
ServiceCall(#[pin] S::Future),
|
ServiceCall(#[pin] S::Future),
|
||||||
SendPayload(#[pin] ResponseBody<B>),
|
SendPayload(#[pin] B),
|
||||||
|
SendErrorPayload(#[pin] Body),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, B, X> State<S, B, X>
|
impl<S, B, X> State<S, B, X>
|
||||||
where
|
where
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
fn is_empty(&self) -> bool {
|
fn is_empty(&self) -> bool {
|
||||||
matches!(self, State::None)
|
matches!(self, State::None)
|
||||||
@ -149,12 +168,17 @@ enum PollResponse {
|
|||||||
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -205,12 +229,17 @@ where
|
|||||||
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -267,11 +296,11 @@ where
|
|||||||
io.poll_flush(cx)
|
io.poll_flush(cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_response(
|
fn send_response_inner(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
message: Response<()>,
|
message: Response<()>,
|
||||||
body: ResponseBody<B>,
|
body: &impl MessageBody,
|
||||||
) -> Result<(), DispatchError> {
|
) -> Result<BodySize, DispatchError> {
|
||||||
let size = body.size();
|
let size = body.size();
|
||||||
let mut this = self.project();
|
let mut this = self.project();
|
||||||
this.codec
|
this.codec
|
||||||
@ -284,10 +313,35 @@ where
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
this.flags.set(Flags::KEEPALIVE, this.codec.keepalive());
|
this.flags.set(Flags::KEEPALIVE, this.codec.keepalive());
|
||||||
match size {
|
|
||||||
BodySize::None | BodySize::Empty => this.state.set(State::None),
|
Ok(size)
|
||||||
_ => this.state.set(State::SendPayload(body)),
|
}
|
||||||
|
|
||||||
|
fn send_response(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
message: Response<()>,
|
||||||
|
body: B,
|
||||||
|
) -> Result<(), DispatchError> {
|
||||||
|
let size = self.as_mut().send_response_inner(message, &body)?;
|
||||||
|
let state = match size {
|
||||||
|
BodySize::None | BodySize::Empty => State::None,
|
||||||
|
_ => State::SendPayload(body),
|
||||||
};
|
};
|
||||||
|
self.project().state.set(state);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_error_response(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
message: Response<()>,
|
||||||
|
body: Body,
|
||||||
|
) -> Result<(), DispatchError> {
|
||||||
|
let size = self.as_mut().send_response_inner(message, &body)?;
|
||||||
|
let state = match size {
|
||||||
|
BodySize::None | BodySize::Empty => State::None,
|
||||||
|
_ => State::SendErrorPayload(body),
|
||||||
|
};
|
||||||
|
self.project().state.set(state);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -325,8 +379,7 @@ where
|
|||||||
// send_response would update InnerDispatcher state to SendPayload or
|
// send_response would update InnerDispatcher state to SendPayload or
|
||||||
// None(If response body is empty).
|
// None(If response body is empty).
|
||||||
// continue loop to poll it.
|
// continue loop to poll it.
|
||||||
self.as_mut()
|
self.as_mut().send_error_response(res, Body::Empty)?;
|
||||||
.send_response(res, ResponseBody::Other(Body::Empty))?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// return with upgrade request and poll it exclusively.
|
// return with upgrade request and poll it exclusively.
|
||||||
@ -346,9 +399,9 @@ where
|
|||||||
|
|
||||||
// send service call error as response
|
// send service call error as response
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
let res: Response = err.into().into();
|
let res = Response::from_error(err);
|
||||||
let (res, body) = res.replace_body(());
|
let (res, body) = res.replace_body(());
|
||||||
self.as_mut().send_response(res, body.into_body())?;
|
self.as_mut().send_error_response(res, body)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// service call pending and could be waiting for more chunk messages.
|
// service call pending and could be waiting for more chunk messages.
|
||||||
@ -364,6 +417,41 @@ where
|
|||||||
},
|
},
|
||||||
|
|
||||||
StateProj::SendPayload(mut stream) => {
|
StateProj::SendPayload(mut stream) => {
|
||||||
|
// keep populate writer buffer until buffer size limit hit,
|
||||||
|
// get blocked or finished.
|
||||||
|
while this.write_buf.len() < super::payload::MAX_BUFFER_SIZE {
|
||||||
|
match stream.as_mut().poll_next(cx) {
|
||||||
|
Poll::Ready(Some(Ok(item))) => {
|
||||||
|
this.codec.encode(
|
||||||
|
Message::Chunk(Some(item)),
|
||||||
|
&mut this.write_buf,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Poll::Ready(None) => {
|
||||||
|
this.codec
|
||||||
|
.encode(Message::Chunk(None), &mut this.write_buf)?;
|
||||||
|
// payload stream finished.
|
||||||
|
// set state to None and handle next message
|
||||||
|
this.state.set(State::None);
|
||||||
|
continue 'res;
|
||||||
|
}
|
||||||
|
|
||||||
|
Poll::Ready(Some(Err(err))) => {
|
||||||
|
return Err(DispatchError::Service(err.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
Poll::Pending => return Ok(PollResponse::DoNothing),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// buffer is beyond max size.
|
||||||
|
// return and try to write the whole buffer to io stream.
|
||||||
|
return Ok(PollResponse::DrainWriteBuf);
|
||||||
|
}
|
||||||
|
|
||||||
|
StateProj::SendErrorPayload(mut stream) => {
|
||||||
|
// TODO: de-dupe impl with SendPayload
|
||||||
|
|
||||||
// keep populate writer buffer until buffer size limit hit,
|
// keep populate writer buffer until buffer size limit hit,
|
||||||
// get blocked or finished.
|
// get blocked or finished.
|
||||||
while this.write_buf.len() < super::payload::MAX_BUFFER_SIZE {
|
while this.write_buf.len() < super::payload::MAX_BUFFER_SIZE {
|
||||||
@ -405,12 +493,14 @@ where
|
|||||||
let fut = this.flow.service.call(req);
|
let fut = this.flow.service.call(req);
|
||||||
this.state.set(State::ServiceCall(fut));
|
this.state.set(State::ServiceCall(fut));
|
||||||
}
|
}
|
||||||
|
|
||||||
// send expect error as response
|
// send expect error as response
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
let res: Response = err.into().into();
|
let res = Response::from_error(err);
|
||||||
let (res, body) = res.replace_body(());
|
let (res, body) = res.replace_body(());
|
||||||
self.as_mut().send_response(res, body.into_body())?;
|
self.as_mut().send_error_response(res, body)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// expect must be solved before progress can be made.
|
// expect must be solved before progress can be made.
|
||||||
Poll::Pending => return Ok(PollResponse::DoNothing),
|
Poll::Pending => return Ok(PollResponse::DoNothing),
|
||||||
},
|
},
|
||||||
@ -456,10 +546,9 @@ where
|
|||||||
// to notify the dispatcher a new state is set and the outer loop
|
// to notify the dispatcher a new state is set and the outer loop
|
||||||
// should be continue.
|
// should be continue.
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
let err = err.into();
|
let res = Response::from_error(err);
|
||||||
let res: Response = err.into();
|
|
||||||
let (res, body) = res.replace_body(());
|
let (res, body) = res.replace_body(());
|
||||||
return self.send_response(res, body.into_body());
|
return self.send_error_response(res, body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -477,9 +566,9 @@ where
|
|||||||
Poll::Pending => Ok(()),
|
Poll::Pending => Ok(()),
|
||||||
// see the comment on ExpectCall state branch's Ready(Err(err)).
|
// see the comment on ExpectCall state branch's Ready(Err(err)).
|
||||||
Poll::Ready(Err(err)) => {
|
Poll::Ready(Err(err)) => {
|
||||||
let res: Response = err.into().into();
|
let res = Response::from_error(err);
|
||||||
let (res, body) = res.replace_body(());
|
let (res, body) = res.replace_body(());
|
||||||
self.send_response(res, body.into_body())
|
self.send_error_response(res, body)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -563,7 +652,7 @@ where
|
|||||||
);
|
);
|
||||||
this.flags.insert(Flags::READ_DISCONNECT);
|
this.flags.insert(Flags::READ_DISCONNECT);
|
||||||
this.messages.push_back(DispatcherMessage::Error(
|
this.messages.push_back(DispatcherMessage::Error(
|
||||||
Response::InternalServerError().finish().drop_body(),
|
Response::internal_server_error().drop_body(),
|
||||||
));
|
));
|
||||||
*this.error = Some(DispatchError::InternalError);
|
*this.error = Some(DispatchError::InternalError);
|
||||||
break;
|
break;
|
||||||
@ -576,7 +665,7 @@ where
|
|||||||
error!("Internal server error: unexpected eof");
|
error!("Internal server error: unexpected eof");
|
||||||
this.flags.insert(Flags::READ_DISCONNECT);
|
this.flags.insert(Flags::READ_DISCONNECT);
|
||||||
this.messages.push_back(DispatcherMessage::Error(
|
this.messages.push_back(DispatcherMessage::Error(
|
||||||
Response::InternalServerError().finish().drop_body(),
|
Response::internal_server_error().drop_body(),
|
||||||
));
|
));
|
||||||
*this.error = Some(DispatchError::InternalError);
|
*this.error = Some(DispatchError::InternalError);
|
||||||
break;
|
break;
|
||||||
@ -599,7 +688,10 @@ where
|
|||||||
}
|
}
|
||||||
// Requests overflow buffer size should be responded with 431
|
// Requests overflow buffer size should be responded with 431
|
||||||
this.messages.push_back(DispatcherMessage::Error(
|
this.messages.push_back(DispatcherMessage::Error(
|
||||||
Response::RequestHeaderFieldsTooLarge().finish().drop_body(),
|
Response::with_body(
|
||||||
|
StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE,
|
||||||
|
(),
|
||||||
|
),
|
||||||
));
|
));
|
||||||
this.flags.insert(Flags::READ_DISCONNECT);
|
this.flags.insert(Flags::READ_DISCONNECT);
|
||||||
*this.error = Some(ParseError::TooLarge.into());
|
*this.error = Some(ParseError::TooLarge.into());
|
||||||
@ -612,7 +704,7 @@ where
|
|||||||
|
|
||||||
// Malformed requests should be responded with 400
|
// Malformed requests should be responded with 400
|
||||||
this.messages.push_back(DispatcherMessage::Error(
|
this.messages.push_back(DispatcherMessage::Error(
|
||||||
Response::BadRequest().finish().drop_body(),
|
Response::bad_request().drop_body(),
|
||||||
));
|
));
|
||||||
this.flags.insert(Flags::READ_DISCONNECT);
|
this.flags.insert(Flags::READ_DISCONNECT);
|
||||||
*this.error = Some(err.into());
|
*this.error = Some(err.into());
|
||||||
@ -648,11 +740,6 @@ where
|
|||||||
// go into Some<Pin<&mut Sleep>> branch
|
// go into Some<Pin<&mut Sleep>> branch
|
||||||
this.ka_timer.set(Some(sleep_until(deadline)));
|
this.ka_timer.set(Some(sleep_until(deadline)));
|
||||||
return self.poll_keepalive(cx);
|
return self.poll_keepalive(cx);
|
||||||
} else {
|
|
||||||
this.flags.insert(Flags::READ_DISCONNECT);
|
|
||||||
if let Some(mut payload) = this.payload.take() {
|
|
||||||
payload.set_error(PayloadError::Incomplete(None));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -682,18 +769,13 @@ where
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// timeout on first request (slow request) return 408
|
// timeout on first request (slow request) return 408
|
||||||
if !this.flags.contains(Flags::STARTED) {
|
trace!("Slow request timeout");
|
||||||
trace!("Slow request timeout");
|
let _ = self.as_mut().send_error_response(
|
||||||
let _ = self.as_mut().send_response(
|
Response::with_body(StatusCode::REQUEST_TIMEOUT, ()),
|
||||||
Response::RequestTimeout().finish().drop_body(),
|
Body::Empty,
|
||||||
ResponseBody::Other(Body::Empty),
|
);
|
||||||
);
|
this = self.project();
|
||||||
this = self.project();
|
|
||||||
} else {
|
|
||||||
trace!("Keep-alive connection timeout");
|
|
||||||
}
|
|
||||||
this.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
|
this.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
|
||||||
this.state.set(State::None);
|
|
||||||
}
|
}
|
||||||
// still have unfinished task. try to reset and register keep-alive.
|
// still have unfinished task. try to reset and register keep-alive.
|
||||||
} else if let Some(deadline) =
|
} else if let Some(deadline) =
|
||||||
@ -825,12 +907,17 @@ where
|
|||||||
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -952,6 +1039,7 @@ mod tests {
|
|||||||
|
|
||||||
use actix_service::fn_service;
|
use actix_service::fn_service;
|
||||||
use actix_utils::future::{ready, Ready};
|
use actix_utils::future::{ready, Ready};
|
||||||
|
use bytes::Bytes;
|
||||||
use futures_util::future::lazy;
|
use futures_util::future::lazy;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -979,19 +1067,22 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ok_service() -> impl Service<Request, Response = Response, Error = Error> {
|
fn ok_service() -> impl Service<Request, Response = Response<Body>, Error = Error> {
|
||||||
fn_service(|_req: Request| ready(Ok::<_, Error>(Response::Ok().finish())))
|
fn_service(|_req: Request| ready(Ok::<_, Error>(Response::ok())))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn echo_path_service() -> impl Service<Request, Response = Response, Error = Error> {
|
fn echo_path_service(
|
||||||
|
) -> impl Service<Request, Response = Response<Body>, Error = Error> {
|
||||||
fn_service(|req: Request| {
|
fn_service(|req: Request| {
|
||||||
let path = req.path().as_bytes();
|
let path = req.path().as_bytes();
|
||||||
ready(Ok::<_, Error>(Response::Ok().body(Body::from_slice(path))))
|
ready(Ok::<_, Error>(
|
||||||
|
Response::ok().set_body(Body::from_slice(path)),
|
||||||
|
))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn echo_payload_service() -> impl Service<Request, Response = Response, Error = Error>
|
fn echo_payload_service(
|
||||||
{
|
) -> impl Service<Request, Response = Response<Bytes>, Error = Error> {
|
||||||
fn_service(|mut req: Request| {
|
fn_service(|mut req: Request| {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
use futures_util::stream::StreamExt as _;
|
use futures_util::stream::StreamExt as _;
|
||||||
@ -1002,7 +1093,7 @@ mod tests {
|
|||||||
body.extend_from_slice(chunk.unwrap().chunk())
|
body.extend_from_slice(chunk.unwrap().chunk())
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok::<_, Error>(Response::Ok().body(body))
|
Ok::<_, Error>(Response::ok().set_body(body.freeze()))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -630,8 +630,7 @@ mod tests {
|
|||||||
async fn test_no_content_length() {
|
async fn test_no_content_length() {
|
||||||
let mut bytes = BytesMut::with_capacity(2048);
|
let mut bytes = BytesMut::with_capacity(2048);
|
||||||
|
|
||||||
let mut res: Response<()> =
|
let mut res = Response::with_body(StatusCode::SWITCHING_PROTOCOLS, ());
|
||||||
Response::new(StatusCode::SWITCHING_PROTOCOLS).into_body::<()>();
|
|
||||||
res.headers_mut().insert(DATE, HeaderValue::from_static(""));
|
res.headers_mut().insert(DATE, HeaderValue::from_static(""));
|
||||||
res.headers_mut()
|
res.headers_mut()
|
||||||
.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));
|
.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));
|
||||||
|
@ -5,7 +5,9 @@ use std::{fmt, net};
|
|||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
|
use actix_service::{
|
||||||
|
fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _,
|
||||||
|
};
|
||||||
use actix_utils::future::ready;
|
use actix_utils::future::ready;
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
|
|
||||||
@ -62,11 +64,15 @@ where
|
|||||||
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,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<(Request, Framed<TcpStream, Codec>), Config = (), Response = ()>,
|
U: ServiceFactory<(Request, Framed<TcpStream, Codec>), Config = (), Response = ()>,
|
||||||
U::Future: 'static,
|
U::Future: 'static,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
@ -82,7 +88,7 @@ where
|
|||||||
Error = DispatchError,
|
Error = DispatchError,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
> {
|
> {
|
||||||
pipeline_factory(|io: TcpStream| {
|
fn_service(|io: TcpStream| {
|
||||||
let peer_addr = io.peer_addr().ok();
|
let peer_addr = io.peer_addr().ok();
|
||||||
ready(Ok((io, peer_addr)))
|
ready(Ok((io, peer_addr)))
|
||||||
})
|
})
|
||||||
@ -107,11 +113,15 @@ mod openssl {
|
|||||||
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,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<
|
U: ServiceFactory<
|
||||||
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||||
Config = (),
|
Config = (),
|
||||||
@ -132,16 +142,14 @@ mod openssl {
|
|||||||
Error = TlsError<SslError, DispatchError>,
|
Error = TlsError<SslError, DispatchError>,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
> {
|
> {
|
||||||
pipeline_factory(
|
Acceptor::new(acceptor)
|
||||||
Acceptor::new(acceptor)
|
.map_err(TlsError::Tls)
|
||||||
.map_err(TlsError::Tls)
|
.map_init_err(|_| panic!())
|
||||||
.map_init_err(|_| panic!()),
|
.and_then(|io: TlsStream<TcpStream>| {
|
||||||
)
|
let peer_addr = io.get_ref().peer_addr().ok();
|
||||||
.and_then(|io: TlsStream<TcpStream>| {
|
ready(Ok((io, peer_addr)))
|
||||||
let peer_addr = io.get_ref().peer_addr().ok();
|
})
|
||||||
ready(Ok((io, peer_addr)))
|
.and_then(self.map_err(TlsError::Service))
|
||||||
})
|
|
||||||
.and_then(self.map_err(TlsError::Service))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -165,11 +173,15 @@ mod rustls {
|
|||||||
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,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<
|
U: ServiceFactory<
|
||||||
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||||
Config = (),
|
Config = (),
|
||||||
@ -190,16 +202,14 @@ mod rustls {
|
|||||||
Error = TlsError<io::Error, DispatchError>,
|
Error = TlsError<io::Error, DispatchError>,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
> {
|
> {
|
||||||
pipeline_factory(
|
Acceptor::new(config)
|
||||||
Acceptor::new(config)
|
.map_err(TlsError::Tls)
|
||||||
.map_err(TlsError::Tls)
|
.map_init_err(|_| panic!())
|
||||||
.map_init_err(|_| panic!()),
|
.and_then(|io: TlsStream<TcpStream>| {
|
||||||
)
|
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||||
.and_then(|io: TlsStream<TcpStream>| {
|
ready(Ok((io, peer_addr)))
|
||||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
})
|
||||||
ready(Ok((io, peer_addr)))
|
.and_then(self.map_err(TlsError::Service))
|
||||||
})
|
|
||||||
.and_then(self.map_err(TlsError::Service))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -255,16 +265,21 @@ impl<T, S, B, X, U> ServiceFactory<(T, Option<net::SocketAddr>)>
|
|||||||
for H1Service<T, S, B, X, U>
|
for H1Service<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||||
|
|
||||||
S: ServiceFactory<Request, Config = ()>,
|
S: ServiceFactory<Request, Config = ()>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
S::InitError: fmt::Debug,
|
S::InitError: fmt::Debug,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
X::InitError: fmt::Debug,
|
X::InitError: fmt::Debug,
|
||||||
|
|
||||||
U: ServiceFactory<(Request, Framed<T, Codec>), Config = (), Response = ()>,
|
U: ServiceFactory<(Request, Framed<T, Codec>), Config = (), Response = ()>,
|
||||||
U::Future: 'static,
|
U::Future: 'static,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
@ -321,12 +336,17 @@ impl<T, S, B, X, U> Service<(T, Option<net::SocketAddr>)>
|
|||||||
for HttpServiceHandler<T, S, B, X, U>
|
for HttpServiceHandler<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
{
|
{
|
||||||
|
@ -4,7 +4,7 @@ use std::task::{Context, Poll};
|
|||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
|
|
||||||
use crate::body::{BodySize, MessageBody, ResponseBody};
|
use crate::body::{BodySize, MessageBody};
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::h1::{Codec, Message};
|
use crate::h1::{Codec, Message};
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
@ -14,7 +14,7 @@ use crate::response::Response;
|
|||||||
pub struct SendResponse<T, B> {
|
pub struct SendResponse<T, B> {
|
||||||
res: Option<Message<(Response<()>, BodySize)>>,
|
res: Option<Message<(Response<()>, BodySize)>>,
|
||||||
#[pin]
|
#[pin]
|
||||||
body: Option<ResponseBody<B>>,
|
body: Option<B>,
|
||||||
#[pin]
|
#[pin]
|
||||||
framed: Option<Framed<T, Codec>>,
|
framed: Option<Framed<T, Codec>>,
|
||||||
}
|
}
|
||||||
@ -22,6 +22,7 @@ pub struct SendResponse<T, B> {
|
|||||||
impl<T, B> SendResponse<T, B>
|
impl<T, B> SendResponse<T, B>
|
||||||
where
|
where
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
pub fn new(framed: Framed<T, Codec>, response: Response<B>) -> Self {
|
pub fn new(framed: Framed<T, Codec>, response: Response<B>) -> Self {
|
||||||
let (res, body) = response.into_parts();
|
let (res, body) = response.into_parts();
|
||||||
@ -38,6 +39,7 @@ impl<T, B> Future for SendResponse<T, B>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
B: MessageBody + Unpin,
|
B: MessageBody + Unpin,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Output = Result<Framed<T, Codec>, Error>;
|
type Output = Result<Framed<T, Codec>, Error>;
|
||||||
|
|
||||||
@ -60,7 +62,18 @@ where
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.is_write_buf_full()
|
.is_write_buf_full()
|
||||||
{
|
{
|
||||||
match this.body.as_mut().as_pin_mut().unwrap().poll_next(cx)? {
|
let next =
|
||||||
|
// TODO: MSRV 1.51: poll_map_err
|
||||||
|
match this.body.as_mut().as_pin_mut().unwrap().poll_next(cx) {
|
||||||
|
Poll::Ready(Some(Ok(item))) => Poll::Ready(Some(item)),
|
||||||
|
Poll::Ready(Some(Err(err))) => {
|
||||||
|
return Poll::Ready(Err(err.into()))
|
||||||
|
}
|
||||||
|
Poll::Ready(None) => Poll::Ready(None),
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
};
|
||||||
|
|
||||||
|
match next {
|
||||||
Poll::Ready(item) => {
|
Poll::Ready(item) => {
|
||||||
// body is done when item is None
|
// body is done when item is None
|
||||||
body_done = item.is_none();
|
body_done = item.is_none();
|
||||||
|
@ -1,20 +1,26 @@
|
|||||||
use std::task::{Context, Poll};
|
use std::{
|
||||||
use std::{cmp, future::Future, marker::PhantomData, net, pin::Pin, rc::Rc};
|
cmp,
|
||||||
|
future::Future,
|
||||||
|
marker::PhantomData,
|
||||||
|
net,
|
||||||
|
pin::Pin,
|
||||||
|
rc::Rc,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
|
use actix_utils::future::poll_fn;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures_core::ready;
|
use futures_core::ready;
|
||||||
use h2::{
|
use h2::server::{Connection, SendResponse};
|
||||||
server::{Connection, SendResponse},
|
|
||||||
SendStream,
|
|
||||||
};
|
|
||||||
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING};
|
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING};
|
||||||
use log::{error, trace};
|
use log::{error, trace};
|
||||||
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::body::{BodySize, MessageBody, ResponseBody};
|
use crate::body::{BodySize, MessageBody};
|
||||||
use crate::config::ServiceConfig;
|
use crate::config::ServiceConfig;
|
||||||
use crate::error::{DispatchError, Error};
|
use crate::error::Error;
|
||||||
use crate::message::ResponseHead;
|
use crate::message::ResponseHead;
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
@ -24,30 +30,19 @@ use crate::OnConnectData;
|
|||||||
|
|
||||||
const CHUNK_SIZE: usize = 16_384;
|
const CHUNK_SIZE: usize = 16_384;
|
||||||
|
|
||||||
/// Dispatcher for HTTP/2 protocol.
|
pin_project! {
|
||||||
#[pin_project::pin_project]
|
/// Dispatcher for HTTP/2 protocol.
|
||||||
pub struct Dispatcher<T, S, B, X, U>
|
pub struct Dispatcher<T, S, B, X, U> {
|
||||||
where
|
flow: Rc<HttpFlow<S, X, U>>,
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
connection: Connection<T, Bytes>,
|
||||||
S: Service<Request>,
|
on_connect_data: OnConnectData,
|
||||||
B: MessageBody,
|
config: ServiceConfig,
|
||||||
{
|
peer_addr: Option<net::SocketAddr>,
|
||||||
flow: Rc<HttpFlow<S, X, U>>,
|
_phantom: PhantomData<B>,
|
||||||
connection: Connection<T, Bytes>,
|
}
|
||||||
on_connect_data: OnConnectData,
|
|
||||||
config: ServiceConfig,
|
|
||||||
peer_addr: Option<net::SocketAddr>,
|
|
||||||
_phantom: PhantomData<B>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U> {
|
||||||
where
|
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
|
||||||
S: Service<Request>,
|
|
||||||
S::Error: Into<Error>,
|
|
||||||
S::Response: Into<Response<B>>,
|
|
||||||
B: MessageBody,
|
|
||||||
{
|
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
flow: Rc<HttpFlow<S, X, U>>,
|
flow: Rc<HttpFlow<S, X, U>>,
|
||||||
connection: Connection<T, Bytes>,
|
connection: Connection<T, Bytes>,
|
||||||
@ -55,7 +50,7 @@ where
|
|||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
peer_addr: Option<net::SocketAddr>,
|
peer_addr: Option<net::SocketAddr>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Dispatcher {
|
Self {
|
||||||
flow,
|
flow,
|
||||||
config,
|
config,
|
||||||
peer_addr,
|
peer_addr,
|
||||||
@ -69,269 +64,208 @@ where
|
|||||||
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>>,
|
||||||
B: MessageBody + 'static,
|
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Output = Result<(), DispatchError>;
|
type Output = Result<(), crate::error::DispatchError>;
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
let this = self.get_mut();
|
let this = self.get_mut();
|
||||||
|
|
||||||
loop {
|
while let Some((req, tx)) =
|
||||||
match ready!(Pin::new(&mut this.connection).poll_accept(cx)) {
|
ready!(Pin::new(&mut this.connection).poll_accept(cx)?)
|
||||||
None => return Poll::Ready(Ok(())),
|
{
|
||||||
|
let (parts, body) = req.into_parts();
|
||||||
|
let pl = crate::h2::Payload::new(body);
|
||||||
|
let pl = Payload::<crate::payload::PayloadStream>::H2(pl);
|
||||||
|
let mut req = Request::with_payload(pl);
|
||||||
|
|
||||||
Some(Err(err)) => return Poll::Ready(Err(err.into())),
|
let head = req.head_mut();
|
||||||
|
head.uri = parts.uri;
|
||||||
|
head.method = parts.method;
|
||||||
|
head.version = parts.version;
|
||||||
|
head.headers = parts.headers.into();
|
||||||
|
head.peer_addr = this.peer_addr;
|
||||||
|
|
||||||
Some(Ok((req, res))) => {
|
// merge on_connect_ext data into request extensions
|
||||||
let (parts, body) = req.into_parts();
|
this.on_connect_data.merge_into(&mut req);
|
||||||
let pl = crate::h2::Payload::new(body);
|
|
||||||
let pl = Payload::<crate::payload::PayloadStream>::H2(pl);
|
|
||||||
let mut req = Request::with_payload(pl);
|
|
||||||
|
|
||||||
let head = req.head_mut();
|
let fut = this.flow.service.call(req);
|
||||||
head.uri = parts.uri;
|
let config = this.config.clone();
|
||||||
head.method = parts.method;
|
|
||||||
head.version = parts.version;
|
|
||||||
head.headers = parts.headers.into();
|
|
||||||
head.peer_addr = this.peer_addr;
|
|
||||||
|
|
||||||
// merge on_connect_ext data into request extensions
|
// multiplex request handling with spawn task
|
||||||
this.on_connect_data.merge_into(&mut req);
|
actix_rt::spawn(async move {
|
||||||
|
// resolve service call and send response.
|
||||||
|
let res = match fut.await {
|
||||||
|
Ok(res) => handle_response(res.into(), tx, config).await,
|
||||||
|
Err(err) => {
|
||||||
|
let res = Response::from_error(err.into());
|
||||||
|
handle_response(res, tx, config).await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let svc = ServiceResponse {
|
// log error.
|
||||||
state: ServiceResponseState::ServiceCall(
|
if let Err(err) = res {
|
||||||
this.flow.service.call(req),
|
match err {
|
||||||
Some(res),
|
DispatchError::SendResponse(err) => {
|
||||||
),
|
trace!("Error sending HTTP/2 response: {:?}", err)
|
||||||
config: this.config.clone(),
|
}
|
||||||
buffer: None,
|
DispatchError::SendData(err) => warn!("{:?}", err),
|
||||||
_phantom: PhantomData,
|
DispatchError::ResponseBody(err) => {
|
||||||
};
|
error!("Response payload stream error: {:?}", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
actix_rt::spawn(svc);
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum DispatchError {
|
||||||
|
SendResponse(h2::Error),
|
||||||
|
SendData(h2::Error),
|
||||||
|
ResponseBody(Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_response<B>(
|
||||||
|
res: Response<B>,
|
||||||
|
mut tx: SendResponse<Bytes>,
|
||||||
|
config: ServiceConfig,
|
||||||
|
) -> Result<(), DispatchError>
|
||||||
|
where
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
{
|
||||||
|
let (res, body) = res.replace_body(());
|
||||||
|
|
||||||
|
// prepare response.
|
||||||
|
let mut size = body.size();
|
||||||
|
let res = prepare_response(config, res.head(), &mut size);
|
||||||
|
let eof = size.is_eof();
|
||||||
|
|
||||||
|
// send response head and return on eof.
|
||||||
|
let mut stream = tx
|
||||||
|
.send_response(res, eof)
|
||||||
|
.map_err(DispatchError::SendResponse)?;
|
||||||
|
|
||||||
|
if eof {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// poll response body and send chunks to client.
|
||||||
|
actix_rt::pin!(body);
|
||||||
|
|
||||||
|
while let Some(res) = poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
||||||
|
let mut chunk = res.map_err(|err| DispatchError::ResponseBody(err.into()))?;
|
||||||
|
|
||||||
|
'send: loop {
|
||||||
|
// reserve enough space and wait for stream ready.
|
||||||
|
stream.reserve_capacity(cmp::min(chunk.len(), CHUNK_SIZE));
|
||||||
|
|
||||||
|
match poll_fn(|cx| stream.poll_capacity(cx)).await {
|
||||||
|
// No capacity left. drop body and return.
|
||||||
|
None => return Ok(()),
|
||||||
|
Some(res) => {
|
||||||
|
// Split chuck to writeable size and send to client.
|
||||||
|
let cap = res.map_err(DispatchError::SendData)?;
|
||||||
|
|
||||||
|
let len = chunk.len();
|
||||||
|
let bytes = chunk.split_to(cmp::min(cap, len));
|
||||||
|
|
||||||
|
stream
|
||||||
|
.send_data(bytes, false)
|
||||||
|
.map_err(DispatchError::SendData)?;
|
||||||
|
|
||||||
|
// Current chuck completely sent. break send loop and poll next one.
|
||||||
|
if chunk.is_empty() {
|
||||||
|
break 'send;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// response body streaming finished. send end of stream and return.
|
||||||
|
stream
|
||||||
|
.send_data(Bytes::new(), true)
|
||||||
|
.map_err(DispatchError::SendData)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pin_project::pin_project]
|
fn prepare_response(
|
||||||
struct ServiceResponse<F, I, E, B> {
|
|
||||||
#[pin]
|
|
||||||
state: ServiceResponseState<F, B>,
|
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
buffer: Option<Bytes>,
|
head: &ResponseHead,
|
||||||
_phantom: PhantomData<(I, E)>,
|
size: &mut BodySize,
|
||||||
}
|
) -> http::Response<()> {
|
||||||
|
let mut has_date = false;
|
||||||
|
let mut skip_len = size != &BodySize::Stream;
|
||||||
|
|
||||||
#[pin_project::pin_project(project = ServiceResponseStateProj)]
|
let mut res = http::Response::new(());
|
||||||
enum ServiceResponseState<F, B> {
|
*res.status_mut() = head.status;
|
||||||
ServiceCall(#[pin] F, Option<SendResponse<Bytes>>),
|
*res.version_mut() = http::Version::HTTP_2;
|
||||||
SendPayload(SendStream<Bytes>, #[pin] ResponseBody<B>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F, I, E, B> ServiceResponse<F, I, E, B>
|
// Content length
|
||||||
where
|
match head.status {
|
||||||
F: Future<Output = Result<I, E>>,
|
http::StatusCode::NO_CONTENT
|
||||||
E: Into<Error>,
|
| http::StatusCode::CONTINUE
|
||||||
I: Into<Response<B>>,
|
| http::StatusCode::PROCESSING => *size = BodySize::None,
|
||||||
B: MessageBody,
|
http::StatusCode::SWITCHING_PROTOCOLS => {
|
||||||
{
|
skip_len = true;
|
||||||
fn prepare_response(
|
*size = BodySize::Stream;
|
||||||
&self,
|
}
|
||||||
head: &ResponseHead,
|
_ => {}
|
||||||
size: &mut BodySize,
|
}
|
||||||
) -> http::Response<()> {
|
|
||||||
let mut has_date = false;
|
|
||||||
let mut skip_len = size != &BodySize::Stream;
|
|
||||||
|
|
||||||
let mut res = http::Response::new(());
|
let _ = match size {
|
||||||
*res.status_mut() = head.status;
|
BodySize::None | BodySize::Stream => None,
|
||||||
*res.version_mut() = http::Version::HTTP_2;
|
BodySize::Empty => res
|
||||||
|
.headers_mut()
|
||||||
|
.insert(CONTENT_LENGTH, HeaderValue::from_static("0")),
|
||||||
|
BodySize::Sized(len) => {
|
||||||
|
let mut buf = itoa::Buffer::new();
|
||||||
|
|
||||||
// Content length
|
res.headers_mut().insert(
|
||||||
match head.status {
|
CONTENT_LENGTH,
|
||||||
http::StatusCode::NO_CONTENT
|
HeaderValue::from_str(buf.format(*len)).unwrap(),
|
||||||
| http::StatusCode::CONTINUE
|
)
|
||||||
| http::StatusCode::PROCESSING => *size = BodySize::None,
|
}
|
||||||
http::StatusCode::SWITCHING_PROTOCOLS => {
|
};
|
||||||
skip_len = true;
|
|
||||||
*size = BodySize::Stream;
|
// copy headers
|
||||||
}
|
for (key, value) in head.headers.iter() {
|
||||||
|
match *key {
|
||||||
|
// TODO: consider skipping other headers according to:
|
||||||
|
// https://tools.ietf.org/html/rfc7540#section-8.1.2.2
|
||||||
|
// omit HTTP/1.x only headers
|
||||||
|
CONNECTION | TRANSFER_ENCODING => continue,
|
||||||
|
CONTENT_LENGTH if skip_len => continue,
|
||||||
|
DATE => has_date = true,
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
let _ = match size {
|
res.headers_mut().append(key, value.clone());
|
||||||
BodySize::None | BodySize::Stream => None,
|
|
||||||
BodySize::Empty => res
|
|
||||||
.headers_mut()
|
|
||||||
.insert(CONTENT_LENGTH, HeaderValue::from_static("0")),
|
|
||||||
BodySize::Sized(len) => {
|
|
||||||
let mut buf = itoa::Buffer::new();
|
|
||||||
|
|
||||||
res.headers_mut().insert(
|
|
||||||
CONTENT_LENGTH,
|
|
||||||
HeaderValue::from_str(buf.format(*len)).unwrap(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// copy headers
|
|
||||||
for (key, value) in head.headers.iter() {
|
|
||||||
match *key {
|
|
||||||
// TODO: consider skipping other headers according to:
|
|
||||||
// https://tools.ietf.org/html/rfc7540#section-8.1.2.2
|
|
||||||
// omit HTTP/1.x only headers
|
|
||||||
CONNECTION | TRANSFER_ENCODING => continue,
|
|
||||||
CONTENT_LENGTH if skip_len => continue,
|
|
||||||
DATE => has_date = true,
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
res.headers_mut().append(key, value.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
// set date header
|
|
||||||
if !has_date {
|
|
||||||
let mut bytes = BytesMut::with_capacity(29);
|
|
||||||
self.config.set_date_header(&mut bytes);
|
|
||||||
res.headers_mut().insert(
|
|
||||||
DATE,
|
|
||||||
// SAFETY: serialized date-times are known ASCII strings
|
|
||||||
unsafe { HeaderValue::from_maybe_shared_unchecked(bytes.freeze()) },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
res
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl<F, I, E, B> Future for ServiceResponse<F, I, E, B>
|
// set date header
|
||||||
where
|
if !has_date {
|
||||||
F: Future<Output = Result<I, E>>,
|
let mut bytes = BytesMut::with_capacity(29);
|
||||||
E: Into<Error>,
|
config.set_date_header(&mut bytes);
|
||||||
I: Into<Response<B>>,
|
res.headers_mut().insert(
|
||||||
B: MessageBody,
|
DATE,
|
||||||
{
|
// SAFETY: serialized date-times are known ASCII strings
|
||||||
type Output = ();
|
unsafe { HeaderValue::from_maybe_shared_unchecked(bytes.freeze()) },
|
||||||
|
);
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
||||||
let mut this = self.as_mut().project();
|
|
||||||
|
|
||||||
match this.state.project() {
|
|
||||||
ServiceResponseStateProj::ServiceCall(call, send) => {
|
|
||||||
match ready!(call.poll(cx)) {
|
|
||||||
Ok(res) => {
|
|
||||||
let (res, body) = res.into().replace_body(());
|
|
||||||
|
|
||||||
let mut send = send.take().unwrap();
|
|
||||||
let mut size = body.size();
|
|
||||||
let h2_res =
|
|
||||||
self.as_mut().prepare_response(res.head(), &mut size);
|
|
||||||
this = self.as_mut().project();
|
|
||||||
|
|
||||||
let stream = match send.send_response(h2_res, size.is_eof()) {
|
|
||||||
Err(e) => {
|
|
||||||
trace!("Error sending HTTP/2 response: {:?}", e);
|
|
||||||
return Poll::Ready(());
|
|
||||||
}
|
|
||||||
Ok(stream) => stream,
|
|
||||||
};
|
|
||||||
|
|
||||||
if size.is_eof() {
|
|
||||||
Poll::Ready(())
|
|
||||||
} else {
|
|
||||||
this.state
|
|
||||||
.set(ServiceResponseState::SendPayload(stream, body));
|
|
||||||
self.poll(cx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(e) => {
|
|
||||||
let res: Response = e.into().into();
|
|
||||||
let (res, body) = res.replace_body(());
|
|
||||||
|
|
||||||
let mut send = send.take().unwrap();
|
|
||||||
let mut size = body.size();
|
|
||||||
let h2_res =
|
|
||||||
self.as_mut().prepare_response(res.head(), &mut size);
|
|
||||||
this = self.as_mut().project();
|
|
||||||
|
|
||||||
let stream = match send.send_response(h2_res, size.is_eof()) {
|
|
||||||
Err(e) => {
|
|
||||||
trace!("Error sending HTTP/2 response: {:?}", e);
|
|
||||||
return Poll::Ready(());
|
|
||||||
}
|
|
||||||
Ok(stream) => stream,
|
|
||||||
};
|
|
||||||
|
|
||||||
if size.is_eof() {
|
|
||||||
Poll::Ready(())
|
|
||||||
} else {
|
|
||||||
this.state.set(ServiceResponseState::SendPayload(
|
|
||||||
stream,
|
|
||||||
body.into_body(),
|
|
||||||
));
|
|
||||||
self.poll(cx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ServiceResponseStateProj::SendPayload(ref mut stream, ref mut body) => {
|
|
||||||
loop {
|
|
||||||
match this.buffer {
|
|
||||||
Some(ref mut buffer) => match ready!(stream.poll_capacity(cx)) {
|
|
||||||
None => return Poll::Ready(()),
|
|
||||||
|
|
||||||
Some(Ok(cap)) => {
|
|
||||||
let len = buffer.len();
|
|
||||||
let bytes = buffer.split_to(cmp::min(cap, len));
|
|
||||||
|
|
||||||
if let Err(e) = stream.send_data(bytes, false) {
|
|
||||||
warn!("{:?}", e);
|
|
||||||
return Poll::Ready(());
|
|
||||||
} else if !buffer.is_empty() {
|
|
||||||
let cap = cmp::min(buffer.len(), CHUNK_SIZE);
|
|
||||||
stream.reserve_capacity(cap);
|
|
||||||
} else {
|
|
||||||
this.buffer.take();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(Err(e)) => {
|
|
||||||
warn!("{:?}", e);
|
|
||||||
return Poll::Ready(());
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
None => match ready!(body.as_mut().poll_next(cx)) {
|
|
||||||
None => {
|
|
||||||
if let Err(e) = stream.send_data(Bytes::new(), true) {
|
|
||||||
warn!("{:?}", e);
|
|
||||||
}
|
|
||||||
return Poll::Ready(());
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(Ok(chunk)) => {
|
|
||||||
stream
|
|
||||||
.reserve_capacity(cmp::min(chunk.len(), CHUNK_SIZE));
|
|
||||||
*this.buffer = Some(chunk);
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(Err(e)) => {
|
|
||||||
error!("Response payload stream error: {:?}", e);
|
|
||||||
return Poll::Ready(());
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
@ -7,8 +7,8 @@ use std::{net, rc::Rc};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
fn_factory, fn_service, pipeline_factory, IntoServiceFactory, Service,
|
fn_factory, fn_service, IntoServiceFactory, Service, ServiceFactory,
|
||||||
ServiceFactory,
|
ServiceFactoryExt as _,
|
||||||
};
|
};
|
||||||
use actix_utils::future::ready;
|
use actix_utils::future::ready;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
@ -40,7 +40,9 @@ where
|
|||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create new `H2Service` instance with config.
|
/// Create new `H2Service` instance with config.
|
||||||
pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
|
pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
|
||||||
@ -69,7 +71,9 @@ where
|
|||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create plain TCP based service
|
/// Create plain TCP based service
|
||||||
pub fn tcp(
|
pub fn tcp(
|
||||||
@ -81,12 +85,12 @@ where
|
|||||||
Error = DispatchError,
|
Error = DispatchError,
|
||||||
InitError = S::InitError,
|
InitError = S::InitError,
|
||||||
> {
|
> {
|
||||||
pipeline_factory(fn_factory(|| {
|
fn_factory(|| {
|
||||||
ready(Ok::<_, S::InitError>(fn_service(|io: TcpStream| {
|
ready(Ok::<_, S::InitError>(fn_service(|io: TcpStream| {
|
||||||
let peer_addr = io.peer_addr().ok();
|
let peer_addr = io.peer_addr().ok();
|
||||||
ready(Ok::<_, DispatchError>((io, peer_addr)))
|
ready(Ok::<_, DispatchError>((io, peer_addr)))
|
||||||
})))
|
})))
|
||||||
}))
|
})
|
||||||
.and_then(self)
|
.and_then(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -106,7 +110,9 @@ mod openssl {
|
|||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create OpenSSL based service
|
/// Create OpenSSL based service
|
||||||
pub fn openssl(
|
pub fn openssl(
|
||||||
@ -119,20 +125,18 @@ mod openssl {
|
|||||||
Error = TlsError<SslError, DispatchError>,
|
Error = TlsError<SslError, DispatchError>,
|
||||||
InitError = S::InitError,
|
InitError = S::InitError,
|
||||||
> {
|
> {
|
||||||
pipeline_factory(
|
Acceptor::new(acceptor)
|
||||||
Acceptor::new(acceptor)
|
.map_err(TlsError::Tls)
|
||||||
.map_err(TlsError::Tls)
|
.map_init_err(|_| panic!())
|
||||||
.map_init_err(|_| panic!()),
|
.and_then(fn_factory(|| {
|
||||||
)
|
ready(Ok::<_, S::InitError>(fn_service(
|
||||||
.and_then(fn_factory(|| {
|
|io: TlsStream<TcpStream>| {
|
||||||
ready(Ok::<_, S::InitError>(fn_service(
|
let peer_addr = io.get_ref().peer_addr().ok();
|
||||||
|io: TlsStream<TcpStream>| {
|
ready(Ok((io, peer_addr)))
|
||||||
let peer_addr = io.get_ref().peer_addr().ok();
|
},
|
||||||
ready(Ok((io, peer_addr)))
|
)))
|
||||||
},
|
}))
|
||||||
)))
|
.and_then(self.map_err(TlsError::Service))
|
||||||
}))
|
|
||||||
.and_then(self.map_err(TlsError::Service))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -152,7 +156,9 @@ mod rustls {
|
|||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create Rustls based service
|
/// Create Rustls based service
|
||||||
pub fn rustls(
|
pub fn rustls(
|
||||||
@ -168,20 +174,18 @@ mod rustls {
|
|||||||
let protos = vec!["h2".to_string().into()];
|
let protos = vec!["h2".to_string().into()];
|
||||||
config.set_protocols(&protos);
|
config.set_protocols(&protos);
|
||||||
|
|
||||||
pipeline_factory(
|
Acceptor::new(config)
|
||||||
Acceptor::new(config)
|
.map_err(TlsError::Tls)
|
||||||
.map_err(TlsError::Tls)
|
.map_init_err(|_| panic!())
|
||||||
.map_init_err(|_| panic!()),
|
.and_then(fn_factory(|| {
|
||||||
)
|
ready(Ok::<_, S::InitError>(fn_service(
|
||||||
.and_then(fn_factory(|| {
|
|io: TlsStream<TcpStream>| {
|
||||||
ready(Ok::<_, S::InitError>(fn_service(
|
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||||
|io: TlsStream<TcpStream>| {
|
ready(Ok((io, peer_addr)))
|
||||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
},
|
||||||
ready(Ok((io, peer_addr)))
|
)))
|
||||||
},
|
}))
|
||||||
)))
|
.and_then(self.map_err(TlsError::Service))
|
||||||
}))
|
|
||||||
.and_then(self.map_err(TlsError::Service))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -189,12 +193,15 @@ mod rustls {
|
|||||||
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
|
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||||
|
|
||||||
S: ServiceFactory<Request, Config = ()>,
|
S: ServiceFactory<Request, Config = ()>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -256,6 +263,7 @@ where
|
|||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = DispatchError;
|
type Error = DispatchError;
|
||||||
@ -320,6 +328,7 @@ where
|
|||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
type Output = Result<(), DispatchError>;
|
type Output = Result<(), DispatchError>;
|
||||||
|
|
||||||
|
@ -1,9 +1,33 @@
|
|||||||
//! Typed HTTP headers, pre-defined `HeaderName`s, traits for parsing and conversion, and other
|
//! Pre-defined `HeaderName`s, traits for parsing and conversion, and other header utility methods.
|
||||||
//! header utility methods.
|
|
||||||
|
|
||||||
use percent_encoding::{AsciiSet, CONTROLS};
|
use percent_encoding::{AsciiSet, CONTROLS};
|
||||||
|
|
||||||
pub use http::header::*;
|
// re-export from http except header map related items
|
||||||
|
pub use http::header::{
|
||||||
|
HeaderName, HeaderValue, InvalidHeaderName, InvalidHeaderValue, ToStrError,
|
||||||
|
};
|
||||||
|
|
||||||
|
// re-export const header names
|
||||||
|
pub use http::header::{
|
||||||
|
ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCEPT_RANGES,
|
||||||
|
ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS,
|
||||||
|
ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
|
||||||
|
ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE,
|
||||||
|
ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, AGE, ALLOW, ALT_SVC,
|
||||||
|
AUTHORIZATION, CACHE_CONTROL, CONNECTION, CONTENT_DISPOSITION, CONTENT_ENCODING,
|
||||||
|
CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_LOCATION, CONTENT_RANGE,
|
||||||
|
CONTENT_SECURITY_POLICY, CONTENT_SECURITY_POLICY_REPORT_ONLY, CONTENT_TYPE, COOKIE,
|
||||||
|
DATE, DNT, ETAG, EXPECT, EXPIRES, FORWARDED, FROM, HOST, IF_MATCH,
|
||||||
|
IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, IF_UNMODIFIED_SINCE, LAST_MODIFIED,
|
||||||
|
LINK, LOCATION, MAX_FORWARDS, ORIGIN, PRAGMA, PROXY_AUTHENTICATE,
|
||||||
|
PROXY_AUTHORIZATION, PUBLIC_KEY_PINS, PUBLIC_KEY_PINS_REPORT_ONLY, RANGE, REFERER,
|
||||||
|
REFERRER_POLICY, REFRESH, RETRY_AFTER, SEC_WEBSOCKET_ACCEPT,
|
||||||
|
SEC_WEBSOCKET_EXTENSIONS, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_PROTOCOL,
|
||||||
|
SEC_WEBSOCKET_VERSION, SERVER, SET_COOKIE, STRICT_TRANSPORT_SECURITY, TE, TRAILER,
|
||||||
|
TRANSFER_ENCODING, UPGRADE, UPGRADE_INSECURE_REQUESTS, USER_AGENT, VARY, VIA,
|
||||||
|
WARNING, WWW_AUTHENTICATE, X_CONTENT_TYPE_OPTIONS, X_DNS_PREFETCH_CONTROL,
|
||||||
|
X_FRAME_OPTIONS, X_XSS_PROTECTION,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::error::ParseError;
|
use crate::error::ParseError;
|
||||||
use crate::HttpMessage;
|
use crate::HttpMessage;
|
||||||
|
@ -104,7 +104,7 @@ impl Display for Charset {
|
|||||||
impl FromStr for Charset {
|
impl FromStr for Charset {
|
||||||
type Err = crate::Error;
|
type Err = crate::Error;
|
||||||
|
|
||||||
fn from_str(s: &str) -> crate::Result<Charset> {
|
fn from_str(s: &str) -> Result<Charset, crate::Error> {
|
||||||
Ok(match s.to_ascii_uppercase().as_ref() {
|
Ok(match s.to_ascii_uppercase().as_ref() {
|
||||||
"US-ASCII" => Us_Ascii,
|
"US-ASCII" => Us_Ascii,
|
||||||
"ISO-8859-1" => Iso_8859_1,
|
"ISO-8859-1" => Iso_8859_1,
|
||||||
|
@ -41,6 +41,8 @@ pub fn write_content_length<B: BufMut>(n: u64, buf: &mut B) {
|
|||||||
buf.put_slice(b"\r\n");
|
buf.put_slice(b"\r\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: bench why this is needed vs Buf::writer
|
||||||
|
/// An `io` writer for a `BufMut` that should only be used once and on an empty buffer.
|
||||||
pub(crate) struct Writer<'a, B>(pub &'a mut B);
|
pub(crate) struct Writer<'a, B>(pub &'a mut B);
|
||||||
|
|
||||||
impl<'a, B> io::Write for Writer<'a, B>
|
impl<'a, B> io::Write for Writer<'a, B>
|
||||||
|
@ -1,19 +1,18 @@
|
|||||||
use std::cell::{Ref, RefMut};
|
use std::{
|
||||||
use std::str;
|
cell::{Ref, RefMut},
|
||||||
|
str,
|
||||||
|
};
|
||||||
|
|
||||||
use encoding_rs::{Encoding, UTF_8};
|
use encoding_rs::{Encoding, UTF_8};
|
||||||
use http::header;
|
use http::header;
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
|
|
||||||
use crate::error::{ContentTypeError, ParseError};
|
use crate::{
|
||||||
use crate::extensions::Extensions;
|
error::{ContentTypeError, ParseError},
|
||||||
use crate::header::{Header, HeaderMap};
|
header::{Header, HeaderMap},
|
||||||
use crate::payload::Payload;
|
payload::Payload,
|
||||||
#[cfg(feature = "cookies")]
|
Extensions,
|
||||||
use crate::{cookie::Cookie, error::CookieParseError};
|
};
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
struct Cookies(Vec<Cookie<'static>>);
|
|
||||||
|
|
||||||
/// Trait that implements general purpose operations on HTTP messages.
|
/// Trait that implements general purpose operations on HTTP messages.
|
||||||
pub trait HttpMessage: Sized {
|
pub trait HttpMessage: Sized {
|
||||||
@ -104,41 +103,6 @@ pub trait HttpMessage: Sized {
|
|||||||
Ok(false)
|
Ok(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load request cookies.
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
|
|
||||||
if self.extensions().get::<Cookies>().is_none() {
|
|
||||||
let mut cookies = Vec::new();
|
|
||||||
for hdr in self.headers().get_all(header::COOKIE) {
|
|
||||||
let s =
|
|
||||||
str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
|
|
||||||
for cookie_str in s.split(';').map(|s| s.trim()) {
|
|
||||||
if !cookie_str.is_empty() {
|
|
||||||
cookies.push(Cookie::parse_encoded(cookie_str)?.into_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.extensions_mut().insert(Cookies(cookies));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Ref::map(self.extensions(), |ext| {
|
|
||||||
&ext.get::<Cookies>().unwrap().0
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Return request cookie.
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
|
|
||||||
if let Ok(cookies) = self.cookies() {
|
|
||||||
for cookie in cookies.iter() {
|
|
||||||
if cookie.name() == name {
|
|
||||||
return Some(cookie.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, T> HttpMessage for &'a mut T
|
impl<'a, T> HttpMessage for &'a mut T
|
||||||
|
@ -6,13 +6,10 @@
|
|||||||
//! | `openssl` | TLS support via [OpenSSL]. |
|
//! | `openssl` | TLS support via [OpenSSL]. |
|
||||||
//! | `rustls` | TLS support via [rustls]. |
|
//! | `rustls` | TLS support via [rustls]. |
|
||||||
//! | `compress` | Payload compression support. (Deflate, Gzip & Brotli) |
|
//! | `compress` | Payload compression support. (Deflate, Gzip & Brotli) |
|
||||||
//! | `cookies` | Support for cookies backed by the [cookie] crate. |
|
|
||||||
//! | `secure-cookies` | Adds for secure cookies. Enables `cookies` feature. |
|
|
||||||
//! | `trust-dns` | Use [trust-dns] as the client DNS resolver. |
|
//! | `trust-dns` | Use [trust-dns] as the client DNS resolver. |
|
||||||
//!
|
//!
|
||||||
//! [OpenSSL]: https://crates.io/crates/openssl
|
//! [OpenSSL]: https://crates.io/crates/openssl
|
||||||
//! [rustls]: https://crates.io/crates/rustls
|
//! [rustls]: https://crates.io/crates/rustls
|
||||||
//! [cookie]: https://crates.io/crates/cookie
|
|
||||||
//! [trust-dns]: https://crates.io/crates/trust-dns
|
//! [trust-dns]: https://crates.io/crates/trust-dns
|
||||||
|
|
||||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||||
@ -38,14 +35,14 @@ mod config;
|
|||||||
#[cfg(feature = "compress")]
|
#[cfg(feature = "compress")]
|
||||||
pub mod encoding;
|
pub mod encoding;
|
||||||
mod extensions;
|
mod extensions;
|
||||||
mod header;
|
pub mod header;
|
||||||
mod helpers;
|
mod helpers;
|
||||||
mod http_codes;
|
|
||||||
mod http_message;
|
mod http_message;
|
||||||
mod message;
|
mod message;
|
||||||
mod payload;
|
mod payload;
|
||||||
mod request;
|
mod request;
|
||||||
mod response;
|
mod response;
|
||||||
|
mod response_builder;
|
||||||
mod service;
|
mod service;
|
||||||
mod time_parser;
|
mod time_parser;
|
||||||
|
|
||||||
@ -55,20 +52,24 @@ pub mod h2;
|
|||||||
pub mod test;
|
pub mod test;
|
||||||
pub mod ws;
|
pub mod ws;
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
pub use cookie;
|
|
||||||
|
|
||||||
pub use self::builder::HttpServiceBuilder;
|
pub use self::builder::HttpServiceBuilder;
|
||||||
pub use self::config::{KeepAlive, ServiceConfig};
|
pub use self::config::{KeepAlive, ServiceConfig};
|
||||||
pub use self::error::{Error, ResponseError, Result};
|
pub use self::error::{Error, ResponseError};
|
||||||
pub use self::extensions::Extensions;
|
pub use self::extensions::Extensions;
|
||||||
|
pub use self::header::ContentEncoding;
|
||||||
pub use self::http_message::HttpMessage;
|
pub use self::http_message::HttpMessage;
|
||||||
|
pub use self::message::ConnectionType;
|
||||||
pub use self::message::{Message, RequestHead, RequestHeadType, ResponseHead};
|
pub use self::message::{Message, RequestHead, RequestHeadType, ResponseHead};
|
||||||
pub use self::payload::{Payload, PayloadStream};
|
pub use self::payload::{Payload, PayloadStream};
|
||||||
pub use self::request::Request;
|
pub use self::request::Request;
|
||||||
pub use self::response::{Response, ResponseBuilder};
|
pub use self::response::Response;
|
||||||
|
pub use self::response_builder::ResponseBuilder;
|
||||||
pub use self::service::HttpService;
|
pub use self::service::HttpService;
|
||||||
|
|
||||||
|
pub use ::http::{uri, uri::Uri};
|
||||||
|
pub use ::http::{Method, StatusCode, Version};
|
||||||
|
|
||||||
|
// TODO: deprecate this mish-mash of random items
|
||||||
pub mod http {
|
pub mod http {
|
||||||
//! Various HTTP related types.
|
//! Various HTTP related types.
|
||||||
|
|
||||||
@ -78,8 +79,6 @@ pub mod http {
|
|||||||
pub use http::{uri, Error, Uri};
|
pub use http::{uri, Error, Uri};
|
||||||
pub use http::{Method, StatusCode, Version};
|
pub use http::{Method, StatusCode, Version};
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
pub use crate::cookie::{Cookie, CookieBuilder};
|
|
||||||
pub use crate::header::HeaderMap;
|
pub use crate::header::HeaderMap;
|
||||||
|
|
||||||
/// A collection of HTTP headers and helpers.
|
/// A collection of HTTP headers and helpers.
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
|
#[doc(hidden)]
|
||||||
macro_rules! downcast_get_type_id {
|
macro_rules! downcast_get_type_id {
|
||||||
() => {
|
() => {
|
||||||
/// A helper method to get the type ID of the type
|
/// A helper method to get the type ID of the type
|
||||||
@ -14,8 +15,15 @@ macro_rules! downcast_get_type_id {
|
|||||||
/// making it impossible for safe code to construct outside of
|
/// making it impossible for safe code to construct outside of
|
||||||
/// this module. This ensures that safe code cannot violate
|
/// this module. This ensures that safe code cannot violate
|
||||||
/// type-safety by implementing this method.
|
/// type-safety by implementing this method.
|
||||||
|
///
|
||||||
|
/// We also take `PrivateHelper` as a parameter, to ensure that
|
||||||
|
/// safe code cannot obtain a `PrivateHelper` instance by
|
||||||
|
/// delegating to an existing implementation of `__private_get_type_id__`
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
fn __private_get_type_id__(&self) -> (std::any::TypeId, PrivateHelper)
|
fn __private_get_type_id__(
|
||||||
|
&self,
|
||||||
|
_: PrivateHelper,
|
||||||
|
) -> (std::any::TypeId, PrivateHelper)
|
||||||
where
|
where
|
||||||
Self: 'static,
|
Self: 'static,
|
||||||
{
|
{
|
||||||
@ -25,6 +33,7 @@ macro_rules! downcast_get_type_id {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Generate implementation for dyn $name
|
//Generate implementation for dyn $name
|
||||||
|
#[doc(hidden)]
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! downcast {
|
macro_rules! downcast {
|
||||||
($name:ident) => {
|
($name:ident) => {
|
||||||
@ -37,7 +46,9 @@ macro_rules! downcast {
|
|||||||
impl dyn $name + 'static {
|
impl dyn $name + 'static {
|
||||||
/// Downcasts generic body to a specific type.
|
/// Downcasts generic body to a specific type.
|
||||||
pub fn downcast_ref<T: $name + 'static>(&self) -> Option<&T> {
|
pub fn downcast_ref<T: $name + 'static>(&self) -> Option<&T> {
|
||||||
if self.__private_get_type_id__().0 == std::any::TypeId::of::<T>() {
|
if self.__private_get_type_id__(PrivateHelper(())).0
|
||||||
|
== std::any::TypeId::of::<T>()
|
||||||
|
{
|
||||||
// SAFETY: external crates cannot override the default
|
// SAFETY: external crates cannot override the default
|
||||||
// implementation of `__private_get_type_id__`, since
|
// implementation of `__private_get_type_id__`, since
|
||||||
// it requires returning a private type. We can therefore
|
// it requires returning a private type. We can therefore
|
||||||
@ -51,7 +62,9 @@ macro_rules! downcast {
|
|||||||
|
|
||||||
/// Downcasts a generic body to a mutable specific type.
|
/// Downcasts a generic body to a mutable specific type.
|
||||||
pub fn downcast_mut<T: $name + 'static>(&mut self) -> Option<&mut T> {
|
pub fn downcast_mut<T: $name + 'static>(&mut self) -> Option<&mut T> {
|
||||||
if self.__private_get_type_id__().0 == std::any::TypeId::of::<T>() {
|
if self.__private_get_type_id__(PrivateHelper(())).0
|
||||||
|
== std::any::TypeId::of::<T>()
|
||||||
|
{
|
||||||
// SAFETY: external crates cannot override the default
|
// SAFETY: external crates cannot override the default
|
||||||
// implementation of `__private_get_type_id__`, since
|
// implementation of `__private_get_type_id__`, since
|
||||||
// it requires returning a private type. We can therefore
|
// it requires returning a private type. We can therefore
|
||||||
@ -70,6 +83,7 @@ macro_rules! downcast {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
#![allow(clippy::upper_case_acronyms)]
|
||||||
|
|
||||||
trait MB {
|
trait MB {
|
||||||
downcast_get_type_id!();
|
downcast_get_type_id!();
|
||||||
|
@ -1,12 +1,15 @@
|
|||||||
use std::cell::{Ref, RefCell, RefMut};
|
use std::{
|
||||||
use std::net;
|
cell::{Ref, RefCell, RefMut},
|
||||||
use std::rc::Rc;
|
net,
|
||||||
|
rc::Rc,
|
||||||
|
};
|
||||||
|
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
|
|
||||||
use crate::extensions::Extensions;
|
use crate::{
|
||||||
use crate::header::HeaderMap;
|
header::{self, HeaderMap},
|
||||||
use crate::http::{header, Method, StatusCode, Uri, Version};
|
Extensions, Method, StatusCode, Uri, Version,
|
||||||
|
};
|
||||||
|
|
||||||
/// Represents various types of connection
|
/// Represents various types of connection
|
||||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
#[derive(Copy, Clone, PartialEq, Debug)]
|
||||||
@ -290,14 +293,14 @@ impl ResponseHead {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
|
||||||
/// Check if keep-alive is enabled
|
/// Check if keep-alive is enabled
|
||||||
|
#[inline]
|
||||||
pub fn keep_alive(&self) -> bool {
|
pub fn keep_alive(&self) -> bool {
|
||||||
self.connection_type() == ConnectionType::KeepAlive
|
self.connection_type() == ConnectionType::KeepAlive
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
|
||||||
/// Check upgrade status of this message
|
/// Check upgrade status of this message
|
||||||
|
#[inline]
|
||||||
pub fn upgrade(&self) -> bool {
|
pub fn upgrade(&self) -> bool {
|
||||||
self.connection_type() == ConnectionType::Upgrade
|
self.connection_type() == ConnectionType::Upgrade
|
||||||
}
|
}
|
||||||
@ -345,8 +348,8 @@ impl ResponseHead {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct Message<T: Head> {
|
pub struct Message<T: Head> {
|
||||||
// Rc here should not be cloned by anyone.
|
/// Rc here should not be cloned by anyone.
|
||||||
// It's used to reuse allocation of T and no shared ownership is allowed.
|
/// It's used to reuse allocation of T and no shared ownership is allowed.
|
||||||
head: Rc<T>,
|
head: Rc<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -386,12 +389,6 @@ impl BoxedResponseHead {
|
|||||||
pub fn new(status: StatusCode) -> Self {
|
pub fn new(status: StatusCode) -> Self {
|
||||||
RESPONSE_POOL.with(|p| p.get_message(status))
|
RESPONSE_POOL.with(|p| p.get_message(status))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn take(&mut self) -> Self {
|
|
||||||
BoxedResponseHead {
|
|
||||||
head: self.head.take(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::ops::Deref for BoxedResponseHead {
|
impl std::ops::Deref for BoxedResponseHead {
|
||||||
|
@ -2,16 +2,18 @@
|
|||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
cell::{Ref, RefMut},
|
cell::{Ref, RefMut},
|
||||||
fmt, net,
|
fmt, net, str,
|
||||||
};
|
};
|
||||||
|
|
||||||
use http::{header, Method, Uri, Version};
|
use http::{header, Method, Uri, Version};
|
||||||
|
|
||||||
use crate::extensions::Extensions;
|
use crate::{
|
||||||
use crate::header::HeaderMap;
|
extensions::Extensions,
|
||||||
use crate::message::{Message, RequestHead};
|
header::HeaderMap,
|
||||||
use crate::payload::{Payload, PayloadStream};
|
message::{Message, RequestHead},
|
||||||
use crate::HttpMessage;
|
payload::{Payload, PayloadStream},
|
||||||
|
HttpMessage,
|
||||||
|
};
|
||||||
|
|
||||||
/// Request
|
/// Request
|
||||||
pub struct Request<P = PayloadStream> {
|
pub struct Request<P = PayloadStream> {
|
||||||
|
File diff suppressed because it is too large
Load Diff
463
actix-http/src/response_builder.rs
Normal file
463
actix-http/src/response_builder.rs
Normal file
@ -0,0 +1,463 @@
|
|||||||
|
//! HTTP response builder.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
cell::{Ref, RefMut},
|
||||||
|
fmt,
|
||||||
|
future::Future,
|
||||||
|
pin::Pin,
|
||||||
|
str,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
|
use futures_core::Stream;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
body::{Body, BodyStream},
|
||||||
|
error::{Error, HttpError},
|
||||||
|
header::{self, IntoHeaderPair, IntoHeaderValue},
|
||||||
|
message::{BoxedResponseHead, ConnectionType, ResponseHead},
|
||||||
|
Extensions, Response, StatusCode,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// An HTTP response builder.
|
||||||
|
///
|
||||||
|
/// Used to construct an instance of `Response` using a builder pattern. Response builders are often
|
||||||
|
/// created using [`Response::build`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_http::{Response, ResponseBuilder, body, http::StatusCode, http::header};
|
||||||
|
///
|
||||||
|
/// # actix_rt::System::new().block_on(async {
|
||||||
|
/// let mut res: Response<_> = Response::build(StatusCode::OK)
|
||||||
|
/// .content_type(mime::APPLICATION_JSON)
|
||||||
|
/// .insert_header((header::SERVER, "my-app/1.0"))
|
||||||
|
/// .append_header((header::SET_COOKIE, "a=1"))
|
||||||
|
/// .append_header((header::SET_COOKIE, "b=2"))
|
||||||
|
/// .body("1234");
|
||||||
|
///
|
||||||
|
/// assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
///
|
||||||
|
/// assert!(res.headers().contains_key("server"));
|
||||||
|
/// assert_eq!(res.headers().get_all("set-cookie").count(), 2);
|
||||||
|
///
|
||||||
|
/// assert_eq!(body::to_bytes(res.into_body()).await.unwrap(), &b"1234"[..]);
|
||||||
|
/// # })
|
||||||
|
/// ```
|
||||||
|
pub struct ResponseBuilder {
|
||||||
|
head: Option<BoxedResponseHead>,
|
||||||
|
err: Option<HttpError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseBuilder {
|
||||||
|
/// Create response builder
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_http::{Response, ResponseBuilder, http::StatusCode};
|
||||||
|
///
|
||||||
|
/// let res: Response<_> = ResponseBuilder::default().finish();
|
||||||
|
/// assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
/// ```
|
||||||
|
#[inline]
|
||||||
|
pub fn new(status: StatusCode) -> Self {
|
||||||
|
ResponseBuilder {
|
||||||
|
head: Some(BoxedResponseHead::new(status)),
|
||||||
|
err: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set HTTP status code of this response.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_http::{ResponseBuilder, http::StatusCode};
|
||||||
|
///
|
||||||
|
/// let res = ResponseBuilder::default().status(StatusCode::NOT_FOUND).finish();
|
||||||
|
/// assert_eq!(res.status(), StatusCode::NOT_FOUND);
|
||||||
|
/// ```
|
||||||
|
#[inline]
|
||||||
|
pub fn status(&mut self, status: StatusCode) -> &mut Self {
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
parts.status = status;
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert a header, replacing any that were set with an equivalent field name.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_http::{ResponseBuilder, http::header};
|
||||||
|
///
|
||||||
|
/// let res = ResponseBuilder::default()
|
||||||
|
/// .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
|
||||||
|
/// .insert_header(("X-TEST", "value"))
|
||||||
|
/// .finish();
|
||||||
|
///
|
||||||
|
/// assert!(res.headers().contains_key("content-type"));
|
||||||
|
/// assert!(res.headers().contains_key("x-test"));
|
||||||
|
/// ```
|
||||||
|
pub fn insert_header<H>(&mut self, header: H) -> &mut Self
|
||||||
|
where
|
||||||
|
H: IntoHeaderPair,
|
||||||
|
{
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
match header.try_into_header_pair() {
|
||||||
|
Ok((key, value)) => {
|
||||||
|
parts.headers.insert(key, value);
|
||||||
|
}
|
||||||
|
Err(e) => self.err = Some(e.into()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append a header, keeping any that were set with an equivalent field name.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_http::{ResponseBuilder, http::header};
|
||||||
|
///
|
||||||
|
/// let res = ResponseBuilder::default()
|
||||||
|
/// .append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
|
||||||
|
/// .append_header(("X-TEST", "value1"))
|
||||||
|
/// .append_header(("X-TEST", "value2"))
|
||||||
|
/// .finish();
|
||||||
|
///
|
||||||
|
/// assert_eq!(res.headers().get_all("content-type").count(), 1);
|
||||||
|
/// assert_eq!(res.headers().get_all("x-test").count(), 2);
|
||||||
|
/// ```
|
||||||
|
pub fn append_header<H>(&mut self, header: H) -> &mut Self
|
||||||
|
where
|
||||||
|
H: IntoHeaderPair,
|
||||||
|
{
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
match header.try_into_header_pair() {
|
||||||
|
Ok((key, value)) => parts.headers.append(key, value),
|
||||||
|
Err(e) => self.err = Some(e.into()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the custom reason for the response.
|
||||||
|
#[inline]
|
||||||
|
pub fn reason(&mut self, reason: &'static str) -> &mut Self {
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
parts.reason = Some(reason);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set connection type to KeepAlive
|
||||||
|
#[inline]
|
||||||
|
pub fn keep_alive(&mut self) -> &mut Self {
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
parts.set_connection_type(ConnectionType::KeepAlive);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set connection type to Upgrade
|
||||||
|
#[inline]
|
||||||
|
pub fn upgrade<V>(&mut self, value: V) -> &mut Self
|
||||||
|
where
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
{
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
parts.set_connection_type(ConnectionType::Upgrade);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(value) = value.try_into_value() {
|
||||||
|
self.insert_header((header::UPGRADE, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Force close connection, even if it is marked as keep-alive
|
||||||
|
#[inline]
|
||||||
|
pub fn force_close(&mut self) -> &mut Self {
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
parts.set_connection_type(ConnectionType::Close);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
|
||||||
|
#[inline]
|
||||||
|
pub fn no_chunking(&mut self, len: u64) -> &mut Self {
|
||||||
|
let mut buf = itoa::Buffer::new();
|
||||||
|
self.insert_header((header::CONTENT_LENGTH, buf.format(len)));
|
||||||
|
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
parts.no_chunking(true);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set response content type.
|
||||||
|
#[inline]
|
||||||
|
pub fn content_type<V>(&mut self, value: V) -> &mut Self
|
||||||
|
where
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
{
|
||||||
|
if let Some(parts) = self.inner() {
|
||||||
|
match value.try_into_value() {
|
||||||
|
Ok(value) => {
|
||||||
|
parts.headers.insert(header::CONTENT_TYPE, value);
|
||||||
|
}
|
||||||
|
Err(e) => self.err = Some(e.into()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Responses extensions
|
||||||
|
#[inline]
|
||||||
|
pub fn extensions(&self) -> Ref<'_, Extensions> {
|
||||||
|
let head = self.head.as_ref().expect("cannot reuse response builder");
|
||||||
|
head.extensions.borrow()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mutable reference to a the response's extensions
|
||||||
|
#[inline]
|
||||||
|
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
|
||||||
|
let head = self.head.as_ref().expect("cannot reuse response builder");
|
||||||
|
head.extensions.borrow_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate response with a wrapped body.
|
||||||
|
///
|
||||||
|
/// This `ResponseBuilder` will be left in a useless state.
|
||||||
|
#[inline]
|
||||||
|
pub fn body<B: Into<Body>>(&mut self, body: B) -> Response<Body> {
|
||||||
|
self.message_body(body.into())
|
||||||
|
.unwrap_or_else(Response::from_error)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate response with a body.
|
||||||
|
///
|
||||||
|
/// This `ResponseBuilder` will be left in a useless state.
|
||||||
|
pub fn message_body<B>(&mut self, body: B) -> Result<Response<B>, Error> {
|
||||||
|
if let Some(err) = self.err.take() {
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let head = self.head.take().expect("cannot reuse response builder");
|
||||||
|
Ok(Response { head, body })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate response with a streaming body.
|
||||||
|
///
|
||||||
|
/// This `ResponseBuilder` will be left in a useless state.
|
||||||
|
#[inline]
|
||||||
|
pub fn streaming<S, E>(&mut self, stream: S) -> Response<Body>
|
||||||
|
where
|
||||||
|
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
|
||||||
|
E: Into<Error> + 'static,
|
||||||
|
{
|
||||||
|
self.body(Body::from_message(BodyStream::new(stream)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate response with an empty body.
|
||||||
|
///
|
||||||
|
/// This `ResponseBuilder` will be left in a useless state.
|
||||||
|
#[inline]
|
||||||
|
pub fn finish(&mut self) -> Response<Body> {
|
||||||
|
self.body(Body::Empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create an owned `ResponseBuilder`, leaving the original in a useless state.
|
||||||
|
pub fn take(&mut self) -> ResponseBuilder {
|
||||||
|
ResponseBuilder {
|
||||||
|
head: self.head.take(),
|
||||||
|
err: self.err.take(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get access to the inner response head if there has been no error.
|
||||||
|
fn inner(&mut self) -> Option<&mut ResponseHead> {
|
||||||
|
if self.err.is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.head.as_deref_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ResponseBuilder {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new(StatusCode::OK)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert `Response` to a `ResponseBuilder`. Body get dropped.
|
||||||
|
impl<B> From<Response<B>> for ResponseBuilder {
|
||||||
|
fn from(res: Response<B>) -> ResponseBuilder {
|
||||||
|
ResponseBuilder {
|
||||||
|
head: Some(res.head),
|
||||||
|
err: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert `ResponseHead` to a `ResponseBuilder`
|
||||||
|
impl<'a> From<&'a ResponseHead> for ResponseBuilder {
|
||||||
|
fn from(head: &'a ResponseHead) -> ResponseBuilder {
|
||||||
|
let mut msg = BoxedResponseHead::new(head.status);
|
||||||
|
msg.version = head.version;
|
||||||
|
msg.reason = head.reason;
|
||||||
|
|
||||||
|
for (k, v) in head.headers.iter() {
|
||||||
|
msg.headers.append(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
msg.no_chunking(!head.chunked());
|
||||||
|
|
||||||
|
ResponseBuilder {
|
||||||
|
head: Some(msg),
|
||||||
|
err: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Future for ResponseBuilder {
|
||||||
|
type Output = Result<Response<Body>, Error>;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
Poll::Ready(Ok(self.finish()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ResponseBuilder {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
let head = self.head.as_ref().unwrap();
|
||||||
|
|
||||||
|
let res = writeln!(
|
||||||
|
f,
|
||||||
|
"\nResponseBuilder {:?} {}{}",
|
||||||
|
head.version,
|
||||||
|
head.status,
|
||||||
|
head.reason.unwrap_or(""),
|
||||||
|
);
|
||||||
|
let _ = writeln!(f, " headers:");
|
||||||
|
for (key, val) in head.headers.iter() {
|
||||||
|
let _ = writeln!(f, " {:?}: {:?}", key, val);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::body::Body;
|
||||||
|
use crate::http::header::{HeaderName, HeaderValue, CONTENT_TYPE};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_basic_builder() {
|
||||||
|
let resp = Response::build(StatusCode::OK)
|
||||||
|
.insert_header(("X-TEST", "value"))
|
||||||
|
.finish();
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_upgrade() {
|
||||||
|
let resp = Response::build(StatusCode::OK)
|
||||||
|
.upgrade("websocket")
|
||||||
|
.finish();
|
||||||
|
assert!(resp.upgrade());
|
||||||
|
assert_eq!(
|
||||||
|
resp.headers().get(header::UPGRADE).unwrap(),
|
||||||
|
HeaderValue::from_static("websocket")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_force_close() {
|
||||||
|
let resp = Response::build(StatusCode::OK).force_close().finish();
|
||||||
|
assert!(!resp.keep_alive())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_content_type() {
|
||||||
|
let resp = Response::build(StatusCode::OK)
|
||||||
|
.content_type("text/plain")
|
||||||
|
.body(Body::Empty);
|
||||||
|
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_into_builder() {
|
||||||
|
let mut resp: Response<Body> = "test".into();
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
|
resp.headers_mut().insert(
|
||||||
|
HeaderName::from_static("cookie"),
|
||||||
|
HeaderValue::from_static("cookie1=val100"),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut builder: ResponseBuilder = resp.into();
|
||||||
|
let resp = builder.status(StatusCode::BAD_REQUEST).finish();
|
||||||
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
let cookie = resp.headers().get_all("Cookie").next().unwrap();
|
||||||
|
assert_eq!(cookie.to_str().unwrap(), "cookie1=val100");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_builder_header_insert_kv() {
|
||||||
|
let mut res = Response::build(StatusCode::OK);
|
||||||
|
res.insert_header(("Content-Type", "application/octet-stream"));
|
||||||
|
let res = res.finish();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
res.headers().get("Content-Type"),
|
||||||
|
Some(&HeaderValue::from_static("application/octet-stream"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_builder_header_insert_typed() {
|
||||||
|
let mut res = Response::build(StatusCode::OK);
|
||||||
|
res.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
|
||||||
|
let res = res.finish();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
res.headers().get("Content-Type"),
|
||||||
|
Some(&HeaderValue::from_static("application/octet-stream"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_builder_header_append_kv() {
|
||||||
|
let mut res = Response::build(StatusCode::OK);
|
||||||
|
res.append_header(("Content-Type", "application/octet-stream"));
|
||||||
|
res.append_header(("Content-Type", "application/json"));
|
||||||
|
let res = res.finish();
|
||||||
|
|
||||||
|
let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect();
|
||||||
|
assert_eq!(headers.len(), 2);
|
||||||
|
assert!(headers.contains(&HeaderValue::from_static("application/octet-stream")));
|
||||||
|
assert!(headers.contains(&HeaderValue::from_static("application/json")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_builder_header_append_typed() {
|
||||||
|
let mut res = Response::build(StatusCode::OK);
|
||||||
|
res.append_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
|
||||||
|
res.append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON));
|
||||||
|
let res = res.finish();
|
||||||
|
|
||||||
|
let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect();
|
||||||
|
assert_eq!(headers.len(), 2);
|
||||||
|
assert!(headers.contains(&HeaderValue::from_static("application/octet-stream")));
|
||||||
|
assert!(headers.contains(&HeaderValue::from_static("application/json")));
|
||||||
|
}
|
||||||
|
}
|
@ -10,7 +10,9 @@ use std::{
|
|||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_rt::net::TcpStream;
|
use actix_rt::net::TcpStream;
|
||||||
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
|
use actix_service::{
|
||||||
|
fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _,
|
||||||
|
};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures_core::{future::LocalBoxFuture, ready};
|
use futures_core::{future::LocalBoxFuture, ready};
|
||||||
use h2::server::{handshake, Handshake};
|
use h2::server::{handshake, Handshake};
|
||||||
@ -57,6 +59,7 @@ where
|
|||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
/// Create new `HttpService` instance.
|
/// Create new `HttpService` instance.
|
||||||
pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self {
|
pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self {
|
||||||
@ -155,6 +158,7 @@ where
|
|||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
@ -180,7 +184,7 @@ where
|
|||||||
Error = DispatchError,
|
Error = DispatchError,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
> {
|
> {
|
||||||
pipeline_factory(|io: TcpStream| async {
|
fn_service(|io: TcpStream| async {
|
||||||
let peer_addr = io.peer_addr().ok();
|
let peer_addr = io.peer_addr().ok();
|
||||||
Ok((io, Protocol::Http1, peer_addr))
|
Ok((io, Protocol::Http1, peer_addr))
|
||||||
})
|
})
|
||||||
@ -206,6 +210,7 @@ mod openssl {
|
|||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
@ -232,25 +237,23 @@ mod openssl {
|
|||||||
Error = TlsError<SslError, DispatchError>,
|
Error = TlsError<SslError, DispatchError>,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
> {
|
> {
|
||||||
pipeline_factory(
|
Acceptor::new(acceptor)
|
||||||
Acceptor::new(acceptor)
|
.map_err(TlsError::Tls)
|
||||||
.map_err(TlsError::Tls)
|
.map_init_err(|_| panic!())
|
||||||
.map_init_err(|_| panic!()),
|
.and_then(|io: TlsStream<TcpStream>| async {
|
||||||
)
|
let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() {
|
||||||
.and_then(|io: TlsStream<TcpStream>| async {
|
if protos.windows(2).any(|window| window == b"h2") {
|
||||||
let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() {
|
Protocol::Http2
|
||||||
if protos.windows(2).any(|window| window == b"h2") {
|
} else {
|
||||||
Protocol::Http2
|
Protocol::Http1
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Protocol::Http1
|
Protocol::Http1
|
||||||
}
|
};
|
||||||
} else {
|
let peer_addr = io.get_ref().peer_addr().ok();
|
||||||
Protocol::Http1
|
Ok((io, proto, peer_addr))
|
||||||
};
|
})
|
||||||
let peer_addr = io.get_ref().peer_addr().ok();
|
.and_then(self.map_err(TlsError::Service))
|
||||||
Ok((io, proto, peer_addr))
|
|
||||||
})
|
|
||||||
.and_then(self.map_err(TlsError::Service))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -275,6 +278,7 @@ mod rustls {
|
|||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
@ -304,25 +308,24 @@ mod rustls {
|
|||||||
let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()];
|
let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()];
|
||||||
config.set_protocols(&protos);
|
config.set_protocols(&protos);
|
||||||
|
|
||||||
pipeline_factory(
|
Acceptor::new(config)
|
||||||
Acceptor::new(config)
|
.map_err(TlsError::Tls)
|
||||||
.map_err(TlsError::Tls)
|
.map_init_err(|_| panic!())
|
||||||
.map_init_err(|_| panic!()),
|
.and_then(|io: TlsStream<TcpStream>| async {
|
||||||
)
|
let proto = if let Some(protos) = io.get_ref().1.get_alpn_protocol()
|
||||||
.and_then(|io: TlsStream<TcpStream>| async {
|
{
|
||||||
let proto = if let Some(protos) = io.get_ref().1.get_alpn_protocol() {
|
if protos.windows(2).any(|window| window == b"h2") {
|
||||||
if protos.windows(2).any(|window| window == b"h2") {
|
Protocol::Http2
|
||||||
Protocol::Http2
|
} else {
|
||||||
|
Protocol::Http1
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Protocol::Http1
|
Protocol::Http1
|
||||||
}
|
};
|
||||||
} else {
|
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||||
Protocol::Http1
|
Ok((io, proto, peer_addr))
|
||||||
};
|
})
|
||||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
.and_then(self.map_err(TlsError::Service))
|
||||||
Ok((io, proto, peer_addr))
|
|
||||||
})
|
|
||||||
.and_then(self.map_err(TlsError::Service))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -340,6 +343,7 @@ where
|
|||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||||
X::Future: 'static,
|
X::Future: 'static,
|
||||||
@ -466,13 +470,18 @@ impl<T, S, B, X, U> Service<(T, Protocol, Option<net::SocketAddr>)>
|
|||||||
for HttpServiceHandler<T, S, B, X, U>
|
for HttpServiceHandler<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display + Into<Error>,
|
U::Error: fmt::Display + Into<Error>,
|
||||||
{
|
{
|
||||||
@ -523,13 +532,18 @@ where
|
|||||||
#[pin_project(project = StateProj)]
|
#[pin_project(project = StateProj)]
|
||||||
enum State<T, S, B, X, U>
|
enum State<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: Into<Error>,
|
S::Error: Into<Error>,
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
|
||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -550,13 +564,18 @@ where
|
|||||||
pub struct HttpServiceHandlerResponse<T, S, B, X, U>
|
pub struct HttpServiceHandlerResponse<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody + 'static,
|
|
||||||
|
B: MessageBody,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
@ -567,13 +586,18 @@ where
|
|||||||
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
|
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin,
|
T: AsyncRead + AsyncWrite + Unpin,
|
||||||
|
|
||||||
S: Service<Request>,
|
S: Service<Request>,
|
||||||
S::Error: Into<Error> + 'static,
|
S::Error: Into<Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Response: Into<Response<B>> + 'static,
|
S::Response: Into<Response<B>> + 'static,
|
||||||
B: MessageBody,
|
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
|
|
||||||
X: Service<Request, Response = Request>,
|
X: Service<Request, Response = Request>,
|
||||||
X::Error: Into<Error>,
|
X::Error: Into<Error>,
|
||||||
|
|
||||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
|
@ -13,11 +13,6 @@ use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
|||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use http::{Method, Uri, Version};
|
use http::{Method, Uri, Version};
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
use crate::{
|
|
||||||
cookie::{Cookie, CookieJar},
|
|
||||||
header::{self, HeaderValue},
|
|
||||||
};
|
|
||||||
use crate::{
|
use crate::{
|
||||||
header::{HeaderMap, IntoHeaderPair},
|
header::{HeaderMap, IntoHeaderPair},
|
||||||
payload::Payload,
|
payload::Payload,
|
||||||
@ -54,8 +49,6 @@ struct Inner {
|
|||||||
method: Method,
|
method: Method,
|
||||||
uri: Uri,
|
uri: Uri,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
cookies: CookieJar,
|
|
||||||
payload: Option<Payload>,
|
payload: Option<Payload>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,8 +59,6 @@ impl Default for TestRequest {
|
|||||||
uri: Uri::from_str("/").unwrap(),
|
uri: Uri::from_str("/").unwrap(),
|
||||||
version: Version::HTTP_11,
|
version: Version::HTTP_11,
|
||||||
headers: HeaderMap::new(),
|
headers: HeaderMap::new(),
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
cookies: CookieJar::new(),
|
|
||||||
payload: None,
|
payload: None,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@ -134,13 +125,6 @@ impl TestRequest {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set cookie for this request.
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
pub fn cookie<'a>(&mut self, cookie: Cookie<'a>) -> &mut Self {
|
|
||||||
parts(&mut self.0).cookies.add(cookie.into_owned());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set request payload.
|
/// Set request payload.
|
||||||
pub fn set_payload<B: Into<Bytes>>(&mut self, data: B) -> &mut Self {
|
pub fn set_payload<B: Into<Bytes>>(&mut self, data: B) -> &mut Self {
|
||||||
let mut payload = crate::h1::Payload::empty();
|
let mut payload = crate::h1::Payload::empty();
|
||||||
@ -169,22 +153,6 @@ impl TestRequest {
|
|||||||
head.version = inner.version;
|
head.version = inner.version;
|
||||||
head.headers = inner.headers;
|
head.headers = inner.headers;
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
{
|
|
||||||
let cookie: String = inner
|
|
||||||
.cookies
|
|
||||||
.delta()
|
|
||||||
// ensure only name=value is written to cookie header
|
|
||||||
.map(|c| Cookie::new(c.name(), c.value()).encoded().to_string())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("; ");
|
|
||||||
|
|
||||||
if !cookie.is_empty() {
|
|
||||||
head.headers
|
|
||||||
.insert(header::COOKIE, HeaderValue::from_str(&cookie).unwrap());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
req
|
req
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,10 +9,8 @@ use derive_more::{Display, Error, From};
|
|||||||
use http::{header, Method, StatusCode};
|
use http::{header, Method, StatusCode};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
error::ResponseError,
|
body::Body, error::ResponseError, header::HeaderValue, message::RequestHead,
|
||||||
header::HeaderValue,
|
response::Response, ResponseBuilder,
|
||||||
message::RequestHead,
|
|
||||||
response::{Response, ResponseBuilder},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
mod codec;
|
mod codec;
|
||||||
@ -101,31 +99,39 @@ pub enum HandshakeError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ResponseError for HandshakeError {
|
impl ResponseError for HandshakeError {
|
||||||
fn error_response(&self) -> Response {
|
fn error_response(&self) -> Response<Body> {
|
||||||
match self {
|
match self {
|
||||||
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
|
HandshakeError::GetMethodRequired => {
|
||||||
.insert_header((header::ALLOW, "GET"))
|
Response::build(StatusCode::METHOD_NOT_ALLOWED)
|
||||||
.finish(),
|
.insert_header((header::ALLOW, "GET"))
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
|
||||||
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
|
HandshakeError::NoWebsocketUpgrade => {
|
||||||
.reason("No WebSocket Upgrade header found")
|
Response::build(StatusCode::BAD_REQUEST)
|
||||||
.finish(),
|
.reason("No WebSocket Upgrade header found")
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
|
||||||
HandshakeError::NoConnectionUpgrade => Response::BadRequest()
|
HandshakeError::NoConnectionUpgrade => {
|
||||||
.reason("No Connection upgrade")
|
Response::build(StatusCode::BAD_REQUEST)
|
||||||
.finish(),
|
.reason("No Connection upgrade")
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
|
||||||
HandshakeError::NoVersionHeader => Response::BadRequest()
|
HandshakeError::NoVersionHeader => Response::build(StatusCode::BAD_REQUEST)
|
||||||
.reason("WebSocket version header is required")
|
.reason("WebSocket version header is required")
|
||||||
.finish(),
|
.finish(),
|
||||||
|
|
||||||
HandshakeError::UnsupportedVersion => Response::BadRequest()
|
HandshakeError::UnsupportedVersion => {
|
||||||
.reason("Unsupported WebSocket version")
|
Response::build(StatusCode::BAD_REQUEST)
|
||||||
.finish(),
|
.reason("Unsupported WebSocket version")
|
||||||
|
.finish()
|
||||||
HandshakeError::BadWebsocketKey => {
|
|
||||||
Response::BadRequest().reason("Handshake error").finish()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
HandshakeError::BadWebsocketKey => Response::build(StatusCode::BAD_REQUEST)
|
||||||
|
.reason("Handshake error")
|
||||||
|
.finish(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -322,17 +328,17 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_wserror_http_response() {
|
fn test_wserror_http_response() {
|
||||||
let resp: Response = HandshakeError::GetMethodRequired.error_response();
|
let resp = HandshakeError::GetMethodRequired.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||||
let resp: Response = HandshakeError::NoWebsocketUpgrade.error_response();
|
let resp = HandshakeError::NoWebsocketUpgrade.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
let resp: Response = HandshakeError::NoConnectionUpgrade.error_response();
|
let resp = HandshakeError::NoConnectionUpgrade.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
let resp: Response = HandshakeError::NoVersionHeader.error_response();
|
let resp = HandshakeError::NoVersionHeader.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
let resp: Response = HandshakeError::UnsupportedVersion.error_response();
|
let resp = HandshakeError::UnsupportedVersion.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
let resp: Response = HandshakeError::BadWebsocketKey.error_response();
|
let resp = HandshakeError::BadWebsocketKey.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,11 @@
|
|||||||
use actix_http::{
|
use actix_http::{
|
||||||
error, http, http::StatusCode, HttpMessage, HttpService, Request, Response,
|
http, http::StatusCode, HttpMessage, HttpService, Request, Response, ResponseError,
|
||||||
};
|
};
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::ServiceFactoryExt;
|
use actix_service::ServiceFactoryExt;
|
||||||
use actix_utils::future;
|
use actix_utils::future;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
use derive_more::{Display, Error};
|
||||||
use futures_util::StreamExt as _;
|
use futures_util::StreamExt as _;
|
||||||
|
|
||||||
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 \
|
||||||
@ -33,7 +34,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
|||||||
async fn test_h1_v2() {
|
async fn test_h1_v2() {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
.finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -61,7 +62,7 @@ async fn test_h1_v2() {
|
|||||||
async fn test_connection_close() {
|
async fn test_connection_close() {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
.finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.tcp()
|
.tcp()
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
})
|
})
|
||||||
@ -77,9 +78,9 @@ async fn test_with_query_parameter() {
|
|||||||
HttpService::build()
|
HttpService::build()
|
||||||
.finish(|req: Request| {
|
.finish(|req: Request| {
|
||||||
if req.uri().query().unwrap().contains("qp=") {
|
if req.uri().query().unwrap().contains("qp=") {
|
||||||
future::ok::<_, ()>(Response::Ok().finish())
|
future::ok::<_, ()>(Response::ok())
|
||||||
} else {
|
} else {
|
||||||
future::ok::<_, ()>(Response::BadRequest().finish())
|
future::ok::<_, ()>(Response::bad_request())
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.tcp()
|
.tcp()
|
||||||
@ -92,6 +93,16 @@ async fn test_with_query_parameter() {
|
|||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display(fmt = "expect failed")]
|
||||||
|
struct ExpectFailed;
|
||||||
|
|
||||||
|
impl ResponseError for ExpectFailed {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
StatusCode::EXPECTATION_FAILED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_h1_expect() {
|
async fn test_h1_expect() {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
@ -100,7 +111,7 @@ async fn test_h1_expect() {
|
|||||||
if req.headers().contains_key("AUTH") {
|
if req.headers().contains_key("AUTH") {
|
||||||
Ok(req)
|
Ok(req)
|
||||||
} else {
|
} else {
|
||||||
Err(error::ErrorExpectationFailed("expect failed"))
|
Err(ExpectFailed)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.h1(|req: Request| async move {
|
.h1(|req: Request| async move {
|
||||||
@ -112,7 +123,7 @@ async fn test_h1_expect() {
|
|||||||
let str = std::str::from_utf8(&buf).unwrap();
|
let str = std::str::from_utf8(&buf).unwrap();
|
||||||
assert_eq!(str, "expect body");
|
assert_eq!(str, "expect body");
|
||||||
|
|
||||||
Ok::<_, ()>(Response::Ok().finish())
|
Ok::<_, ()>(Response::ok())
|
||||||
})
|
})
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
@ -134,7 +145,7 @@ async fn test_h1_expect() {
|
|||||||
let response = request.send_body("expect body").await.unwrap();
|
let response = request.send_body("expect body").await.unwrap();
|
||||||
assert_eq!(response.status(), StatusCode::EXPECTATION_FAILED);
|
assert_eq!(response.status(), StatusCode::EXPECTATION_FAILED);
|
||||||
|
|
||||||
// test exepct would continue
|
// test expect would continue
|
||||||
let request = srv
|
let request = srv
|
||||||
.request(http::Method::GET, srv.url("/"))
|
.request(http::Method::GET, srv.url("/"))
|
||||||
.insert_header(("Expect", "100-continue"))
|
.insert_header(("Expect", "100-continue"))
|
||||||
|
@ -4,15 +4,20 @@ extern crate tls_openssl as openssl;
|
|||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
use actix_http::error::{ErrorBadRequest, PayloadError};
|
use actix_http::{
|
||||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
body::{Body, SizedStream},
|
||||||
use actix_http::http::{Method, StatusCode, Version};
|
error::PayloadError,
|
||||||
use actix_http::HttpMessage;
|
http::{
|
||||||
use actix_http::{body, Error, HttpService, Request, Response};
|
header::{self, HeaderName, HeaderValue},
|
||||||
|
Method, StatusCode, Version,
|
||||||
|
},
|
||||||
|
Error, HttpMessage, HttpService, Request, Response, ResponseError,
|
||||||
|
};
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::{fn_service, ServiceFactoryExt};
|
use actix_service::{fn_service, ServiceFactoryExt};
|
||||||
use actix_utils::future::{err, ok, ready};
|
use actix_utils::future::{err, ok, ready};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use derive_more::{Display, Error};
|
||||||
use futures_core::Stream;
|
use futures_core::Stream;
|
||||||
use futures_util::stream::{once, StreamExt as _};
|
use futures_util::stream::{once, StreamExt as _};
|
||||||
use openssl::{
|
use openssl::{
|
||||||
@ -67,7 +72,7 @@ fn tls_config() -> SslAcceptor {
|
|||||||
async fn test_h2() -> io::Result<()> {
|
async fn test_h2() -> io::Result<()> {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, Error>(Response::Ok().finish()))
|
.h2(|_| ok::<_, Error>(Response::ok()))
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
})
|
})
|
||||||
@ -85,7 +90,7 @@ async fn test_h2_1() -> io::Result<()> {
|
|||||||
.finish(|req: Request| {
|
.finish(|req: Request| {
|
||||||
assert!(req.peer_addr().is_some());
|
assert!(req.peer_addr().is_some());
|
||||||
assert_eq!(req.version(), Version::HTTP_2);
|
assert_eq!(req.version(), Version::HTTP_2);
|
||||||
ok::<_, Error>(Response::Ok().finish())
|
ok::<_, Error>(Response::ok())
|
||||||
})
|
})
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
@ -104,7 +109,7 @@ async fn test_h2_body() -> io::Result<()> {
|
|||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|mut req: Request<_>| async move {
|
.h2(|mut req: Request<_>| async move {
|
||||||
let body = load_body(req.take_payload()).await?;
|
let body = load_body(req.take_payload()).await?;
|
||||||
Ok::<_, Error>(Response::Ok().body(body))
|
Ok::<_, Error>(Response::ok().set_body(body))
|
||||||
})
|
})
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
@ -182,7 +187,7 @@ async fn test_h2_headers() {
|
|||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
let data = data.clone();
|
let data = data.clone();
|
||||||
HttpService::build().h2(move |_| {
|
HttpService::build().h2(move |_| {
|
||||||
let mut builder = Response::Ok();
|
let mut builder = Response::build(StatusCode::OK);
|
||||||
for idx in 0..90 {
|
for idx in 0..90 {
|
||||||
builder.insert_header(
|
builder.insert_header(
|
||||||
(format!("X-TEST-{}", idx).as_str(),
|
(format!("X-TEST-{}", idx).as_str(),
|
||||||
@ -241,7 +246,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
|||||||
async fn test_h2_body2() {
|
async fn test_h2_body2() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
})
|
})
|
||||||
@ -259,7 +264,7 @@ async fn test_h2_body2() {
|
|||||||
async fn test_h2_head_empty() {
|
async fn test_h2_head_empty() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
})
|
})
|
||||||
@ -283,7 +288,7 @@ async fn test_h2_head_empty() {
|
|||||||
async fn test_h2_head_binary() {
|
async fn test_h2_head_binary() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
})
|
})
|
||||||
@ -306,7 +311,7 @@ async fn test_h2_head_binary() {
|
|||||||
async fn test_h2_head_binary2() {
|
async fn test_h2_head_binary2() {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
})
|
})
|
||||||
@ -328,7 +333,7 @@ async fn test_h2_body_length() {
|
|||||||
.h2(|_| {
|
.h2(|_| {
|
||||||
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
@ -351,7 +356,7 @@ async fn test_h2_body_chunked_explicit() {
|
|||||||
.h2(|_| {
|
.h2(|_| {
|
||||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::build(StatusCode::OK)
|
||||||
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||||
.streaming(body),
|
.streaming(body),
|
||||||
)
|
)
|
||||||
@ -379,7 +384,7 @@ async fn test_h2_response_http_error_handling() {
|
|||||||
.h2(fn_service(|_| {
|
.h2(fn_service(|_| {
|
||||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::build(StatusCode::OK)
|
||||||
.insert_header((header::CONTENT_TYPE, broken_header))
|
.insert_header((header::CONTENT_TYPE, broken_header))
|
||||||
.body(STR),
|
.body(STR),
|
||||||
)
|
)
|
||||||
@ -397,11 +402,21 @@ async fn test_h2_response_http_error_handling() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display(fmt = "error")]
|
||||||
|
struct BadRequest;
|
||||||
|
|
||||||
|
impl ResponseError for BadRequest {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_h2_service_error() {
|
async fn test_h2_service_error() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| err::<Response, Error>(ErrorBadRequest("error")))
|
.h2(|_| err::<Response<Body>, _>(BadRequest))
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
})
|
})
|
||||||
@ -424,7 +439,7 @@ async fn test_h2_on_connect() {
|
|||||||
})
|
})
|
||||||
.h2(|req: Request| {
|
.h2(|req: Request| {
|
||||||
assert!(req.extensions().contains::<isize>());
|
assert!(req.extensions().contains::<isize>());
|
||||||
ok::<_, ()>(Response::Ok().finish())
|
ok::<_, ()>(Response::ok())
|
||||||
})
|
})
|
||||||
.openssl(tls_config())
|
.openssl(tls_config())
|
||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
|
@ -2,15 +2,20 @@
|
|||||||
|
|
||||||
extern crate tls_rustls as rustls;
|
extern crate tls_rustls as rustls;
|
||||||
|
|
||||||
use actix_http::error::PayloadError;
|
use actix_http::{
|
||||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
body::{Body, SizedStream},
|
||||||
use actix_http::http::{Method, StatusCode, Version};
|
error::PayloadError,
|
||||||
use actix_http::{body, error, Error, HttpService, Request, Response};
|
http::{
|
||||||
|
header::{self, HeaderName, HeaderValue},
|
||||||
|
Method, StatusCode, Version,
|
||||||
|
},
|
||||||
|
Error, HttpService, Request, Response, ResponseError,
|
||||||
|
};
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::{fn_factory_with_config, fn_service};
|
use actix_service::{fn_factory_with_config, fn_service};
|
||||||
use actix_utils::future::{err, ok};
|
use actix_utils::future::{err, ok};
|
||||||
|
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use derive_more::{Display, Error};
|
||||||
use futures_core::Stream;
|
use futures_core::Stream;
|
||||||
use futures_util::stream::{once, StreamExt as _};
|
use futures_util::stream::{once, StreamExt as _};
|
||||||
use rustls::{
|
use rustls::{
|
||||||
@ -51,7 +56,7 @@ fn tls_config() -> RustlsServerConfig {
|
|||||||
async fn test_h1() -> io::Result<()> {
|
async fn test_h1() -> io::Result<()> {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, Error>(Response::Ok().finish()))
|
.h1(|_| ok::<_, Error>(Response::ok()))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -65,7 +70,7 @@ async fn test_h1() -> io::Result<()> {
|
|||||||
async fn test_h2() -> io::Result<()> {
|
async fn test_h2() -> io::Result<()> {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, Error>(Response::Ok().finish()))
|
.h2(|_| ok::<_, Error>(Response::ok()))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -82,7 +87,7 @@ async fn test_h1_1() -> io::Result<()> {
|
|||||||
.h1(|req: Request| {
|
.h1(|req: Request| {
|
||||||
assert!(req.peer_addr().is_some());
|
assert!(req.peer_addr().is_some());
|
||||||
assert_eq!(req.version(), Version::HTTP_11);
|
assert_eq!(req.version(), Version::HTTP_11);
|
||||||
ok::<_, Error>(Response::Ok().finish())
|
ok::<_, Error>(Response::ok())
|
||||||
})
|
})
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
@ -100,7 +105,7 @@ async fn test_h2_1() -> io::Result<()> {
|
|||||||
.finish(|req: Request| {
|
.finish(|req: Request| {
|
||||||
assert!(req.peer_addr().is_some());
|
assert!(req.peer_addr().is_some());
|
||||||
assert_eq!(req.version(), Version::HTTP_2);
|
assert_eq!(req.version(), Version::HTTP_2);
|
||||||
ok::<_, Error>(Response::Ok().finish())
|
ok::<_, Error>(Response::ok())
|
||||||
})
|
})
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
@ -118,7 +123,7 @@ async fn test_h2_body1() -> io::Result<()> {
|
|||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|mut req: Request<_>| async move {
|
.h2(|mut req: Request<_>| async move {
|
||||||
let body = load_body(req.take_payload()).await?;
|
let body = load_body(req.take_payload()).await?;
|
||||||
Ok::<_, Error>(Response::Ok().body(body))
|
Ok::<_, Error>(Response::ok().set_body(body))
|
||||||
})
|
})
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
@ -194,7 +199,7 @@ async fn test_h2_headers() {
|
|||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
let data = data.clone();
|
let data = data.clone();
|
||||||
HttpService::build().h2(move |_| {
|
HttpService::build().h2(move |_| {
|
||||||
let mut config = Response::Ok();
|
let mut config = Response::build(StatusCode::OK);
|
||||||
for idx in 0..90 {
|
for idx in 0..90 {
|
||||||
config.insert_header((
|
config.insert_header((
|
||||||
format!("X-TEST-{}", idx).as_str(),
|
format!("X-TEST-{}", idx).as_str(),
|
||||||
@ -252,7 +257,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
|||||||
async fn test_h2_body2() {
|
async fn test_h2_body2() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -269,7 +274,7 @@ async fn test_h2_body2() {
|
|||||||
async fn test_h2_head_empty() {
|
async fn test_h2_head_empty() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -295,7 +300,7 @@ async fn test_h2_head_empty() {
|
|||||||
async fn test_h2_head_binary() {
|
async fn test_h2_head_binary() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -320,7 +325,7 @@ async fn test_h2_head_binary() {
|
|||||||
async fn test_h2_head_binary2() {
|
async fn test_h2_head_binary2() {
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -344,7 +349,7 @@ async fn test_h2_body_length() {
|
|||||||
.h2(|_| {
|
.h2(|_| {
|
||||||
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
@ -366,7 +371,7 @@ async fn test_h2_body_chunked_explicit() {
|
|||||||
.h2(|_| {
|
.h2(|_| {
|
||||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::build(StatusCode::OK)
|
||||||
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||||
.streaming(body),
|
.streaming(body),
|
||||||
)
|
)
|
||||||
@ -394,7 +399,7 @@ async fn test_h2_response_http_error_handling() {
|
|||||||
ok::<_, ()>(fn_service(|_| {
|
ok::<_, ()>(fn_service(|_| {
|
||||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::build(StatusCode::OK)
|
||||||
.insert_header((http::header::CONTENT_TYPE, broken_header))
|
.insert_header((http::header::CONTENT_TYPE, broken_header))
|
||||||
.body(STR),
|
.body(STR),
|
||||||
)
|
)
|
||||||
@ -412,11 +417,21 @@ async fn test_h2_response_http_error_handling() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display(fmt = "error")]
|
||||||
|
struct BadRequest;
|
||||||
|
|
||||||
|
impl ResponseError for BadRequest {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_h2_service_error() {
|
async fn test_h2_service_error() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| err::<Response, Error>(error::ErrorBadRequest("error")))
|
.h2(|_| err::<Response<Body>, _>(BadRequest))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -433,7 +448,7 @@ async fn test_h2_service_error() {
|
|||||||
async fn test_h1_service_error() {
|
async fn test_h1_service_error() {
|
||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| err::<Response, Error>(error::ErrorBadRequest("error")))
|
.h1(|_| err::<Response<Body>, _>(BadRequest))
|
||||||
.rustls(tls_config())
|
.rustls(tls_config())
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
@ -2,20 +2,22 @@ use std::io::{Read, Write};
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::{net, thread};
|
use std::{net, thread};
|
||||||
|
|
||||||
|
use actix_http::{
|
||||||
|
body::{Body, SizedStream},
|
||||||
|
http::{self, header, StatusCode},
|
||||||
|
Error, HttpService, KeepAlive, Request, Response,
|
||||||
|
};
|
||||||
|
use actix_http::{HttpMessage, ResponseError};
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_rt::time::sleep;
|
use actix_rt::time::sleep;
|
||||||
use actix_service::fn_service;
|
use actix_service::fn_service;
|
||||||
use actix_utils::future::{err, ok, ready};
|
use actix_utils::future::{err, ok, ready};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
use derive_more::{Display, Error};
|
||||||
use futures_util::stream::{once, StreamExt as _};
|
use futures_util::stream::{once, StreamExt as _};
|
||||||
use futures_util::FutureExt as _;
|
use futures_util::FutureExt as _;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
|
||||||
use actix_http::HttpMessage;
|
|
||||||
use actix_http::{
|
|
||||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_h1() {
|
async fn test_h1() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
@ -25,7 +27,7 @@ async fn test_h1() {
|
|||||||
.client_disconnect(1000)
|
.client_disconnect(1000)
|
||||||
.h1(|req: Request| {
|
.h1(|req: Request| {
|
||||||
assert!(req.peer_addr().is_some());
|
assert!(req.peer_addr().is_some());
|
||||||
ok::<_, ()>(Response::Ok().finish())
|
ok::<_, ()>(Response::ok())
|
||||||
})
|
})
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
@ -45,7 +47,7 @@ async fn test_h1_2() {
|
|||||||
.finish(|req: Request| {
|
.finish(|req: Request| {
|
||||||
assert!(req.peer_addr().is_some());
|
assert!(req.peer_addr().is_some());
|
||||||
assert_eq!(req.version(), http::Version::HTTP_11);
|
assert_eq!(req.version(), http::Version::HTTP_11);
|
||||||
ok::<_, ()>(Response::Ok().finish())
|
ok::<_, ()>(Response::ok())
|
||||||
})
|
})
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
@ -55,6 +57,16 @@ async fn test_h1_2() {
|
|||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display(fmt = "expect failed")]
|
||||||
|
struct ExpectFailed;
|
||||||
|
|
||||||
|
impl ResponseError for ExpectFailed {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
StatusCode::PRECONDITION_FAILED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_expect_continue() {
|
async fn test_expect_continue() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
@ -63,10 +75,10 @@ async fn test_expect_continue() {
|
|||||||
if req.head().uri.query() == Some("yes=") {
|
if req.head().uri.query() == Some("yes=") {
|
||||||
ok(req)
|
ok(req)
|
||||||
} else {
|
} else {
|
||||||
err(error::ErrorPreconditionFailed("error"))
|
err(ExpectFailed)
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
.finish(|_| ok::<_, ()>(Response::Ok().finish()))
|
.finish(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -93,11 +105,11 @@ async fn test_expect_continue_h1() {
|
|||||||
if req.head().uri.query() == Some("yes=") {
|
if req.head().uri.query() == Some("yes=") {
|
||||||
ok(req)
|
ok(req)
|
||||||
} else {
|
} else {
|
||||||
err(error::ErrorPreconditionFailed("error"))
|
err(ExpectFailed)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}))
|
}))
|
||||||
.h1(fn_service(|_| ok::<_, ()>(Response::Ok().finish())))
|
.h1(fn_service(|_| ok::<_, ()>(Response::ok())))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -131,7 +143,9 @@ async fn test_chunked_payload() {
|
|||||||
})
|
})
|
||||||
.fold(0usize, |acc, chunk| ready(acc + chunk.len()))
|
.fold(0usize, |acc, chunk| ready(acc + chunk.len()))
|
||||||
.map(|req_size| {
|
.map(|req_size| {
|
||||||
Ok::<_, Error>(Response::Ok().body(format!("size={}", req_size)))
|
Ok::<_, Error>(
|
||||||
|
Response::ok().set_body(format!("size={}", req_size)),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
}))
|
}))
|
||||||
.tcp()
|
.tcp()
|
||||||
@ -176,7 +190,7 @@ async fn test_slow_request() {
|
|||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.client_timeout(100)
|
.client_timeout(100)
|
||||||
.finish(|_| ok::<_, ()>(Response::Ok().finish()))
|
.finish(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -192,7 +206,7 @@ async fn test_slow_request() {
|
|||||||
async fn test_http1_malformed_request() {
|
async fn test_http1_malformed_request() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -208,7 +222,7 @@ async fn test_http1_malformed_request() {
|
|||||||
async fn test_http1_keepalive() {
|
async fn test_http1_keepalive() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -230,7 +244,7 @@ async fn test_http1_keepalive_timeout() {
|
|||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.keep_alive(1)
|
.keep_alive(1)
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -251,7 +265,7 @@ async fn test_http1_keepalive_timeout() {
|
|||||||
async fn test_http1_keepalive_close() {
|
async fn test_http1_keepalive_close() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -272,7 +286,7 @@ async fn test_http1_keepalive_close() {
|
|||||||
async fn test_http10_keepalive_default_close() {
|
async fn test_http10_keepalive_default_close() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -292,7 +306,7 @@ async fn test_http10_keepalive_default_close() {
|
|||||||
async fn test_http10_keepalive() {
|
async fn test_http10_keepalive() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -320,7 +334,7 @@ async fn test_http1_keepalive_disabled() {
|
|||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.keep_alive(KeepAlive::Disabled)
|
.keep_alive(KeepAlive::Disabled)
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -391,7 +405,7 @@ async fn test_h1_headers() {
|
|||||||
let mut srv = test_server(move || {
|
let mut srv = test_server(move || {
|
||||||
let data = data.clone();
|
let data = data.clone();
|
||||||
HttpService::build().h1(move |_| {
|
HttpService::build().h1(move |_| {
|
||||||
let mut builder = Response::Ok();
|
let mut builder = Response::build(StatusCode::OK);
|
||||||
for idx in 0..90 {
|
for idx in 0..90 {
|
||||||
builder.insert_header((
|
builder.insert_header((
|
||||||
format!("X-TEST-{}", idx).as_str(),
|
format!("X-TEST-{}", idx).as_str(),
|
||||||
@ -448,7 +462,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
|||||||
async fn test_h1_body() {
|
async fn test_h1_body() {
|
||||||
let mut srv = test_server(|| {
|
let mut srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -465,7 +479,7 @@ async fn test_h1_body() {
|
|||||||
async fn test_h1_head_empty() {
|
async fn test_h1_head_empty() {
|
||||||
let mut srv = test_server(|| {
|
let mut srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -490,7 +504,7 @@ async fn test_h1_head_empty() {
|
|||||||
async fn test_h1_head_binary() {
|
async fn test_h1_head_binary() {
|
||||||
let mut srv = test_server(|| {
|
let mut srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -515,7 +529,7 @@ async fn test_h1_head_binary() {
|
|||||||
async fn test_h1_head_binary2() {
|
async fn test_h1_head_binary2() {
|
||||||
let srv = test_server(|| {
|
let srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -539,7 +553,7 @@ async fn test_h1_body_length() {
|
|||||||
.h1(|_| {
|
.h1(|_| {
|
||||||
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.tcp()
|
.tcp()
|
||||||
@ -561,7 +575,7 @@ async fn test_h1_body_chunked_explicit() {
|
|||||||
.h1(|_| {
|
.h1(|_| {
|
||||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::build(StatusCode::OK)
|
||||||
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||||
.streaming(body),
|
.streaming(body),
|
||||||
)
|
)
|
||||||
@ -595,7 +609,7 @@ async fn test_h1_body_chunked_implicit() {
|
|||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| {
|
.h1(|_| {
|
||||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(Response::Ok().streaming(body))
|
ok::<_, ()>(Response::build(StatusCode::OK).streaming(body))
|
||||||
})
|
})
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
@ -625,7 +639,7 @@ async fn test_h1_response_http_error_handling() {
|
|||||||
.h1(fn_service(|_| {
|
.h1(fn_service(|_| {
|
||||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::build(StatusCode::OK)
|
||||||
.insert_header((http::header::CONTENT_TYPE, broken_header))
|
.insert_header((http::header::CONTENT_TYPE, broken_header))
|
||||||
.body(STR),
|
.body(STR),
|
||||||
)
|
)
|
||||||
@ -642,11 +656,21 @@ async fn test_h1_response_http_error_handling() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display(fmt = "error")]
|
||||||
|
struct BadRequest;
|
||||||
|
|
||||||
|
impl ResponseError for BadRequest {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_h1_service_error() {
|
async fn test_h1_service_error() {
|
||||||
let mut srv = test_server(|| {
|
let mut srv = test_server(|| {
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h1(|_| err::<Response, _>(error::ErrorBadRequest("error")))
|
.h1(|_| err::<Response<Body>, _>(BadRequest))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@ -668,7 +692,7 @@ async fn test_h1_on_connect() {
|
|||||||
})
|
})
|
||||||
.h1(|req: Request| {
|
.h1(|req: Request| {
|
||||||
assert!(req.extensions().contains::<isize>());
|
assert!(req.extensions().contains::<isize>());
|
||||||
ok::<_, ()>(Response::Ok().finish())
|
ok::<_, ()>(Response::ok())
|
||||||
})
|
})
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
|
@ -1,193 +1,163 @@
|
|||||||
use std::cell::Cell;
|
use std::{
|
||||||
use std::future::Future;
|
cell::Cell,
|
||||||
use std::marker::PhantomData;
|
task::{Context, Poll},
|
||||||
use std::pin::Pin;
|
};
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
use std::task::{Context, Poll};
|
|
||||||
|
|
||||||
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::BodySize,
|
||||||
|
h1,
|
||||||
|
ws::{self, CloseCode, Frame, Item, Message},
|
||||||
|
Error, HttpService, Request, Response,
|
||||||
|
};
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::{fn_factory, Service};
|
use actix_service::{fn_factory, Service};
|
||||||
use actix_utils::future;
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
use futures_core::future::LocalBoxFuture;
|
||||||
use futures_util::{SinkExt as _, StreamExt as _};
|
use futures_util::{SinkExt as _, StreamExt as _};
|
||||||
|
|
||||||
use crate::ws::Dispatcher;
|
#[derive(Clone)]
|
||||||
|
struct WsService(Cell<bool>);
|
||||||
|
|
||||||
struct WsService<T>(Arc<Mutex<(PhantomData<T>, Cell<bool>)>>);
|
impl WsService {
|
||||||
|
|
||||||
impl<T> WsService<T> {
|
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
WsService(Arc::new(Mutex::new((PhantomData, Cell::new(false)))))
|
WsService(Cell::new(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_polled(&self) {
|
fn set_polled(&self) {
|
||||||
*self.0.lock().unwrap().1.get_mut() = true;
|
self.0.set(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn was_polled(&self) -> bool {
|
fn was_polled(&self) -> bool {
|
||||||
self.0.lock().unwrap().1.get()
|
self.0.get()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Clone for WsService<T> {
|
impl<T> Service<(Request, Framed<T, h1::Codec>)> for WsService
|
||||||
fn clone(&self) -> Self {
|
|
||||||
WsService(self.0.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Service<(Request, Framed<T, h1::Codec>)> for WsService<T>
|
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||||
{
|
{
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Pin<Box<dyn Future<Output = Result<(), Error>>>>;
|
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||||
|
|
||||||
fn poll_ready(&self, _ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
self.set_polled();
|
self.set_polled();
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&self, (req, mut framed): (Request, Framed<T, h1::Codec>)) -> Self::Future {
|
fn call(&self, (req, mut framed): (Request, Framed<T, h1::Codec>)) -> Self::Future {
|
||||||
let fut = async move {
|
assert!(self.was_polled());
|
||||||
let res = ws::handshake(req.head()).unwrap().message_body(());
|
|
||||||
|
|
||||||
framed
|
Box::pin(async move {
|
||||||
.send((res, body::BodySize::None).into())
|
let res = ws::handshake(req.head())?.message_body(())?;
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
Dispatcher::with(framed.replace_codec(ws::Codec::new()), service)
|
framed.send((res, BodySize::None).into()).await?;
|
||||||
.await
|
|
||||||
.map_err(|_| panic!())
|
|
||||||
};
|
|
||||||
|
|
||||||
Box::pin(fut)
|
let framed = framed.replace_codec(ws::Codec::new());
|
||||||
|
|
||||||
|
ws::Dispatcher::with(framed, service).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
|
async fn service(msg: Frame) -> Result<Message, Error> {
|
||||||
let msg = match msg {
|
let msg = match msg {
|
||||||
ws::Frame::Ping(msg) => ws::Message::Pong(msg),
|
Frame::Ping(msg) => Message::Pong(msg),
|
||||||
ws::Frame::Text(text) => {
|
Frame::Text(text) => {
|
||||||
ws::Message::Text(String::from_utf8_lossy(&text).into_owned().into())
|
Message::Text(String::from_utf8_lossy(&text).into_owned().into())
|
||||||
}
|
}
|
||||||
ws::Frame::Binary(bin) => ws::Message::Binary(bin),
|
Frame::Binary(bin) => Message::Binary(bin),
|
||||||
ws::Frame::Continuation(item) => ws::Message::Continuation(item),
|
Frame::Continuation(item) => Message::Continuation(item),
|
||||||
ws::Frame::Close(reason) => ws::Message::Close(reason),
|
Frame::Close(reason) => Message::Close(reason),
|
||||||
_ => panic!(),
|
_ => return Err(Error::from(ws::ProtocolError::BadOpCode)),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(msg)
|
Ok(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_simple() {
|
async fn test_simple() {
|
||||||
let ws_service = WsService::new();
|
let mut srv = test_server(|| {
|
||||||
let mut srv = test_server({
|
HttpService::build()
|
||||||
let ws_service = ws_service.clone();
|
.upgrade(fn_factory(|| async { Ok::<_, ()>(WsService::new()) }))
|
||||||
move || {
|
.finish(|_| async { Ok::<_, ()>(Response::not_found()) })
|
||||||
let ws_service = ws_service.clone();
|
.tcp()
|
||||||
HttpService::build()
|
|
||||||
.upgrade(fn_factory(move || future::ok::<_, ()>(ws_service.clone())))
|
|
||||||
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
|
|
||||||
.tcp()
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
let mut framed = srv.ws().await.unwrap();
|
let mut framed = srv.ws().await.unwrap();
|
||||||
framed.send(ws::Message::Text("text".into())).await.unwrap();
|
framed.send(Message::Text("text".into())).await.unwrap();
|
||||||
let (item, mut framed) = framed.into_future().await;
|
|
||||||
assert_eq!(
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
item.unwrap().unwrap(),
|
assert_eq!(item, Frame::Text(Bytes::from_static(b"text")));
|
||||||
ws::Frame::Text(Bytes::from_static(b"text"))
|
|
||||||
);
|
framed.send(Message::Binary("text".into())).await.unwrap();
|
||||||
|
|
||||||
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
|
assert_eq!(item, Frame::Binary(Bytes::from_static(&b"text"[..])));
|
||||||
|
|
||||||
|
framed.send(Message::Ping("text".into())).await.unwrap();
|
||||||
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
|
assert_eq!(item, Frame::Pong("text".to_string().into()));
|
||||||
|
|
||||||
framed
|
framed
|
||||||
.send(ws::Message::Binary("text".into()))
|
.send(Message::Continuation(Item::FirstText("text".into())))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let (item, mut framed) = framed.into_future().await;
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
item.unwrap().unwrap(),
|
item,
|
||||||
ws::Frame::Binary(Bytes::from_static(&b"text"[..]))
|
Frame::Continuation(Item::FirstText(Bytes::from_static(b"text")))
|
||||||
);
|
|
||||||
|
|
||||||
framed.send(ws::Message::Ping("text".into())).await.unwrap();
|
|
||||||
let (item, mut framed) = framed.into_future().await;
|
|
||||||
assert_eq!(
|
|
||||||
item.unwrap().unwrap(),
|
|
||||||
ws::Frame::Pong("text".to_string().into())
|
|
||||||
);
|
|
||||||
|
|
||||||
framed
|
|
||||||
.send(ws::Message::Continuation(ws::Item::FirstText(
|
|
||||||
"text".into(),
|
|
||||||
)))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let (item, mut framed) = framed.into_future().await;
|
|
||||||
assert_eq!(
|
|
||||||
item.unwrap().unwrap(),
|
|
||||||
ws::Frame::Continuation(ws::Item::FirstText(Bytes::from_static(b"text")))
|
|
||||||
);
|
);
|
||||||
|
|
||||||
assert!(framed
|
assert!(framed
|
||||||
.send(ws::Message::Continuation(ws::Item::FirstText(
|
.send(Message::Continuation(Item::FirstText("text".into())))
|
||||||
"text".into()
|
|
||||||
)))
|
|
||||||
.await
|
.await
|
||||||
.is_err());
|
.is_err());
|
||||||
assert!(framed
|
assert!(framed
|
||||||
.send(ws::Message::Continuation(ws::Item::FirstBinary(
|
.send(Message::Continuation(Item::FirstBinary("text".into())))
|
||||||
"text".into()
|
|
||||||
)))
|
|
||||||
.await
|
.await
|
||||||
.is_err());
|
.is_err());
|
||||||
|
|
||||||
framed
|
framed
|
||||||
.send(ws::Message::Continuation(ws::Item::Continue("text".into())))
|
.send(Message::Continuation(Item::Continue("text".into())))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let (item, mut framed) = framed.into_future().await;
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
item.unwrap().unwrap(),
|
item,
|
||||||
ws::Frame::Continuation(ws::Item::Continue(Bytes::from_static(b"text")))
|
Frame::Continuation(Item::Continue(Bytes::from_static(b"text")))
|
||||||
);
|
);
|
||||||
|
|
||||||
framed
|
framed
|
||||||
.send(ws::Message::Continuation(ws::Item::Last("text".into())))
|
.send(Message::Continuation(Item::Last("text".into())))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let (item, mut framed) = framed.into_future().await;
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
item.unwrap().unwrap(),
|
item,
|
||||||
ws::Frame::Continuation(ws::Item::Last(Bytes::from_static(b"text")))
|
Frame::Continuation(Item::Last(Bytes::from_static(b"text")))
|
||||||
);
|
);
|
||||||
|
|
||||||
assert!(framed
|
assert!(framed
|
||||||
.send(ws::Message::Continuation(ws::Item::Continue("text".into())))
|
.send(Message::Continuation(Item::Continue("text".into())))
|
||||||
.await
|
.await
|
||||||
.is_err());
|
.is_err());
|
||||||
|
|
||||||
assert!(framed
|
assert!(framed
|
||||||
.send(ws::Message::Continuation(ws::Item::Last("text".into())))
|
.send(Message::Continuation(Item::Last("text".into())))
|
||||||
.await
|
.await
|
||||||
.is_err());
|
.is_err());
|
||||||
|
|
||||||
framed
|
framed
|
||||||
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
|
.send(Message::Close(Some(CloseCode::Normal.into())))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let (item, _framed) = framed.into_future().await;
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(item, Frame::Close(Some(CloseCode::Normal.into())));
|
||||||
item.unwrap().unwrap(),
|
|
||||||
ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(ws_service.was_polled());
|
|
||||||
}
|
}
|
||||||
|
@ -16,8 +16,8 @@ name = "actix_multipart"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "4.0.0-beta.5", default-features = false }
|
actix-web = { version = "4.0.0-beta.6", default-features = false }
|
||||||
actix-utils = "3.0.0-beta.4"
|
actix-utils = "3.0.0"
|
||||||
|
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
derive_more = "0.99.5"
|
derive_more = "0.99.5"
|
||||||
@ -31,6 +31,6 @@ twoway = "0.2"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-http = "3.0.0-beta.5"
|
actix-http = "3.0.0-beta.6"
|
||||||
tokio = { version = "1", features = ["sync"] }
|
tokio = { version = "1", features = ["sync"] }
|
||||||
tokio-stream = "0.1"
|
tokio-stream = "0.1"
|
||||||
|
@ -45,11 +45,10 @@ impl ResponseError for MultipartError {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use actix_web::HttpResponse;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_multipart_error() {
|
fn test_multipart_error() {
|
||||||
let resp: HttpResponse = MultipartError::Boundary.error_response();
|
let resp = MultipartError::Boundary.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,10 @@
|
|||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
|
||||||
|
|
||||||
|
## 0.1.0-beta.2 - 2021-04-17
|
||||||
|
* No significant changes from `0.1.0-beta.1`.
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-beta.1 - 2021-04-02
|
## 0.1.0-beta.1 - 2021-04-02
|
||||||
* Move integration testing structs from `actix-web`. [#2112]
|
* Move integration testing structs from `actix-web`. [#2112]
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-test"
|
name = "actix-test"
|
||||||
version = "0.1.0-beta.1"
|
version = "0.1.0-beta.2"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"Rob Ede <robjtede@icloud.com>",
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
@ -19,14 +19,14 @@ rustls = ["tls-rustls", "actix-http/rustls"]
|
|||||||
openssl = ["tls-openssl", "actix-http/openssl"]
|
openssl = ["tls-openssl", "actix-http/openssl"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0"
|
||||||
actix-http = { version = "3.0.0-beta.5", features = ["cookies"] }
|
actix-http = "3.0.0-beta.6"
|
||||||
actix-http-test = { version = "3.0.0-beta.4", features = [] }
|
actix-http-test = { version = "3.0.0-beta.4", features = [] }
|
||||||
actix-service = "2.0.0-beta.4"
|
actix-service = "2.0.0"
|
||||||
actix-utils = "3.0.0-beta.2"
|
actix-utils = "3.0.0"
|
||||||
actix-web = { version = "4.0.0-beta.5", default-features = false, features = ["cookies"] }
|
actix-web = { version = "4.0.0-beta.6", default-features = false, features = ["cookies"] }
|
||||||
actix-rt = "2.1"
|
actix-rt = "2.1"
|
||||||
awc = { version = "3.0.0-beta.4", default-features = false, features = ["cookies"] }
|
awc = { version = "3.0.0-beta.5", default-features = false, features = ["cookies"] }
|
||||||
|
|
||||||
futures-core = { version = "0.3.7", default-features = false, features = ["std"] }
|
futures-core = { version = "0.3.7", default-features = false, features = ["std"] }
|
||||||
futures-util = { version = "0.3.7", default-features = false, features = [] }
|
futures-util = { version = "0.3.7", default-features = false, features = [] }
|
||||||
|
@ -37,12 +37,12 @@ use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
|||||||
pub use actix_http::test::TestBuffer;
|
pub use actix_http::test::TestBuffer;
|
||||||
use actix_http::{
|
use actix_http::{
|
||||||
http::{HeaderMap, Method},
|
http::{HeaderMap, Method},
|
||||||
ws, HttpService, Request,
|
ws, HttpService, Request, Response,
|
||||||
};
|
};
|
||||||
use actix_service::{map_config, IntoServiceFactory, ServiceFactory};
|
use actix_service::{map_config, IntoServiceFactory, ServiceFactory};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::{AppConfig, MessageBody, Server, Service},
|
dev::{AppConfig, MessageBody, Server, Service},
|
||||||
rt, web, Error, HttpResponse,
|
rt, web, Error,
|
||||||
};
|
};
|
||||||
use awc::{error::PayloadError, Client, ClientRequest, ClientResponse, Connector};
|
use awc::{error::PayloadError, Client, ClientRequest, ClientResponse, Connector};
|
||||||
use futures_core::Stream;
|
use futures_core::Stream;
|
||||||
@ -83,9 +83,10 @@ where
|
|||||||
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
S: ServiceFactory<Request, Config = AppConfig> + '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<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
start_with(TestServerConfig::default(), factory)
|
start_with(TestServerConfig::default(), factory)
|
||||||
}
|
}
|
||||||
@ -122,9 +123,10 @@ where
|
|||||||
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
S: ServiceFactory<Request, Config = AppConfig> + '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<Response<B>> + 'static,
|
||||||
<S::Service as Service<Request>>::Future: 'static,
|
<S::Service as Service<Request>>::Future: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
B::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
|
@ -17,9 +17,9 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = { version = "0.11.0-beta.3", default-features = false }
|
actix = { version = "0.11.0-beta.3", default-features = false }
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0"
|
||||||
actix-http = "3.0.0-beta.5"
|
actix-http = "3.0.0-beta.6"
|
||||||
actix-web = { version = "4.0.0-beta.5", default-features = false }
|
actix-web = { version = "4.0.0-beta.6", default-features = false }
|
||||||
|
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
bytestring = "1"
|
bytestring = "1"
|
||||||
@ -29,8 +29,8 @@ tokio = { version = "1", features = ["sync"] }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-test = "0.1.0-beta.1"
|
actix-test = "0.1.0-beta.2"
|
||||||
|
|
||||||
awc = { version = "3.0.0-beta.4", default-features = false }
|
awc = { version = "3.0.0-beta.5", default-features = false }
|
||||||
env_logger = "0.8"
|
env_logger = "0.8"
|
||||||
futures-util = { version = "0.3.7", default-features = false }
|
futures-util = { version = "0.3.7", default-features = false }
|
||||||
|
@ -22,9 +22,9 @@ use actix_http::{
|
|||||||
http::HeaderValue,
|
http::HeaderValue,
|
||||||
ws::{hash_key, Codec},
|
ws::{hash_key, Codec},
|
||||||
};
|
};
|
||||||
use actix_web::dev::HttpResponseBuilder;
|
|
||||||
use actix_web::error::{Error, PayloadError};
|
use actix_web::error::{Error, PayloadError};
|
||||||
use actix_web::http::{header, Method, StatusCode};
|
use actix_web::http::{header, Method, StatusCode};
|
||||||
|
use actix_web::HttpResponseBuilder;
|
||||||
use actix_web::{HttpRequest, HttpResponse};
|
use actix_web::{HttpRequest, HttpResponse};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use bytestring::ByteString;
|
use bytestring::ByteString;
|
||||||
|
@ -20,9 +20,9 @@ proc-macro2 = "1"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.2"
|
actix-rt = "2.2"
|
||||||
actix-test = "0.1.0-beta.1"
|
actix-test = "0.1.0-beta.2"
|
||||||
actix-utils = "3.0.0-beta.4"
|
actix-utils = "3.0.0"
|
||||||
actix-web = "4.0.0-beta.5"
|
actix-web = "4.0.0-beta.6"
|
||||||
|
|
||||||
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||||
trybuild = "1"
|
trybuild = "1"
|
||||||
|
@ -1,10 +1,15 @@
|
|||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::task::{Context, Poll};
|
|
||||||
|
|
||||||
use actix_utils::future;
|
use actix_utils::future::{ok, Ready};
|
||||||
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
|
use actix_web::{
|
||||||
use actix_web::http::header::{HeaderName, HeaderValue};
|
dev::{Service, ServiceRequest, ServiceResponse, Transform},
|
||||||
use actix_web::{http, web::Path, App, Error, HttpResponse, Responder};
|
http::{
|
||||||
|
self,
|
||||||
|
header::{HeaderName, HeaderValue},
|
||||||
|
StatusCode,
|
||||||
|
},
|
||||||
|
web, App, Error, HttpResponse, Responder,
|
||||||
|
};
|
||||||
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, route, trace};
|
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, route, trace};
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
|
|
||||||
@ -56,26 +61,26 @@ async fn trace_test() -> impl Responder {
|
|||||||
|
|
||||||
#[get("/test")]
|
#[get("/test")]
|
||||||
fn auto_async() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
|
fn auto_async() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
|
||||||
future::ok(HttpResponse::Ok().finish())
|
ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/test")]
|
#[get("/test")]
|
||||||
fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
|
fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
|
||||||
future::ok(HttpResponse::Ok().finish())
|
ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[put("/test/{param}")]
|
#[put("/test/{param}")]
|
||||||
async fn put_param_test(_: Path<String>) -> impl Responder {
|
async fn put_param_test(_: web::Path<String>) -> impl Responder {
|
||||||
HttpResponse::Created()
|
HttpResponse::Created()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[delete("/test/{param}")]
|
#[delete("/test/{param}")]
|
||||||
async fn delete_param_test(_: Path<String>) -> impl Responder {
|
async fn delete_param_test(_: web::Path<String>) -> impl Responder {
|
||||||
HttpResponse::NoContent()
|
HttpResponse::NoContent()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/test/{param}")]
|
#[get("/test/{param}")]
|
||||||
async fn get_param_test(_: Path<String>) -> impl Responder {
|
async fn get_param_test(_: web::Path<String>) -> impl Responder {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,10 +108,10 @@ where
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Transform = ChangeStatusCodeMiddleware<S>;
|
type Transform = ChangeStatusCodeMiddleware<S>;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Future = future::Ready<Result<Self::Transform, Self::InitError>>;
|
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
fn new_transform(&self, service: S) -> Self::Future {
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
future::ok(ChangeStatusCodeMiddleware { service })
|
ok(ChangeStatusCodeMiddleware { service })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -124,9 +129,7 @@ where
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||||
|
|
||||||
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
actix_web::dev::forward_ready!(service);
|
||||||
self.service.poll_ready(cx)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||||
let fut = self.service.call(req);
|
let fut = self.service.call(req);
|
||||||
@ -143,7 +146,8 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[get("/test/wrap", wrap = "ChangeStatusCode")]
|
#[get("/test/wrap", wrap = "ChangeStatusCode")]
|
||||||
async fn get_wrap(_: Path<String>) -> impl Responder {
|
async fn get_wrap(_: web::Path<String>) -> impl Responder {
|
||||||
|
// panic!("actually never gets called because path failed to extract");
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -257,6 +261,10 @@ async fn test_wrap() {
|
|||||||
let srv = actix_test::start(|| App::new().service(get_wrap));
|
let srv = actix_test::start(|| App::new().service(get_wrap));
|
||||||
|
|
||||||
let request = srv.request(http::Method::GET, srv.url("/test/wrap"));
|
let request = srv.request(http::Method::GET, srv.url("/test/wrap"));
|
||||||
let response = request.send().await.unwrap();
|
let mut response = request.send().await.unwrap();
|
||||||
|
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||||
assert!(response.headers().contains_key("custom-header"));
|
assert!(response.headers().contains_key("custom-header"));
|
||||||
|
let body = response.body().await.unwrap();
|
||||||
|
let body = String::from_utf8(body.to_vec()).unwrap();
|
||||||
|
assert!(body.contains("wrong number of parameters"));
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
#[rustversion::stable(1.46)] // MSRV
|
||||||
#[test]
|
#[test]
|
||||||
fn compile_macros() {
|
fn compile_macros() {
|
||||||
let t = trybuild::TestCases::new();
|
let t = trybuild::TestCases::new();
|
||||||
@ -12,11 +13,3 @@ fn compile_macros() {
|
|||||||
|
|
||||||
t.pass("tests/trybuild/docstring-ok.rs");
|
t.pass("tests/trybuild/docstring-ok.rs");
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[rustversion::not(nightly)]
|
|
||||||
// fn skip_on_nightly(t: &trybuild::TestCases) {
|
|
||||||
//
|
|
||||||
// }
|
|
||||||
|
|
||||||
// #[rustversion::nightly]
|
|
||||||
// fn skip_on_nightly(_t: &trybuild::TestCases) {}
|
|
||||||
|
@ -3,6 +3,13 @@
|
|||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
|
||||||
|
|
||||||
|
## 3.0.0-beta.5 - 2021-04-17
|
||||||
|
### Removed
|
||||||
|
* Deprecated methods on `ClientRequest`: `if_true`, `if_some`. [#2148]
|
||||||
|
|
||||||
|
[#2148]: https://github.com/actix/actix-web/pull/2148
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.4 - 2021-04-02
|
## 3.0.0-beta.4 - 2021-04-02
|
||||||
### Added
|
### Added
|
||||||
* Add `Client::headers` to get default mut reference of `HeaderMap` of client object. [#2114]
|
* Add `Client::headers` to get default mut reference of `HeaderMap` of client object. [#2114]
|
||||||
|
@ -1,22 +1,20 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "awc"
|
name = "awc"
|
||||||
version = "3.0.0-beta.4"
|
version = "3.0.0-beta.5"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"fakeshadow <24548779@qq.com>",
|
"fakeshadow <24548779@qq.com>",
|
||||||
]
|
]
|
||||||
description = "Async HTTP and WebSocket client library built on the Actix ecosystem"
|
description = "Async HTTP and WebSocket client library built on the Actix ecosystem"
|
||||||
readme = "README.md"
|
|
||||||
keywords = ["actix", "http", "framework", "async", "web"]
|
keywords = ["actix", "http", "framework", "async", "web"]
|
||||||
homepage = "https://actix.rs"
|
|
||||||
repository = "https://github.com/actix/actix-web.git"
|
|
||||||
documentation = "https://docs.rs/awc/"
|
|
||||||
categories = [
|
categories = [
|
||||||
"network-programming",
|
"network-programming",
|
||||||
"asynchronous",
|
"asynchronous",
|
||||||
"web-programming::http-client",
|
"web-programming::http-client",
|
||||||
"web-programming::websocket",
|
"web-programming::websocket",
|
||||||
]
|
]
|
||||||
|
homepage = "https://actix.rs"
|
||||||
|
repository = "https://github.com/actix/actix-web"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
@ -41,19 +39,20 @@ rustls = ["tls-rustls", "actix-http/rustls"]
|
|||||||
compress = ["actix-http/compress"]
|
compress = ["actix-http/compress"]
|
||||||
|
|
||||||
# cookie parsing and cookie jar
|
# cookie parsing and cookie jar
|
||||||
cookies = ["actix-http/cookies"]
|
cookies = ["cookie"]
|
||||||
|
|
||||||
# trust-dns as dns resolver
|
# trust-dns as dns resolver
|
||||||
trust-dns = ["actix-http/trust-dns"]
|
trust-dns = ["actix-http/trust-dns"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.4.0-beta.1"
|
actix-codec = "0.4.0"
|
||||||
actix-service = "2.0.0-beta.4"
|
actix-service = "2.0.0"
|
||||||
actix-http = "3.0.0-beta.5"
|
actix-http = "3.0.0-beta.6"
|
||||||
actix-rt = { version = "2.1", default-features = false }
|
actix-rt = { version = "2.1", default-features = false }
|
||||||
|
|
||||||
base64 = "0.13"
|
base64 = "0.13"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
|
cookie = { version = "0.15", features = ["percent-encode"], optional = true }
|
||||||
derive_more = "0.99.5"
|
derive_more = "0.99.5"
|
||||||
futures-core = { version = "0.3.7", default-features = false }
|
futures-core = { version = "0.3.7", default-features = false }
|
||||||
itoa = "0.4"
|
itoa = "0.4"
|
||||||
@ -69,13 +68,13 @@ tls-openssl = { version = "0.10.9", package = "openssl", optional = true }
|
|||||||
tls-rustls = { version = "0.19.0", package = "rustls", optional = true, features = ["dangerous_configuration"] }
|
tls-rustls = { version = "0.19.0", package = "rustls", optional = true, features = ["dangerous_configuration"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "4.0.0-beta.5", features = ["openssl"] }
|
actix-web = { version = "4.0.0-beta.6", features = ["openssl"] }
|
||||||
actix-http = { version = "3.0.0-beta.5", features = ["openssl"] }
|
actix-http = { version = "3.0.0-beta.6", features = ["openssl"] }
|
||||||
actix-http-test = { version = "3.0.0-beta.4", features = ["openssl"] }
|
actix-http-test = { version = "3.0.0-beta.4", features = ["openssl"] }
|
||||||
actix-utils = "3.0.0-beta.4"
|
actix-utils = "3.0.0"
|
||||||
actix-server = "2.0.0-beta.3"
|
actix-server = "2.0.0-beta.3"
|
||||||
actix-tls = { version = "3.0.0-beta.5", features = ["openssl", "rustls"] }
|
actix-tls = { version = "3.0.0-beta.5", features = ["openssl", "rustls"] }
|
||||||
actix-test = { version = "0.1.0-beta.1", features = ["openssl", "rustls"] }
|
actix-test = { version = "0.1.0-beta.2", features = ["openssl", "rustls"] }
|
||||||
|
|
||||||
brotli2 = "0.3.2"
|
brotli2 = "0.3.2"
|
||||||
env_logger = "0.8"
|
env_logger = "0.8"
|
||||||
|
@ -93,12 +93,11 @@
|
|||||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||||
|
|
||||||
use std::convert::TryFrom;
|
use std::{convert::TryFrom, rc::Rc, time::Duration};
|
||||||
use std::rc::Rc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
#[cfg(feature = "cookies")]
|
||||||
pub use actix_http::cookie;
|
pub use cookie;
|
||||||
|
|
||||||
pub use actix_http::{client::Connector, http};
|
pub use actix_http::{client::Connector, http};
|
||||||
|
|
||||||
use actix_http::{
|
use actix_http::{
|
||||||
|
@ -8,14 +8,14 @@ use futures_core::Stream;
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use actix_http::body::Body;
|
use actix_http::body::Body;
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
use actix_http::cookie::{Cookie, CookieJar};
|
|
||||||
use actix_http::http::header::{self, IntoHeaderPair};
|
use actix_http::http::header::{self, IntoHeaderPair};
|
||||||
use actix_http::http::{
|
use actix_http::http::{
|
||||||
uri, ConnectionType, Error as HttpError, HeaderMap, HeaderValue, Method, Uri, Version,
|
uri, ConnectionType, Error as HttpError, HeaderMap, HeaderValue, Method, Uri, Version,
|
||||||
};
|
};
|
||||||
use actix_http::{Error, RequestHead};
|
use actix_http::{Error, RequestHead};
|
||||||
|
|
||||||
|
#[cfg(feature = "cookies")]
|
||||||
|
use crate::cookie::{Cookie, CookieJar};
|
||||||
use crate::error::{FreezeRequestError, InvalidUrl};
|
use crate::error::{FreezeRequestError, InvalidUrl};
|
||||||
use crate::frozen::FrozenClientRequest;
|
use crate::frozen::FrozenClientRequest;
|
||||||
use crate::sender::{PrepForSendingError, RequestSender, SendClientRequest};
|
use crate::sender::{PrepForSendingError, RequestSender, SendClientRequest};
|
||||||
@ -271,7 +271,7 @@ impl ClientRequest {
|
|||||||
/// async fn main() {
|
/// async fn main() {
|
||||||
/// let resp = awc::Client::new().get("https://www.rust-lang.org")
|
/// let resp = awc::Client::new().get("https://www.rust-lang.org")
|
||||||
/// .cookie(
|
/// .cookie(
|
||||||
/// awc::http::Cookie::build("name", "value")
|
/// awc::cookie::Cookie::build("name", "value")
|
||||||
/// .domain("www.rust-lang.org")
|
/// .domain("www.rust-lang.org")
|
||||||
/// .path("/")
|
/// .path("/")
|
||||||
/// .secure(true)
|
/// .secure(true)
|
||||||
@ -311,34 +311,6 @@ impl ClientRequest {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This method calls provided closure with builder reference if value is `true`.
|
|
||||||
#[doc(hidden)]
|
|
||||||
#[deprecated = "Use an if statement."]
|
|
||||||
pub fn if_true<F>(self, value: bool, f: F) -> Self
|
|
||||||
where
|
|
||||||
F: FnOnce(ClientRequest) -> ClientRequest,
|
|
||||||
{
|
|
||||||
if value {
|
|
||||||
f(self)
|
|
||||||
} else {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This method calls provided closure with builder reference if value is `Some`.
|
|
||||||
#[doc(hidden)]
|
|
||||||
#[deprecated = "Use an if-let construction."]
|
|
||||||
pub fn if_some<T, F>(self, value: Option<T>, f: F) -> Self
|
|
||||||
where
|
|
||||||
F: FnOnce(T, ClientRequest) -> ClientRequest,
|
|
||||||
{
|
|
||||||
if let Some(val) = value {
|
|
||||||
f(val, self)
|
|
||||||
} else {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the query part of the request
|
/// Sets the query part of the request
|
||||||
pub fn query<T: Serialize>(
|
pub fn query<T: Serialize>(
|
||||||
mut self,
|
mut self,
|
||||||
@ -494,7 +466,7 @@ impl ClientRequest {
|
|||||||
let cookie: String = jar
|
let cookie: String = jar
|
||||||
.delta()
|
.delta()
|
||||||
// ensure only name=value is written to cookie header
|
// ensure only name=value is written to cookie header
|
||||||
.map(|c| Cookie::new(c.name(), c.value()).encoded().to_string())
|
.map(|c| c.stripped().encoded().to_string())
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("; ");
|
.join("; ");
|
||||||
|
|
||||||
|
@ -20,8 +20,7 @@ use futures_core::{ready, Stream};
|
|||||||
use serde::de::DeserializeOwned;
|
use serde::de::DeserializeOwned;
|
||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
#[cfg(feature = "cookies")]
|
||||||
use actix_http::{cookie::Cookie, error::CookieParseError};
|
use crate::cookie::{Cookie, ParseError as CookieParseError};
|
||||||
|
|
||||||
use crate::error::JsonPayloadError;
|
use crate::error::JsonPayloadError;
|
||||||
|
|
||||||
/// Client Response
|
/// Client Response
|
||||||
@ -80,24 +79,6 @@ impl<S> HttpMessage for ClientResponse<S> {
|
|||||||
fn extensions_mut(&self) -> RefMut<'_, Extensions> {
|
fn extensions_mut(&self) -> RefMut<'_, Extensions> {
|
||||||
self.head.extensions_mut()
|
self.head.extensions_mut()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load request cookies.
|
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
|
|
||||||
struct Cookies(Vec<Cookie<'static>>);
|
|
||||||
|
|
||||||
if self.extensions().get::<Cookies>().is_none() {
|
|
||||||
let mut cookies = Vec::new();
|
|
||||||
for hdr in self.headers().get_all(&header::SET_COOKIE) {
|
|
||||||
let s = std::str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
|
|
||||||
cookies.push(Cookie::parse_encoded(s)?.into_owned());
|
|
||||||
}
|
|
||||||
self.extensions_mut().insert(Cookies(cookies));
|
|
||||||
}
|
|
||||||
Ok(Ref::map(self.extensions(), |ext| {
|
|
||||||
&ext.get::<Cookies>().unwrap().0
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> ClientResponse<S> {
|
impl<S> ClientResponse<S> {
|
||||||
@ -180,6 +161,37 @@ impl<S> ClientResponse<S> {
|
|||||||
self.timeout = ResponseTimeout::Disabled(timeout);
|
self.timeout = ResponseTimeout::Disabled(timeout);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Load request cookies.
|
||||||
|
#[cfg(feature = "cookies")]
|
||||||
|
pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
|
||||||
|
struct Cookies(Vec<Cookie<'static>>);
|
||||||
|
|
||||||
|
if self.extensions().get::<Cookies>().is_none() {
|
||||||
|
let mut cookies = Vec::new();
|
||||||
|
for hdr in self.headers().get_all(&header::SET_COOKIE) {
|
||||||
|
let s = std::str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
|
||||||
|
cookies.push(Cookie::parse_encoded(s)?.into_owned());
|
||||||
|
}
|
||||||
|
self.extensions_mut().insert(Cookies(cookies));
|
||||||
|
}
|
||||||
|
Ok(Ref::map(self.extensions(), |ext| {
|
||||||
|
&ext.get::<Cookies>().unwrap().0
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return request cookie.
|
||||||
|
#[cfg(feature = "cookies")]
|
||||||
|
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
|
||||||
|
if let Ok(cookies) = self.cookies() {
|
||||||
|
for cookie in cookies.iter() {
|
||||||
|
if cookie.name() == name {
|
||||||
|
return Some(cookie.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> ClientResponse<S>
|
impl<S> ClientResponse<S>
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
future::Future,
|
future::Future,
|
||||||
net,
|
io, net,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
rc::Rc,
|
rc::Rc,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
@ -209,7 +209,8 @@ impl RequestSender {
|
|||||||
) -> SendClientRequest {
|
) -> SendClientRequest {
|
||||||
let body = match serde_json::to_string(value) {
|
let body = match serde_json::to_string(value) {
|
||||||
Ok(body) => body,
|
Ok(body) => body,
|
||||||
Err(e) => return Error::from(e).into(),
|
// TODO: own error type
|
||||||
|
Err(e) => return Error::from(io::Error::new(io::ErrorKind::Other, e)).into(),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Err(e) = self.set_header_if_none(header::CONTENT_TYPE, "application/json") {
|
if let Err(e) = self.set_header_if_none(header::CONTENT_TYPE, "application/json") {
|
||||||
@ -235,7 +236,8 @@ impl RequestSender {
|
|||||||
) -> SendClientRequest {
|
) -> SendClientRequest {
|
||||||
let body = match serde_urlencoded::to_string(value) {
|
let body = match serde_urlencoded::to_string(value) {
|
||||||
Ok(body) => body,
|
Ok(body) => body,
|
||||||
Err(e) => return Error::from(e).into(),
|
// TODO: own error type
|
||||||
|
Err(e) => return Error::from(io::Error::new(io::ErrorKind::Other, e)).into(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// set content-type
|
// set content-type
|
||||||
|
@ -1,14 +1,11 @@
|
|||||||
//! Test helpers for actix http client to use during testing.
|
//! Test helpers for actix http client to use during testing.
|
||||||
use actix_http::http::header::IntoHeaderPair;
|
use actix_http::http::header::IntoHeaderPair;
|
||||||
use actix_http::http::{StatusCode, Version};
|
use actix_http::http::{StatusCode, Version};
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
use actix_http::{
|
|
||||||
cookie::{Cookie, CookieJar},
|
|
||||||
http::header::{self, HeaderValue},
|
|
||||||
};
|
|
||||||
use actix_http::{h1, Payload, ResponseHead};
|
use actix_http::{h1, Payload, ResponseHead};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
|
||||||
|
#[cfg(feature = "cookies")]
|
||||||
|
use crate::cookie::{Cookie, CookieJar};
|
||||||
use crate::ClientResponse;
|
use crate::ClientResponse;
|
||||||
|
|
||||||
/// Test `ClientResponse` builder
|
/// Test `ClientResponse` builder
|
||||||
@ -92,6 +89,8 @@ impl TestResponse {
|
|||||||
|
|
||||||
#[cfg(feature = "cookies")]
|
#[cfg(feature = "cookies")]
|
||||||
for cookie in self.cookies.delta() {
|
for cookie in self.cookies.delta() {
|
||||||
|
use actix_http::http::header::{self, HeaderValue};
|
||||||
|
|
||||||
head.headers.insert(
|
head.headers.insert(
|
||||||
header::SET_COOKIE,
|
header::SET_COOKIE,
|
||||||
HeaderValue::from_str(&cookie.encoded().to_string()).unwrap(),
|
HeaderValue::from_str(&cookie.encoded().to_string()).unwrap(),
|
||||||
|
@ -31,8 +31,6 @@ use std::net::SocketAddr;
|
|||||||
use std::{fmt, str};
|
use std::{fmt, str};
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
#[cfg(feature = "cookies")]
|
|
||||||
use actix_http::cookie::{Cookie, CookieJar};
|
|
||||||
use actix_http::{ws, Payload, RequestHead};
|
use actix_http::{ws, Payload, RequestHead};
|
||||||
use actix_rt::time::timeout;
|
use actix_rt::time::timeout;
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
@ -40,6 +38,8 @@ use actix_service::Service;
|
|||||||
pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message};
|
pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message};
|
||||||
|
|
||||||
use crate::connect::{BoxedSocket, ConnectRequest};
|
use crate::connect::{BoxedSocket, ConnectRequest};
|
||||||
|
#[cfg(feature = "cookies")]
|
||||||
|
use crate::cookie::{Cookie, CookieJar};
|
||||||
use crate::error::{InvalidUrl, SendRequestError, WsClientError};
|
use crate::error::{InvalidUrl, SendRequestError, WsClientError};
|
||||||
use crate::http::header::{self, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION};
|
use crate::http::header::{self, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION};
|
||||||
use crate::http::{ConnectionType, Error as HttpError, Method, StatusCode, Uri, Version};
|
use crate::http::{ConnectionType, Error as HttpError, Method, StatusCode, Uri, Version};
|
||||||
@ -280,7 +280,7 @@ impl WebsocketsRequest {
|
|||||||
let cookie: String = jar
|
let cookie: String = jar
|
||||||
.delta()
|
.delta()
|
||||||
// ensure only name=value is written to cookie header
|
// ensure only name=value is written to cookie header
|
||||||
.map(|c| Cookie::new(c.name(), c.value()).encoded().to_string())
|
.map(|c| c.stripped().encoded().to_string())
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("; ");
|
.join("; ");
|
||||||
|
|
||||||
|
@ -8,6 +8,7 @@ use std::time::Duration;
|
|||||||
use actix_utils::future::ok;
|
use actix_utils::future::ok;
|
||||||
use brotli2::write::BrotliEncoder;
|
use brotli2::write::BrotliEncoder;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
use cookie::Cookie;
|
||||||
use flate2::read::GzDecoder;
|
use flate2::read::GzDecoder;
|
||||||
use flate2::write::GzEncoder;
|
use flate2::write::GzEncoder;
|
||||||
use flate2::Compression;
|
use flate2::Compression;
|
||||||
@ -19,12 +20,12 @@ use actix_http::{
|
|||||||
HttpService,
|
HttpService,
|
||||||
};
|
};
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::{map_config, pipeline_factory};
|
use actix_service::{fn_service, map_config, ServiceFactoryExt as _};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::{AppConfig, BodyEncoding},
|
dev::{AppConfig, BodyEncoding},
|
||||||
http::{header, Cookie},
|
http::header,
|
||||||
middleware::Compress,
|
middleware::Compress,
|
||||||
web, App, Error, HttpMessage, HttpRequest, HttpResponse,
|
web, App, Error, HttpRequest, HttpResponse,
|
||||||
};
|
};
|
||||||
use awc::error::{JsonPayloadError, PayloadError, SendRequestError};
|
use awc::error::{JsonPayloadError, PayloadError, SendRequestError};
|
||||||
|
|
||||||
@ -238,7 +239,7 @@ async fn test_connection_reuse() {
|
|||||||
|
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
pipeline_factory(move |io| {
|
fn_service(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
@ -275,7 +276,7 @@ async fn test_connection_force_close() {
|
|||||||
|
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
pipeline_factory(move |io| {
|
fn_service(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
@ -312,7 +313,7 @@ async fn test_connection_server_close() {
|
|||||||
|
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
pipeline_factory(move |io| {
|
fn_service(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
@ -352,7 +353,7 @@ async fn test_connection_wait_queue() {
|
|||||||
|
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
pipeline_factory(move |io| {
|
fn_service(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
@ -400,7 +401,7 @@ async fn test_connection_wait_queue_force_close() {
|
|||||||
|
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
pipeline_factory(move |io| {
|
fn_service(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
|
@ -12,7 +12,7 @@ use std::{
|
|||||||
|
|
||||||
use actix_http::HttpService;
|
use actix_http::HttpService;
|
||||||
use actix_http_test::test_server;
|
use actix_http_test::test_server;
|
||||||
use actix_service::{map_config, pipeline_factory, ServiceFactoryExt};
|
use actix_service::{fn_service, map_config, ServiceFactoryExt};
|
||||||
use actix_utils::future::ok;
|
use actix_utils::future::ok;
|
||||||
use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse};
|
use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse};
|
||||||
use rustls::internal::pemfile::{certs, pkcs8_private_keys};
|
use rustls::internal::pemfile::{certs, pkcs8_private_keys};
|
||||||
@ -57,7 +57,7 @@ async fn test_connection_reuse_h2() {
|
|||||||
|
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
pipeline_factory(move |io| {
|
fn_service(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
|
@ -7,7 +7,7 @@ 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::{map_config, pipeline_factory, ServiceFactoryExt};
|
use actix_service::{fn_service, map_config, ServiceFactoryExt};
|
||||||
use actix_utils::future::ok;
|
use actix_utils::future::ok;
|
||||||
use actix_web::http::Version;
|
use actix_web::http::Version;
|
||||||
use actix_web::{dev::AppConfig, web, App, HttpResponse};
|
use actix_web::{dev::AppConfig, web, App, HttpResponse};
|
||||||
@ -48,7 +48,7 @@ async fn test_connection_reuse_h2() {
|
|||||||
|
|
||||||
let srv = test_server(move || {
|
let srv = test_server(move || {
|
||||||
let num2 = num2.clone();
|
let num2 = num2.clone();
|
||||||
pipeline_factory(move |io| {
|
fn_service(move |io| {
|
||||||
num2.fetch_add(1, Ordering::Relaxed);
|
num2.fetch_add(1, Ordering::Relaxed);
|
||||||
ok(io)
|
ok(io)
|
||||||
})
|
})
|
||||||
|
@ -36,7 +36,7 @@ async fn test_simple() {
|
|||||||
ws::Dispatcher::with(framed, ws_service).await
|
ws::Dispatcher::with(framed, ws_service).await
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.finish(|_| ok::<_, Error>(Response::NotFound()))
|
.finish(|_| ok::<_, Error>(Response::not_found()))
|
||||||
.tcp()
|
.tcp()
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use actix_web::{test, web, App, HttpResponse};
|
use actix_web::{web, App, HttpResponse};
|
||||||
use awc::Client;
|
use awc::Client;
|
||||||
use criterion::{criterion_group, criterion_main, Criterion};
|
use criterion::{criterion_group, criterion_main, Criterion};
|
||||||
use futures_util::future::join_all;
|
use futures_util::future::join_all;
|
||||||
|
@ -1,20 +1,23 @@
|
|||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::{Extensions, Request, Response};
|
use actix_http::{Extensions, Request};
|
||||||
use actix_router::{Path, ResourceDef, Router, Url};
|
use actix_router::{Path, ResourceDef, Router, Url};
|
||||||
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
|
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
|
||||||
use actix_service::{fn_service, Service, ServiceFactory};
|
use actix_service::{fn_service, Service, ServiceFactory};
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
use futures_util::future::join_all;
|
use futures_util::future::join_all;
|
||||||
|
|
||||||
use crate::config::{AppConfig, AppService};
|
|
||||||
use crate::data::FnDataFactory;
|
use crate::data::FnDataFactory;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::guard::Guard;
|
use crate::guard::Guard;
|
||||||
use crate::request::{HttpRequest, HttpRequestPool};
|
use crate::request::{HttpRequest, HttpRequestPool};
|
||||||
use crate::rmap::ResourceMap;
|
use crate::rmap::ResourceMap;
|
||||||
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
|
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
|
||||||
|
use crate::{
|
||||||
|
config::{AppConfig, AppService},
|
||||||
|
HttpResponse,
|
||||||
|
};
|
||||||
|
|
||||||
type Guards = Vec<Box<dyn Guard>>;
|
type Guards = Vec<Box<dyn Guard>>;
|
||||||
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
|
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
|
||||||
@ -64,7 +67,7 @@ where
|
|||||||
// if no user defined default service exists.
|
// if no user defined default service exists.
|
||||||
let default = self.default.clone().unwrap_or_else(|| {
|
let default = self.default.clone().unwrap_or_else(|| {
|
||||||
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async {
|
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async {
|
||||||
Ok(req.into_response(Response::NotFound().finish()))
|
Ok(req.into_response(HttpResponse::NotFound()))
|
||||||
})))
|
})))
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -163,8 +166,7 @@ impl AppInitServiceState {
|
|||||||
Rc::new(AppInitServiceState {
|
Rc::new(AppInitServiceState {
|
||||||
rmap,
|
rmap,
|
||||||
config,
|
config,
|
||||||
// TODO: AppConfig can be used to pass user defined HttpRequestPool
|
// TODO: AppConfig can be used to pass user defined HttpRequestPool capacity.
|
||||||
// capacity.
|
|
||||||
pool: HttpRequestPool::default(),
|
pool: HttpRequestPool::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
13
src/data.rs
13
src/data.rs
@ -1,16 +1,13 @@
|
|||||||
use std::any::type_name;
|
use std::{any::type_name, ops::Deref, sync::Arc};
|
||||||
use std::ops::Deref;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use actix_http::error::{Error, ErrorInternalServerError};
|
use actix_http::{error::Error, Extensions};
|
||||||
use actix_http::Extensions;
|
|
||||||
use actix_utils::future::{err, ok, Ready};
|
use actix_utils::future::{err, ok, Ready};
|
||||||
use futures_core::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use crate::dev::Payload;
|
use crate::{
|
||||||
use crate::extract::FromRequest;
|
dev::Payload, error::ErrorInternalServerError, extract::FromRequest, request::HttpRequest,
|
||||||
use crate::request::HttpRequest;
|
};
|
||||||
|
|
||||||
/// Data factory.
|
/// Data factory.
|
||||||
pub(crate) trait DataFactory {
|
pub(crate) trait DataFactory {
|
||||||
|
304
src/error/internal.rs
Normal file
304
src/error/internal.rs
Normal file
@ -0,0 +1,304 @@
|
|||||||
|
use std::{cell::RefCell, fmt, io::Write as _};
|
||||||
|
|
||||||
|
use actix_http::{body::Body, header, Response, StatusCode};
|
||||||
|
use bytes::{BufMut as _, BytesMut};
|
||||||
|
|
||||||
|
use crate::{Error, HttpResponse, ResponseError};
|
||||||
|
|
||||||
|
/// Wraps errors to alter the generated response status code.
|
||||||
|
///
|
||||||
|
/// In following example, the `io::Error` is wrapped into `ErrorBadRequest` which will generate a
|
||||||
|
/// response with the 400 Bad Request status code instead of the usual status code generated by
|
||||||
|
/// an `io::Error`.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// # use std::io;
|
||||||
|
/// # use actix_web::{error, HttpRequest};
|
||||||
|
/// async fn handler_error() -> Result<String, actix_web::Error> {
|
||||||
|
/// let err = io::Error::new(io::ErrorKind::Other, "error");
|
||||||
|
/// Err(error::ErrorBadRequest(err))
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub struct InternalError<T> {
|
||||||
|
cause: T,
|
||||||
|
status: InternalErrorType,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum InternalErrorType {
|
||||||
|
Status(StatusCode),
|
||||||
|
Response(RefCell<Option<HttpResponse>>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> InternalError<T> {
|
||||||
|
/// Constructs an `InternalError` with given status code.
|
||||||
|
pub fn new(cause: T, status: StatusCode) -> Self {
|
||||||
|
InternalError {
|
||||||
|
cause,
|
||||||
|
status: InternalErrorType::Status(status),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Constructs an `InternalError` with pre-defined response.
|
||||||
|
pub fn from_response(cause: T, response: HttpResponse) -> Self {
|
||||||
|
InternalError {
|
||||||
|
cause,
|
||||||
|
status: InternalErrorType::Response(RefCell::new(Some(response))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: fmt::Debug> fmt::Debug for InternalError<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
self.cause.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: fmt::Display> fmt::Display for InternalError<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
self.cause.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> ResponseError for InternalError<T>
|
||||||
|
where
|
||||||
|
T: fmt::Debug + fmt::Display,
|
||||||
|
{
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
match self.status {
|
||||||
|
InternalErrorType::Status(st) => st,
|
||||||
|
InternalErrorType::Response(ref resp) => {
|
||||||
|
if let Some(resp) = resp.borrow().as_ref() {
|
||||||
|
resp.head().status
|
||||||
|
} else {
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_response(&self) -> Response<Body> {
|
||||||
|
match self.status {
|
||||||
|
InternalErrorType::Status(status) => {
|
||||||
|
let mut res = Response::new(status);
|
||||||
|
let mut buf = BytesMut::new().writer();
|
||||||
|
let _ = write!(buf, "{}", self);
|
||||||
|
|
||||||
|
res.headers_mut().insert(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
header::HeaderValue::from_static("text/plain; charset=utf-8"),
|
||||||
|
);
|
||||||
|
res.set_body(Body::from(buf.into_inner())).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
InternalErrorType::Response(ref resp) => {
|
||||||
|
if let Some(resp) = resp.borrow_mut().take() {
|
||||||
|
resp.into()
|
||||||
|
} else {
|
||||||
|
Response::new(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! error_helper {
|
||||||
|
($name:ident, $status:ident) => {
|
||||||
|
paste::paste! {
|
||||||
|
#[doc = "Helper function that wraps any error and generates a `" $status "` response."]
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
pub fn $name<T>(err: T) -> Error
|
||||||
|
where
|
||||||
|
T: fmt::Debug + fmt::Display + 'static,
|
||||||
|
{
|
||||||
|
InternalError::new(err, StatusCode::$status).into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
error_helper!(ErrorBadRequest, BAD_REQUEST);
|
||||||
|
error_helper!(ErrorUnauthorized, UNAUTHORIZED);
|
||||||
|
error_helper!(ErrorPaymentRequired, PAYMENT_REQUIRED);
|
||||||
|
error_helper!(ErrorForbidden, FORBIDDEN);
|
||||||
|
error_helper!(ErrorNotFound, NOT_FOUND);
|
||||||
|
error_helper!(ErrorMethodNotAllowed, METHOD_NOT_ALLOWED);
|
||||||
|
error_helper!(ErrorNotAcceptable, NOT_ACCEPTABLE);
|
||||||
|
error_helper!(
|
||||||
|
ErrorProxyAuthenticationRequired,
|
||||||
|
PROXY_AUTHENTICATION_REQUIRED
|
||||||
|
);
|
||||||
|
error_helper!(ErrorRequestTimeout, REQUEST_TIMEOUT);
|
||||||
|
error_helper!(ErrorConflict, CONFLICT);
|
||||||
|
error_helper!(ErrorGone, GONE);
|
||||||
|
error_helper!(ErrorLengthRequired, LENGTH_REQUIRED);
|
||||||
|
error_helper!(ErrorPayloadTooLarge, PAYLOAD_TOO_LARGE);
|
||||||
|
error_helper!(ErrorUriTooLong, URI_TOO_LONG);
|
||||||
|
error_helper!(ErrorUnsupportedMediaType, UNSUPPORTED_MEDIA_TYPE);
|
||||||
|
error_helper!(ErrorRangeNotSatisfiable, RANGE_NOT_SATISFIABLE);
|
||||||
|
error_helper!(ErrorImATeapot, IM_A_TEAPOT);
|
||||||
|
error_helper!(ErrorMisdirectedRequest, MISDIRECTED_REQUEST);
|
||||||
|
error_helper!(ErrorUnprocessableEntity, UNPROCESSABLE_ENTITY);
|
||||||
|
error_helper!(ErrorLocked, LOCKED);
|
||||||
|
error_helper!(ErrorFailedDependency, FAILED_DEPENDENCY);
|
||||||
|
error_helper!(ErrorUpgradeRequired, UPGRADE_REQUIRED);
|
||||||
|
error_helper!(ErrorPreconditionFailed, PRECONDITION_FAILED);
|
||||||
|
error_helper!(ErrorPreconditionRequired, PRECONDITION_REQUIRED);
|
||||||
|
error_helper!(ErrorTooManyRequests, TOO_MANY_REQUESTS);
|
||||||
|
error_helper!(
|
||||||
|
ErrorRequestHeaderFieldsTooLarge,
|
||||||
|
REQUEST_HEADER_FIELDS_TOO_LARGE
|
||||||
|
);
|
||||||
|
error_helper!(
|
||||||
|
ErrorUnavailableForLegalReasons,
|
||||||
|
UNAVAILABLE_FOR_LEGAL_REASONS
|
||||||
|
);
|
||||||
|
error_helper!(ErrorExpectationFailed, EXPECTATION_FAILED);
|
||||||
|
error_helper!(ErrorInternalServerError, INTERNAL_SERVER_ERROR);
|
||||||
|
error_helper!(ErrorNotImplemented, NOT_IMPLEMENTED);
|
||||||
|
error_helper!(ErrorBadGateway, BAD_GATEWAY);
|
||||||
|
error_helper!(ErrorServiceUnavailable, SERVICE_UNAVAILABLE);
|
||||||
|
error_helper!(ErrorGatewayTimeout, GATEWAY_TIMEOUT);
|
||||||
|
error_helper!(ErrorHttpVersionNotSupported, HTTP_VERSION_NOT_SUPPORTED);
|
||||||
|
error_helper!(ErrorVariantAlsoNegotiates, VARIANT_ALSO_NEGOTIATES);
|
||||||
|
error_helper!(ErrorInsufficientStorage, INSUFFICIENT_STORAGE);
|
||||||
|
error_helper!(ErrorLoopDetected, LOOP_DETECTED);
|
||||||
|
error_helper!(ErrorNotExtended, NOT_EXTENDED);
|
||||||
|
error_helper!(
|
||||||
|
ErrorNetworkAuthenticationRequired,
|
||||||
|
NETWORK_AUTHENTICATION_REQUIRED
|
||||||
|
);
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use actix_http::{error::ParseError, Response};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_internal_error() {
|
||||||
|
let err = InternalError::from_response(ParseError::Method, HttpResponse::Ok().finish());
|
||||||
|
let resp: Response<Body> = err.error_response();
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_error_helpers() {
|
||||||
|
let res: Response<Body> = ErrorBadRequest("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorUnauthorized("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorPaymentRequired("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::PAYMENT_REQUIRED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorForbidden("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::FORBIDDEN);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorNotFound("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorMethodNotAllowed("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorNotAcceptable("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::NOT_ACCEPTABLE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorProxyAuthenticationRequired("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorRequestTimeout("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorConflict("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::CONFLICT);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorGone("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::GONE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorLengthRequired("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::LENGTH_REQUIRED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorPreconditionFailed("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::PRECONDITION_FAILED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorPayloadTooLarge("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorUriTooLong("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::URI_TOO_LONG);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorUnsupportedMediaType("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorRangeNotSatisfiable("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorExpectationFailed("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::EXPECTATION_FAILED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorImATeapot("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::IM_A_TEAPOT);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorMisdirectedRequest("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::MISDIRECTED_REQUEST);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorUnprocessableEntity("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorLocked("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::LOCKED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorFailedDependency("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::FAILED_DEPENDENCY);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorUpgradeRequired("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::UPGRADE_REQUIRED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorPreconditionRequired("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::PRECONDITION_REQUIRED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorTooManyRequests("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorRequestHeaderFieldsTooLarge("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorUnavailableForLegalReasons("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorInternalServerError("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorNotImplemented("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::NOT_IMPLEMENTED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorBadGateway("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::BAD_GATEWAY);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorServiceUnavailable("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorGatewayTimeout("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorHttpVersionNotSupported("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorVariantAlsoNegotiates("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::VARIANT_ALSO_NEGOTIATES);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorInsufficientStorage("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::INSUFFICIENT_STORAGE);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorLoopDetected("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::LOOP_DETECTED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorNotExtended("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::NOT_EXTENDED);
|
||||||
|
|
||||||
|
let res: Response<Body> = ErrorNetworkAuthenticationRequired("err").into();
|
||||||
|
assert_eq!(res.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED);
|
||||||
|
}
|
||||||
|
}
|
@ -3,12 +3,24 @@
|
|||||||
pub use actix_http::error::*;
|
pub use actix_http::error::*;
|
||||||
use derive_more::{Display, Error, From};
|
use derive_more::{Display, Error, From};
|
||||||
use serde_json::error::Error as JsonError;
|
use serde_json::error::Error as JsonError;
|
||||||
|
use serde_urlencoded::de::Error as FormDeError;
|
||||||
|
use serde_urlencoded::ser::Error as FormError;
|
||||||
use url::ParseError as UrlParseError;
|
use url::ParseError as UrlParseError;
|
||||||
|
|
||||||
use crate::{http::StatusCode, HttpResponse};
|
use crate::http::StatusCode;
|
||||||
|
|
||||||
|
mod internal;
|
||||||
|
|
||||||
|
pub use self::internal::*;
|
||||||
|
|
||||||
|
/// A convenience [`Result`](std::result::Result) for Actix Web operations.
|
||||||
|
///
|
||||||
|
/// This type alias is generally used to avoid writing out `actix_http::Error` directly.
|
||||||
|
pub type Result<T, E = actix_http::Error> = std::result::Result<T, E>;
|
||||||
|
|
||||||
/// 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, Error, From)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum UrlGenerationError {
|
pub enum UrlGenerationError {
|
||||||
/// Resource not found
|
/// Resource not found
|
||||||
#[display(fmt = "Resource not found")]
|
#[display(fmt = "Resource not found")]
|
||||||
@ -23,13 +35,11 @@ pub enum UrlGenerationError {
|
|||||||
ParseError(UrlParseError),
|
ParseError(UrlParseError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for UrlGenerationError {}
|
|
||||||
|
|
||||||
/// `InternalServerError` for `UrlGeneratorError`
|
|
||||||
impl ResponseError for UrlGenerationError {}
|
impl ResponseError for UrlGenerationError {}
|
||||||
|
|
||||||
/// A set of errors that can occur during parsing urlencoded payloads
|
/// A set of errors that can occur during parsing urlencoded payloads
|
||||||
#[derive(Debug, Display, Error, From)]
|
#[derive(Debug, Display, Error, From)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum UrlencodedError {
|
pub enum UrlencodedError {
|
||||||
/// Can not decode chunked transfer encoding.
|
/// Can not decode chunked transfer encoding.
|
||||||
#[display(fmt = "Can not decode chunked transfer encoding.")]
|
#[display(fmt = "Can not decode chunked transfer encoding.")]
|
||||||
@ -52,64 +62,84 @@ pub enum UrlencodedError {
|
|||||||
ContentType,
|
ContentType,
|
||||||
|
|
||||||
/// Parse error.
|
/// Parse error.
|
||||||
#[display(fmt = "Parse error.")]
|
#[display(fmt = "Parse error: {}.", _0)]
|
||||||
Parse,
|
Parse(FormDeError),
|
||||||
|
|
||||||
|
/// Encoding error.
|
||||||
|
#[display(fmt = "Encoding error.")]
|
||||||
|
Encoding,
|
||||||
|
|
||||||
|
/// Serialize error.
|
||||||
|
#[display(fmt = "Serialize error: {}.", _0)]
|
||||||
|
Serialize(FormError),
|
||||||
|
|
||||||
/// Payload error.
|
/// Payload error.
|
||||||
#[display(fmt = "Error that occur during reading payload: {}.", _0)]
|
#[display(fmt = "Error that occur during reading payload: {}.", _0)]
|
||||||
Payload(PayloadError),
|
Payload(PayloadError),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `UrlencodedError`
|
|
||||||
impl ResponseError for UrlencodedError {
|
impl ResponseError for UrlencodedError {
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
match *self {
|
match self {
|
||||||
UrlencodedError::Overflow { .. } => StatusCode::PAYLOAD_TOO_LARGE,
|
Self::Overflow { .. } => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
UrlencodedError::UnknownLength => StatusCode::LENGTH_REQUIRED,
|
Self::UnknownLength => StatusCode::LENGTH_REQUIRED,
|
||||||
|
Self::Payload(err) => err.status_code(),
|
||||||
_ => StatusCode::BAD_REQUEST,
|
_ => StatusCode::BAD_REQUEST,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A set of errors that can occur during parsing json payloads
|
/// A set of errors that can occur during parsing json payloads
|
||||||
#[derive(Debug, Display, From)]
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum JsonPayloadError {
|
pub enum JsonPayloadError {
|
||||||
/// Payload size is bigger than allowed. (default: 32kB)
|
/// Payload size is bigger than allowed. (default: 32kB)
|
||||||
#[display(fmt = "Json payload size is bigger than allowed")]
|
#[display(fmt = "Json payload size is bigger than allowed")]
|
||||||
Overflow,
|
Overflow,
|
||||||
|
|
||||||
/// Content type error
|
/// Content type error
|
||||||
#[display(fmt = "Content type error")]
|
#[display(fmt = "Content type error")]
|
||||||
ContentType,
|
ContentType,
|
||||||
|
|
||||||
/// Deserialize error
|
/// Deserialize error
|
||||||
#[display(fmt = "Json deserialize error: {}", _0)]
|
#[display(fmt = "Json deserialize error: {}", _0)]
|
||||||
Deserialize(JsonError),
|
Deserialize(JsonError),
|
||||||
|
|
||||||
|
/// Serialize error
|
||||||
|
#[display(fmt = "Json serialize error: {}", _0)]
|
||||||
|
Serialize(JsonError),
|
||||||
|
|
||||||
/// Payload error
|
/// Payload error
|
||||||
#[display(fmt = "Error that occur during reading payload: {}", _0)]
|
#[display(fmt = "Error that occur during reading payload: {}", _0)]
|
||||||
Payload(PayloadError),
|
Payload(PayloadError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for JsonPayloadError {}
|
impl From<PayloadError> for JsonPayloadError {
|
||||||
|
fn from(err: PayloadError) -> Self {
|
||||||
|
Self::Payload(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `JsonPayloadError`
|
|
||||||
impl ResponseError for JsonPayloadError {
|
impl ResponseError for JsonPayloadError {
|
||||||
fn error_response(&self) -> HttpResponse {
|
fn status_code(&self) -> StatusCode {
|
||||||
match *self {
|
match self {
|
||||||
JsonPayloadError::Overflow => HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE),
|
Self::Overflow => StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
_ => HttpResponse::new(StatusCode::BAD_REQUEST),
|
Self::Serialize(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Self::Payload(err) => err.status_code(),
|
||||||
|
_ => StatusCode::BAD_REQUEST,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A set of errors that can occur during parsing request paths
|
/// A set of errors that can occur during parsing request paths
|
||||||
#[derive(Debug, Display, From)]
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum PathError {
|
pub enum PathError {
|
||||||
/// Deserialize error
|
/// Deserialize error
|
||||||
#[display(fmt = "Path deserialize error: {}", _0)]
|
#[display(fmt = "Path deserialize error: {}", _0)]
|
||||||
Deserialize(serde::de::value::Error),
|
Deserialize(serde::de::value::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for PathError {}
|
|
||||||
|
|
||||||
/// Return `BadRequest` for `PathError`
|
/// Return `BadRequest` for `PathError`
|
||||||
impl ResponseError for PathError {
|
impl ResponseError for PathError {
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
@ -119,13 +149,13 @@ impl ResponseError for PathError {
|
|||||||
|
|
||||||
/// A set of errors that can occur during parsing query strings.
|
/// A set of errors that can occur during parsing query strings.
|
||||||
#[derive(Debug, Display, Error, From)]
|
#[derive(Debug, Display, Error, From)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum QueryPayloadError {
|
pub enum QueryPayloadError {
|
||||||
/// Query deserialize error.
|
/// Query deserialize error.
|
||||||
#[display(fmt = "Query deserialize error: {}", _0)]
|
#[display(fmt = "Query deserialize error: {}", _0)]
|
||||||
Deserialize(serde::de::value::Error),
|
Deserialize(serde::de::value::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return `BadRequest` for `QueryPayloadError`
|
|
||||||
impl ResponseError for QueryPayloadError {
|
impl ResponseError for QueryPayloadError {
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
StatusCode::BAD_REQUEST
|
StatusCode::BAD_REQUEST
|
||||||
@ -133,26 +163,26 @@ impl ResponseError for QueryPayloadError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Error type returned when reading body as lines.
|
/// Error type returned when reading body as lines.
|
||||||
#[derive(From, Display, Debug)]
|
#[derive(Debug, Display, Error, From)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub enum ReadlinesError {
|
pub enum ReadlinesError {
|
||||||
/// Error when decoding a line.
|
|
||||||
#[display(fmt = "Encoding error")]
|
#[display(fmt = "Encoding error")]
|
||||||
/// Payload size is bigger than allowed. (default: 256kB)
|
/// Payload size is bigger than allowed. (default: 256kB)
|
||||||
EncodingError,
|
EncodingError,
|
||||||
|
|
||||||
/// Payload error.
|
/// Payload error.
|
||||||
#[display(fmt = "Error that occur during reading payload: {}", _0)]
|
#[display(fmt = "Error that occur during reading payload: {}", _0)]
|
||||||
Payload(PayloadError),
|
Payload(PayloadError),
|
||||||
|
|
||||||
/// Line limit exceeded.
|
/// Line limit exceeded.
|
||||||
#[display(fmt = "Line limit exceeded")]
|
#[display(fmt = "Line limit exceeded")]
|
||||||
LimitOverflow,
|
LimitOverflow,
|
||||||
|
|
||||||
/// ContentType error.
|
/// ContentType error.
|
||||||
#[display(fmt = "Content-type error")]
|
#[display(fmt = "Content-type error")]
|
||||||
ContentTypeError(ContentTypeError),
|
ContentTypeError(ContentTypeError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for ReadlinesError {}
|
|
||||||
|
|
||||||
/// Return `BadRequest` for `ReadlinesError`
|
|
||||||
impl ResponseError for ReadlinesError {
|
impl ResponseError for ReadlinesError {
|
||||||
fn status_code(&self) -> StatusCode {
|
fn status_code(&self) -> StatusCode {
|
||||||
match *self {
|
match *self {
|
||||||
@ -168,26 +198,25 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_urlencoded_error() {
|
fn test_urlencoded_error() {
|
||||||
let resp: HttpResponse =
|
let resp = UrlencodedError::Overflow { size: 0, limit: 0 }.error_response();
|
||||||
UrlencodedError::Overflow { size: 0, limit: 0 }.error_response();
|
|
||||||
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
let resp: HttpResponse = UrlencodedError::UnknownLength.error_response();
|
let resp = UrlencodedError::UnknownLength.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::LENGTH_REQUIRED);
|
assert_eq!(resp.status(), StatusCode::LENGTH_REQUIRED);
|
||||||
let resp: HttpResponse = UrlencodedError::ContentType.error_response();
|
let resp = UrlencodedError::ContentType.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_json_payload_error() {
|
fn test_json_payload_error() {
|
||||||
let resp: HttpResponse = JsonPayloadError::Overflow.error_response();
|
let resp = JsonPayloadError::Overflow.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
let resp: HttpResponse = JsonPayloadError::ContentType.error_response();
|
let resp = JsonPayloadError::ContentType.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_query_payload_error() {
|
fn test_query_payload_error() {
|
||||||
let resp: HttpResponse = QueryPayloadError::Deserialize(
|
let resp = QueryPayloadError::Deserialize(
|
||||||
serde_urlencoded::from_str::<i32>("bad query").unwrap_err(),
|
serde_urlencoded::from_str::<i32>("bad query").unwrap_err(),
|
||||||
)
|
)
|
||||||
.error_response();
|
.error_response();
|
||||||
@ -196,9 +225,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_readlines_error() {
|
fn test_readlines_error() {
|
||||||
let resp: HttpResponse = ReadlinesError::LimitOverflow.error_response();
|
let resp = ReadlinesError::LimitOverflow.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
let resp: HttpResponse = ReadlinesError::EncodingError.error_response();
|
let resp = ReadlinesError::EncodingError.error_response();
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -26,6 +26,8 @@
|
|||||||
//! ```
|
//! ```
|
||||||
#![allow(non_snake_case)]
|
#![allow(non_snake_case)]
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::http::{self, header, uri::Uri};
|
use actix_http::http::{self, header, uri::Uri};
|
||||||
use actix_http::RequestHead;
|
use actix_http::RequestHead;
|
||||||
@ -40,6 +42,12 @@ pub trait Guard {
|
|||||||
fn check(&self, request: &RequestHead) -> bool;
|
fn check(&self, request: &RequestHead) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Guard for Rc<dyn Guard> {
|
||||||
|
fn check(&self, request: &RequestHead) -> bool {
|
||||||
|
self.deref().check(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Create guard object for supplied function.
|
/// Create guard object for supplied function.
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -3,20 +3,23 @@ use std::marker::PhantomData;
|
|||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
use actix_http::{Error, Response};
|
use actix_http::Error;
|
||||||
use actix_service::{Service, ServiceFactory};
|
use actix_service::{Service, ServiceFactory};
|
||||||
use actix_utils::future::{ready, Ready};
|
use actix_utils::future::{ready, Ready};
|
||||||
use futures_core::ready;
|
use futures_core::ready;
|
||||||
use pin_project::pin_project;
|
use pin_project::pin_project;
|
||||||
|
|
||||||
use crate::extract::FromRequest;
|
use crate::{
|
||||||
use crate::request::HttpRequest;
|
extract::FromRequest,
|
||||||
use crate::responder::Responder;
|
request::HttpRequest,
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
responder::Responder,
|
||||||
|
response::HttpResponse,
|
||||||
|
service::{ServiceRequest, ServiceResponse},
|
||||||
|
};
|
||||||
|
|
||||||
/// A request handler is an async function that accepts zero or more parameters that can be
|
/// A request handler is an async function that accepts zero or more parameters that can be
|
||||||
/// extracted from a request (ie, [`impl FromRequest`](crate::FromRequest)) and returns a type that can be converted into
|
/// extracted from a request (i.e., [`impl FromRequest`](crate::FromRequest)) and returns a type
|
||||||
/// an [`HttpResponse`](crate::HttpResponse) (ie, [`impl Responder`](crate::Responder)).
|
/// that can be converted into an [`HttpResponse`] (that is, it impls the [`Responder`] trait).
|
||||||
///
|
///
|
||||||
/// If you got the error `the trait Handler<_, _, _> is not implemented`, then your function is not
|
/// If you got the error `the trait Handler<_, _, _> is not implemented`, then your function is not
|
||||||
/// a valid handler. See [Request Handlers](https://actix.rs/docs/handlers/) for more information.
|
/// a valid handler. See [Request Handlers](https://actix.rs/docs/handlers/) for more information.
|
||||||
@ -102,9 +105,7 @@ where
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = HandlerServiceFuture<F, T, R>;
|
type Future = HandlerServiceFuture<F, T, R>;
|
||||||
|
|
||||||
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
actix_service::always_ready!();
|
||||||
Poll::Ready(Ok(()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||||
let (req, mut payload) = req.into_parts();
|
let (req, mut payload) = req.into_parts();
|
||||||
@ -147,9 +148,9 @@ where
|
|||||||
let state = HandlerServiceFuture::Handle(fut, req.take());
|
let state = HandlerServiceFuture::Handle(fut, req.take());
|
||||||
self.as_mut().set(state);
|
self.as_mut().set(state);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(err) => {
|
||||||
let res: Response = e.into().into();
|
|
||||||
let req = req.take().unwrap();
|
let req = req.take().unwrap();
|
||||||
|
let res = HttpResponse::from_error(err.into());
|
||||||
return Poll::Ready(Ok(ServiceResponse::new(req, res)));
|
return Poll::Ready(Ok(ServiceResponse::new(req, res)));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -5,7 +5,7 @@ use mime::Mime;
|
|||||||
use super::{qitem, QualityItem};
|
use super::{qitem, QualityItem};
|
||||||
use crate::http::header;
|
use crate::http::header;
|
||||||
|
|
||||||
crate::header! {
|
crate::__define_common_header! {
|
||||||
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
|
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
|
||||||
///
|
///
|
||||||
/// The `Accept` header field can be used by user agents to specify
|
/// The `Accept` header field can be used by user agents to specify
|
||||||
@ -81,14 +81,14 @@ crate::header! {
|
|||||||
|
|
||||||
test_accept {
|
test_accept {
|
||||||
// Tests from the RFC
|
// Tests from the RFC
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test1,
|
test1,
|
||||||
vec![b"audio/*; q=0.2, audio/basic"],
|
vec![b"audio/*; q=0.2, audio/basic"],
|
||||||
Some(Accept(vec![
|
Some(Accept(vec![
|
||||||
QualityItem::new("audio/*".parse().unwrap(), q(200)),
|
QualityItem::new("audio/*".parse().unwrap(), q(200)),
|
||||||
qitem("audio/basic".parse().unwrap()),
|
qitem("audio/basic".parse().unwrap()),
|
||||||
])));
|
])));
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test2,
|
test2,
|
||||||
vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"],
|
vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"],
|
||||||
Some(Accept(vec![
|
Some(Accept(vec![
|
||||||
@ -100,13 +100,13 @@ crate::header! {
|
|||||||
qitem("text/x-c".parse().unwrap()),
|
qitem("text/x-c".parse().unwrap()),
|
||||||
])));
|
])));
|
||||||
// Custom tests
|
// Custom tests
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test3,
|
test3,
|
||||||
vec![b"text/plain; charset=utf-8"],
|
vec![b"text/plain; charset=utf-8"],
|
||||||
Some(Accept(vec![
|
Some(Accept(vec![
|
||||||
qitem(mime::TEXT_PLAIN_UTF_8),
|
qitem(mime::TEXT_PLAIN_UTF_8),
|
||||||
])));
|
])));
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test4,
|
test4,
|
||||||
vec![b"text/plain; charset=utf-8; q=0.5"],
|
vec![b"text/plain; charset=utf-8; q=0.5"],
|
||||||
Some(Accept(vec![
|
Some(Accept(vec![
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
use super::{Charset, QualityItem, ACCEPT_CHARSET};
|
use super::{Charset, QualityItem, ACCEPT_CHARSET};
|
||||||
|
|
||||||
crate::header! {
|
crate::__define_common_header! {
|
||||||
/// `Accept-Charset` header, defined in
|
/// `Accept-Charset` header, defined in
|
||||||
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3)
|
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3)
|
||||||
///
|
///
|
||||||
@ -57,6 +57,6 @@ crate::header! {
|
|||||||
|
|
||||||
test_accept_charset {
|
test_accept_charset {
|
||||||
// Test case from RFC
|
// Test case from RFC
|
||||||
test_header!(test1, vec![b"iso-8859-5, unicode-1-1;q=0.8"]);
|
crate::__common_header_test!(test1, vec![b"iso-8859-5, unicode-1-1;q=0.8"]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -64,12 +64,12 @@ header! {
|
|||||||
|
|
||||||
test_accept_encoding {
|
test_accept_encoding {
|
||||||
// From the RFC
|
// From the RFC
|
||||||
test_header!(test1, vec![b"compress, gzip"]);
|
crate::__common_header_test!(test1, vec![b"compress, gzip"]);
|
||||||
test_header!(test2, vec![b""], Some(AcceptEncoding(vec![])));
|
crate::__common_header_test!(test2, vec![b""], Some(AcceptEncoding(vec![])));
|
||||||
test_header!(test3, vec![b"*"]);
|
crate::__common_header_test!(test3, vec![b"*"]);
|
||||||
// Note: Removed quality 1 from gzip
|
// Note: Removed quality 1 from gzip
|
||||||
test_header!(test4, vec![b"compress;q=0.5, gzip"]);
|
crate::__common_header_test!(test4, vec![b"compress;q=0.5, gzip"]);
|
||||||
// Note: Removed quality 1 from gzip
|
// Note: Removed quality 1 from gzip
|
||||||
test_header!(test5, vec![b"gzip, identity; q=0.5, *;q=0"]);
|
crate::__common_header_test!(test5, vec![b"gzip, identity; q=0.5, *;q=0"]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
use super::{QualityItem, ACCEPT_LANGUAGE};
|
|
||||||
use language_tags::LanguageTag;
|
use language_tags::LanguageTag;
|
||||||
|
|
||||||
crate::header! {
|
use super::{QualityItem, ACCEPT_LANGUAGE};
|
||||||
|
|
||||||
|
crate::__define_common_header! {
|
||||||
/// `Accept-Language` header, defined in
|
/// `Accept-Language` header, defined in
|
||||||
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
|
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
|
||||||
///
|
///
|
||||||
@ -23,14 +24,11 @@ crate::header! {
|
|||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, qitem};
|
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// let mut langtag: LanguageTag = Default::default();
|
/// let langtag = LanguageTag::parse("en-US").unwrap();
|
||||||
/// langtag.language = Some("en".to_owned());
|
|
||||||
/// langtag.region = Some("US".to_owned());
|
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// AcceptLanguage(vec![
|
/// AcceptLanguage(vec![
|
||||||
/// qitem(langtag),
|
/// qitem(langtag),
|
||||||
@ -39,16 +37,15 @@ crate::header! {
|
|||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{AcceptLanguage, QualityItem, q, qitem};
|
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, QualityItem, q, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// AcceptLanguage(vec![
|
/// AcceptLanguage(vec![
|
||||||
/// qitem(langtag!(da)),
|
/// qitem(LanguageTag::parse("da").unwrap()),
|
||||||
/// QualityItem::new(langtag!(en;;;GB), q(800)),
|
/// QualityItem::new(LanguageTag::parse("en-GB").unwrap(), q(800)),
|
||||||
/// QualityItem::new(langtag!(en), q(700)),
|
/// QualityItem::new(LanguageTag::parse("en").unwrap(), q(700)),
|
||||||
/// ])
|
/// ])
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
@ -56,9 +53,9 @@ crate::header! {
|
|||||||
|
|
||||||
test_accept_language {
|
test_accept_language {
|
||||||
// From the RFC
|
// From the RFC
|
||||||
test_header!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]);
|
crate::__common_header_test!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]);
|
||||||
// Own test
|
// Own test
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test2, vec![b"en-US, en; q=0.5, fr"],
|
test2, vec![b"en-US, en; q=0.5, fr"],
|
||||||
Some(AcceptLanguage(vec![
|
Some(AcceptLanguage(vec![
|
||||||
qitem("en-US".parse().unwrap()),
|
qitem("en-US".parse().unwrap()),
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use actix_http::http::Method;
|
|
||||||
use crate::http::header;
|
use crate::http::header;
|
||||||
|
use actix_http::http::Method;
|
||||||
|
|
||||||
crate::header! {
|
crate::__define_common_header! {
|
||||||
/// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)
|
/// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)
|
||||||
///
|
///
|
||||||
/// The `Allow` header field lists the set of methods advertised as
|
/// The `Allow` header field lists the set of methods advertised as
|
||||||
@ -49,12 +49,12 @@ crate::header! {
|
|||||||
|
|
||||||
test_allow {
|
test_allow {
|
||||||
// From the RFC
|
// From the RFC
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test1,
|
test1,
|
||||||
vec![b"GET, HEAD, PUT"],
|
vec![b"GET, HEAD, PUT"],
|
||||||
Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT])));
|
Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT])));
|
||||||
// Own tests
|
// Own tests
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test2,
|
test2,
|
||||||
vec![b"OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH"],
|
vec![b"OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH"],
|
||||||
Some(HeaderField(vec![
|
Some(HeaderField(vec![
|
||||||
@ -67,7 +67,7 @@ crate::header! {
|
|||||||
Method::TRACE,
|
Method::TRACE,
|
||||||
Method::CONNECT,
|
Method::CONNECT,
|
||||||
Method::PATCH])));
|
Method::PATCH])));
|
||||||
test_header!(
|
crate::__common_header_test!(
|
||||||
test3,
|
test3,
|
||||||
vec![b""],
|
vec![b""],
|
||||||
Some(HeaderField(Vec::<Method>::new())));
|
Some(HeaderField(Vec::<Method>::new())));
|
||||||
|
@ -1,9 +1,7 @@
|
|||||||
use std::fmt::{self, Write};
|
use std::fmt::{self, Write};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use super::{
|
use super::{fmt_comma_delimited, from_comma_delimited, Header, IntoHeaderValue, Writer};
|
||||||
fmt_comma_delimited, from_comma_delimited, Header, IntoHeaderValue, Writer,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::http::header;
|
use crate::http::header;
|
||||||
|
|
||||||
@ -51,9 +49,9 @@ use crate::http::header;
|
|||||||
#[derive(PartialEq, Clone, Debug)]
|
#[derive(PartialEq, Clone, Debug)]
|
||||||
pub struct CacheControl(pub Vec<CacheDirective>);
|
pub struct CacheControl(pub Vec<CacheDirective>);
|
||||||
|
|
||||||
__hyper__deref!(CacheControl => Vec<CacheDirective>);
|
crate::__common_header_deref!(CacheControl => Vec<CacheDirective>);
|
||||||
|
|
||||||
//TODO: this could just be the header! macro
|
// TODO: this could just be the __define_common_header! macro
|
||||||
impl Header for CacheControl {
|
impl Header for CacheControl {
|
||||||
fn name() -> header::HeaderName {
|
fn name() -> header::HeaderName {
|
||||||
header::CACHE_CONTROL
|
header::CACHE_CONTROL
|
||||||
@ -75,7 +73,7 @@ impl Header for CacheControl {
|
|||||||
|
|
||||||
impl fmt::Display for CacheControl {
|
impl fmt::Display for CacheControl {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
fmt_comma_delimited(f, &self[..])
|
fmt_comma_delimited(f, &self.0[..])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -176,9 +174,7 @@ impl FromStr for CacheDirective {
|
|||||||
("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
|
("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
|
||||||
("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
|
("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
|
||||||
("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
|
("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
|
||||||
(left, right) => {
|
(left, right) => Ok(Extension(left.to_owned(), Some(right.to_owned()))),
|
||||||
Ok(Extension(left.to_owned(), Some(right.to_owned())))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(_) => Err(None),
|
Some(_) => Err(None),
|
||||||
|
@ -10,8 +10,8 @@ use once_cell::sync::Lazy;
|
|||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use std::fmt::{self, Write};
|
use std::fmt::{self, Write};
|
||||||
|
|
||||||
use crate::http::header;
|
|
||||||
use super::{ExtendedValue, Header, IntoHeaderValue, Writer};
|
use super::{ExtendedValue, Header, IntoHeaderValue, Writer};
|
||||||
|
use crate::http::header;
|
||||||
|
|
||||||
/// Split at the index of the first `needle` if it exists or at the end.
|
/// Split at the index of the first `needle` if it exists or at the end.
|
||||||
fn split_once(haystack: &str, needle: char) -> (&str, &str) {
|
fn split_once(haystack: &str, needle: char) -> (&str, &str) {
|
||||||
@ -401,15 +401,11 @@ impl ContentDisposition {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if it is [`Ext`](DispositionType::Ext) and the `disp_type` matches.
|
/// Returns `true` if it is [`Ext`](DispositionType::Ext) and the `disp_type` matches.
|
||||||
pub fn is_ext<T: AsRef<str>>(&self, disp_type: T) -> bool {
|
pub fn is_ext(&self, disp_type: impl AsRef<str>) -> bool {
|
||||||
match self.disposition {
|
matches!(
|
||||||
DispositionType::Ext(ref t)
|
self.disposition,
|
||||||
if t.eq_ignore_ascii_case(disp_type.as_ref()) =>
|
DispositionType::Ext(ref t) if t.eq_ignore_ascii_case(disp_type.as_ref())
|
||||||
{
|
)
|
||||||
true
|
|
||||||
}
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return the value of *name* if exists.
|
/// Return the value of *name* if exists.
|
||||||
@ -434,7 +430,7 @@ impl ContentDisposition {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the value of the parameter which the `name` matches.
|
/// Return the value of the parameter which the `name` matches.
|
||||||
pub fn get_unknown<T: AsRef<str>>(&self, name: T) -> Option<&str> {
|
pub fn get_unknown(&self, name: impl AsRef<str>) -> Option<&str> {
|
||||||
let name = name.as_ref();
|
let name = name.as_ref();
|
||||||
self.parameters
|
self.parameters
|
||||||
.iter()
|
.iter()
|
||||||
@ -443,7 +439,7 @@ impl ContentDisposition {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Return the value of the extended parameter which the `name` matches.
|
/// Return the value of the extended parameter which the `name` matches.
|
||||||
pub fn get_unknown_ext<T: AsRef<str>>(&self, name: T) -> Option<&ExtendedValue> {
|
pub fn get_unknown_ext(&self, name: impl AsRef<str>) -> Option<&ExtendedValue> {
|
||||||
let name = name.as_ref();
|
let name = name.as_ref();
|
||||||
self.parameters
|
self.parameters
|
||||||
.iter()
|
.iter()
|
||||||
@ -521,7 +517,8 @@ impl fmt::Display for DispositionParam {
|
|||||||
//
|
//
|
||||||
//
|
//
|
||||||
// See also comments in test_from_raw_unnecessary_percent_decode.
|
// See also comments in test_from_raw_unnecessary_percent_decode.
|
||||||
static RE: Lazy<Regex> = Lazy::new(|| Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").unwrap());
|
static RE: Lazy<Regex> =
|
||||||
|
Lazy::new(|| Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").unwrap());
|
||||||
match self {
|
match self {
|
||||||
DispositionParam::Name(ref value) => write!(f, "name={}", value),
|
DispositionParam::Name(ref value) => write!(f, "name={}", value),
|
||||||
DispositionParam::Filename(ref value) => {
|
DispositionParam::Filename(ref value) => {
|
||||||
@ -555,8 +552,7 @@ impl fmt::Display for ContentDisposition {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{ContentDisposition, DispositionParam, DispositionType};
|
use super::{ContentDisposition, DispositionParam, DispositionType};
|
||||||
use crate::http::header::Charset;
|
use crate::http::header::{Charset, ExtendedValue, HeaderValue};
|
||||||
use crate::http::header::{ExtendedValue, HeaderValue};
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_from_raw_basic() {
|
fn test_from_raw_basic() {
|
||||||
@ -618,8 +614,8 @@ mod tests {
|
|||||||
charset: Charset::Ext(String::from("UTF-8")),
|
charset: Charset::Ext(String::from("UTF-8")),
|
||||||
language_tag: None,
|
language_tag: None,
|
||||||
value: vec![
|
value: vec![
|
||||||
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20,
|
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r',
|
||||||
b'r', b'a', b't', b'e', b's',
|
b'a', b't', b'e', b's',
|
||||||
],
|
],
|
||||||
})],
|
})],
|
||||||
};
|
};
|
||||||
@ -635,8 +631,8 @@ mod tests {
|
|||||||
charset: Charset::Ext(String::from("UTF-8")),
|
charset: Charset::Ext(String::from("UTF-8")),
|
||||||
language_tag: None,
|
language_tag: None,
|
||||||
value: vec![
|
value: vec![
|
||||||
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20,
|
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r',
|
||||||
b'r', b'a', b't', b'e', b's',
|
b'a', b't', b'e', b's',
|
||||||
],
|
],
|
||||||
})],
|
})],
|
||||||
};
|
};
|
||||||
@ -698,26 +694,22 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_from_raw_only_disp() {
|
fn test_from_raw_only_disp() {
|
||||||
let a = ContentDisposition::from_raw(&HeaderValue::from_static("attachment"))
|
let a = ContentDisposition::from_raw(&HeaderValue::from_static("attachment")).unwrap();
|
||||||
.unwrap();
|
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::Attachment,
|
disposition: DispositionType::Attachment,
|
||||||
parameters: vec![],
|
parameters: vec![],
|
||||||
};
|
};
|
||||||
assert_eq!(a, b);
|
assert_eq!(a, b);
|
||||||
|
|
||||||
let a =
|
let a = ContentDisposition::from_raw(&HeaderValue::from_static("inline ;")).unwrap();
|
||||||
ContentDisposition::from_raw(&HeaderValue::from_static("inline ;")).unwrap();
|
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::Inline,
|
disposition: DispositionType::Inline,
|
||||||
parameters: vec![],
|
parameters: vec![],
|
||||||
};
|
};
|
||||||
assert_eq!(a, b);
|
assert_eq!(a, b);
|
||||||
|
|
||||||
let a = ContentDisposition::from_raw(&HeaderValue::from_static(
|
let a = ContentDisposition::from_raw(&HeaderValue::from_static("unknown-disp-param"))
|
||||||
"unknown-disp-param",
|
.unwrap();
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::Ext(String::from("unknown-disp-param")),
|
disposition: DispositionType::Ext(String::from("unknown-disp-param")),
|
||||||
parameters: vec![],
|
parameters: vec![],
|
||||||
@ -756,8 +748,8 @@ mod tests {
|
|||||||
Mainstream browsers like Firefox (gecko) and Chrome use UTF-8 directly as above.
|
Mainstream browsers like Firefox (gecko) and Chrome use UTF-8 directly as above.
|
||||||
(And now, only UTF-8 is handled by this implementation.)
|
(And now, only UTF-8 is handled by this implementation.)
|
||||||
*/
|
*/
|
||||||
let a = HeaderValue::from_str("form-data; name=upload; filename=\"文件.webp\"")
|
let a =
|
||||||
.unwrap();
|
HeaderValue::from_str("form-data; name=upload; filename=\"文件.webp\"").unwrap();
|
||||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::FormData,
|
disposition: DispositionType::FormData,
|
||||||
@ -808,8 +800,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_from_raw_semicolon() {
|
fn test_from_raw_semicolon() {
|
||||||
let a =
|
let a = HeaderValue::from_static("form-data; filename=\"A semicolon here;.pdf\"");
|
||||||
HeaderValue::from_static("form-data; filename=\"A semicolon here;.pdf\"");
|
|
||||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::FormData,
|
disposition: DispositionType::FormData,
|
||||||
@ -845,9 +836,8 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert_eq!(a, b);
|
assert_eq!(a, b);
|
||||||
|
|
||||||
let a = HeaderValue::from_static(
|
let a =
|
||||||
"form-data; name=photo; filename=\"%74%65%73%74.png\"",
|
HeaderValue::from_static("form-data; name=photo; filename=\"%74%65%73%74.png\"");
|
||||||
);
|
|
||||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::FormData,
|
disposition: DispositionType::FormData,
|
||||||
@ -892,8 +882,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_display_extended() {
|
fn test_display_extended() {
|
||||||
let as_string =
|
let as_string = "attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
|
||||||
"attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
|
|
||||||
let a = HeaderValue::from_static(as_string);
|
let a = HeaderValue::from_static(as_string);
|
||||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||||
let display_rendered = format!("{}", a);
|
let display_rendered = format!("{}", a);
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use super::{QualityItem, CONTENT_LANGUAGE};
|
use super::{QualityItem, CONTENT_LANGUAGE};
|
||||||
use language_tags::LanguageTag;
|
use language_tags::LanguageTag;
|
||||||
|
|
||||||
crate::header! {
|
crate::__define_common_header! {
|
||||||
/// `Content-Language` header, defined in
|
/// `Content-Language` header, defined in
|
||||||
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
|
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
|
||||||
///
|
///
|
||||||
@ -24,35 +24,33 @@ crate::header! {
|
|||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{ContentLanguage, qitem};
|
/// use actix_web::http::header::{ContentLanguage, LanguageTag, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// ContentLanguage(vec![
|
/// ContentLanguage(vec![
|
||||||
/// qitem(langtag!(en)),
|
/// qitem(LanguageTag::parse("en").unwrap()),
|
||||||
/// ])
|
/// ])
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use language_tags::langtag;
|
|
||||||
/// use actix_web::HttpResponse;
|
/// use actix_web::HttpResponse;
|
||||||
/// use actix_web::http::header::{ContentLanguage, qitem};
|
/// use actix_web::http::header::{ContentLanguage, LanguageTag, qitem};
|
||||||
///
|
///
|
||||||
/// let mut builder = HttpResponse::Ok();
|
/// let mut builder = HttpResponse::Ok();
|
||||||
/// builder.insert_header(
|
/// builder.insert_header(
|
||||||
/// ContentLanguage(vec![
|
/// ContentLanguage(vec![
|
||||||
/// qitem(langtag!(da)),
|
/// qitem(LanguageTag::parse("da").unwrap()),
|
||||||
/// qitem(langtag!(en;;;GB)),
|
/// qitem(LanguageTag::parse("en-GB").unwrap()),
|
||||||
/// ])
|
/// ])
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
(ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+
|
(ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+
|
||||||
|
|
||||||
test_content_language {
|
test_content_language {
|
||||||
test_header!(test1, vec![b"da"]);
|
crate::__common_header_test!(test1, vec![b"da"]);
|
||||||
test_header!(test2, vec![b"mi, en"]);
|
crate::__common_header_test!(test2, vec![b"mi, en"]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,70 +1,68 @@
|
|||||||
use std::fmt::{self, Display, Write};
|
use std::fmt::{self, Display, Write};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use super::{HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE};
|
||||||
use crate::error::ParseError;
|
use crate::error::ParseError;
|
||||||
use super::{
|
|
||||||
HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE,
|
|
||||||
};
|
|
||||||
|
|
||||||
crate::header! {
|
crate::__define_common_header! {
|
||||||
/// `Content-Range` header, defined in
|
/// `Content-Range` header, defined in
|
||||||
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2)
|
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2)
|
||||||
(ContentRange, CONTENT_RANGE) => [ContentRangeSpec]
|
(ContentRange, CONTENT_RANGE) => [ContentRangeSpec]
|
||||||
|
|
||||||
test_content_range {
|
test_content_range {
|
||||||
test_header!(test_bytes,
|
crate::__common_header_test!(test_bytes,
|
||||||
vec![b"bytes 0-499/500"],
|
vec![b"bytes 0-499/500"],
|
||||||
Some(ContentRange(ContentRangeSpec::Bytes {
|
Some(ContentRange(ContentRangeSpec::Bytes {
|
||||||
range: Some((0, 499)),
|
range: Some((0, 499)),
|
||||||
instance_length: Some(500)
|
instance_length: Some(500)
|
||||||
})));
|
})));
|
||||||
|
|
||||||
test_header!(test_bytes_unknown_len,
|
crate::__common_header_test!(test_bytes_unknown_len,
|
||||||
vec![b"bytes 0-499/*"],
|
vec![b"bytes 0-499/*"],
|
||||||
Some(ContentRange(ContentRangeSpec::Bytes {
|
Some(ContentRange(ContentRangeSpec::Bytes {
|
||||||
range: Some((0, 499)),
|
range: Some((0, 499)),
|
||||||
instance_length: None
|
instance_length: None
|
||||||
})));
|
})));
|
||||||
|
|
||||||
test_header!(test_bytes_unknown_range,
|
crate::__common_header_test!(test_bytes_unknown_range,
|
||||||
vec![b"bytes */500"],
|
vec![b"bytes */500"],
|
||||||
Some(ContentRange(ContentRangeSpec::Bytes {
|
Some(ContentRange(ContentRangeSpec::Bytes {
|
||||||
range: None,
|
range: None,
|
||||||
instance_length: Some(500)
|
instance_length: Some(500)
|
||||||
})));
|
})));
|
||||||
|
|
||||||
test_header!(test_unregistered,
|
crate::__common_header_test!(test_unregistered,
|
||||||
vec![b"seconds 1-2"],
|
vec![b"seconds 1-2"],
|
||||||
Some(ContentRange(ContentRangeSpec::Unregistered {
|
Some(ContentRange(ContentRangeSpec::Unregistered {
|
||||||
unit: "seconds".to_owned(),
|
unit: "seconds".to_owned(),
|
||||||
resp: "1-2".to_owned()
|
resp: "1-2".to_owned()
|
||||||
})));
|
})));
|
||||||
|
|
||||||
test_header!(test_no_len,
|
crate::__common_header_test!(test_no_len,
|
||||||
vec![b"bytes 0-499"],
|
vec![b"bytes 0-499"],
|
||||||
None::<ContentRange>);
|
None::<ContentRange>);
|
||||||
|
|
||||||
test_header!(test_only_unit,
|
crate::__common_header_test!(test_only_unit,
|
||||||
vec![b"bytes"],
|
vec![b"bytes"],
|
||||||
None::<ContentRange>);
|
None::<ContentRange>);
|
||||||
|
|
||||||
test_header!(test_end_less_than_start,
|
crate::__common_header_test!(test_end_less_than_start,
|
||||||
vec![b"bytes 499-0/500"],
|
vec![b"bytes 499-0/500"],
|
||||||
None::<ContentRange>);
|
None::<ContentRange>);
|
||||||
|
|
||||||
test_header!(test_blank,
|
crate::__common_header_test!(test_blank,
|
||||||
vec![b""],
|
vec![b""],
|
||||||
None::<ContentRange>);
|
None::<ContentRange>);
|
||||||
|
|
||||||
test_header!(test_bytes_many_spaces,
|
crate::__common_header_test!(test_bytes_many_spaces,
|
||||||
vec![b"bytes 1-2/500 3"],
|
vec![b"bytes 1-2/500 3"],
|
||||||
None::<ContentRange>);
|
None::<ContentRange>);
|
||||||
|
|
||||||
test_header!(test_bytes_many_slashes,
|
crate::__common_header_test!(test_bytes_many_slashes,
|
||||||
vec![b"bytes 1-2/500/600"],
|
vec![b"bytes 1-2/500/600"],
|
||||||
None::<ContentRange>);
|
None::<ContentRange>);
|
||||||
|
|
||||||
test_header!(test_bytes_many_dashes,
|
crate::__common_header_test!(test_bytes_many_dashes,
|
||||||
vec![b"bytes 1-2-3/500"],
|
vec![b"bytes 1-2-3/500"],
|
||||||
None::<ContentRange>);
|
None::<ContentRange>);
|
||||||
|
|
||||||
@ -141,8 +139,7 @@ impl FromStr for ContentRangeSpec {
|
|||||||
} else {
|
} else {
|
||||||
let (first_byte, last_byte) =
|
let (first_byte, last_byte) =
|
||||||
split_in_two(range, '-').ok_or(ParseError::Header)?;
|
split_in_two(range, '-').ok_or(ParseError::Header)?;
|
||||||
let first_byte =
|
let first_byte = first_byte.parse().map_err(|_| ParseError::Header)?;
|
||||||
first_byte.parse().map_err(|_| ParseError::Header)?;
|
|
||||||
let last_byte = last_byte.parse().map_err(|_| ParseError::Header)?;
|
let last_byte = last_byte.parse().map_err(|_| ParseError::Header)?;
|
||||||
if last_byte < first_byte {
|
if last_byte < first_byte {
|
||||||
return Err(ParseError::Header);
|
return Err(ParseError::Header);
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user