mirror of
https://github.com/fafhrd91/actix-web
synced 2024-11-27 09:42:57 +01:00
Merge branch 'master' into origin/feature/awc-retry-middleware
This commit is contained in:
commit
58dfc3ba22
@ -1,3 +1,7 @@
|
||||
[alias]
|
||||
chk = "hack check --workspace --all-features --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
|
||||
with:
|
||||
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_reading_deflate_encoding_large_random_rustls
|
||||
|
||||
|
27
CHANGES.md
27
CHANGES.md
@ -1,6 +1,33 @@
|
||||
# Changes
|
||||
|
||||
## 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
|
||||
|
94
Cargo.toml
94
Cargo.toml
@ -1,26 +1,23 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "4.0.0-beta.5"
|
||||
version = "4.0.0-beta.6"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
|
||||
readme = "README.md"
|
||||
keywords = ["actix", "http", "web", "framework", "async"]
|
||||
categories = [
|
||||
"network-programming",
|
||||
"asynchronous",
|
||||
"web-programming::http-server",
|
||||
"web-programming::websocket"
|
||||
]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
documentation = "https://docs.rs/actix-web/"
|
||||
categories = ["network-programming", "asynchronous",
|
||||
"web-programming::http-server",
|
||||
"web-programming::websocket"]
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2018"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# features that docs.rs will build with
|
||||
features = ["openssl", "rustls", "compress", "secure-cookies"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||
codecov = { repository = "actix/actix-web", branch = "master", service = "github" }
|
||||
features = ["openssl", "rustls", "compress", "cookies", "secure-cookies"]
|
||||
|
||||
[lib]
|
||||
name = "actix_web"
|
||||
@ -28,16 +25,18 @@ path = "src/lib.rs"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
".",
|
||||
"awc",
|
||||
"actix-http",
|
||||
"actix-files",
|
||||
"actix-multipart",
|
||||
"actix-web-actors",
|
||||
"actix-web-codegen",
|
||||
"actix-http-test",
|
||||
"actix-test",
|
||||
".",
|
||||
"awc",
|
||||
"actix-http",
|
||||
"actix-files",
|
||||
"actix-multipart",
|
||||
"actix-web-actors",
|
||||
"actix-web-codegen",
|
||||
"actix-http-test",
|
||||
"actix-test",
|
||||
]
|
||||
# enable when MSRV is 1.51+
|
||||
# resolver = "2"
|
||||
|
||||
[features]
|
||||
default = ["compress", "cookies"]
|
||||
@ -46,10 +45,10 @@ default = ["compress", "cookies"]
|
||||
compress = ["actix-http/compress"]
|
||||
|
||||
# support for cookies
|
||||
cookies = ["actix-http/cookies"]
|
||||
cookies = ["cookie"]
|
||||
|
||||
# secure cookies feature
|
||||
secure-cookies = ["actix-http/secure-cookies"]
|
||||
secure-cookies = ["cookie/secure"]
|
||||
|
||||
# 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 = ["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]
|
||||
actix-codec = "0.4.0-beta.1"
|
||||
actix-codec = "0.4.0"
|
||||
actix-macros = "0.2.0"
|
||||
actix-router = "0.2.7"
|
||||
actix-rt = "2.2"
|
||||
actix-server = "2.0.0-beta.3"
|
||||
actix-service = "2.0.0-beta.4"
|
||||
actix-utils = "3.0.0-beta.4"
|
||||
actix-service = "2.0.0"
|
||||
actix-utils = "3.0.0"
|
||||
actix-tls = { version = "3.0.0-beta.5", default-features = false, optional = true }
|
||||
|
||||
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"
|
||||
bytes = "1"
|
||||
cookie = { version = "0.15", features = ["percent-encode"], optional = true }
|
||||
derive_more = "0.99.5"
|
||||
either = "1.5.3"
|
||||
encoding_rs = "0.8"
|
||||
futures-core = { 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"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
paste = "1"
|
||||
pin-project = "1.0.0"
|
||||
regex = "1.4"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
@ -108,8 +94,8 @@ time = { version = "0.2.23", default-features = false, features = ["std"] }
|
||||
url = "2.1"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-test = { version = "0.1.0-beta.1", features = ["openssl", "rustls"] }
|
||||
awc = { version = "3.0.0-beta.4", features = ["openssl"] }
|
||||
actix-test = { version = "0.1.0-beta.2", features = ["openssl", "rustls"] }
|
||||
awc = { version = "3.0.0-beta.5", features = ["openssl"] }
|
||||
|
||||
brotli2 = "0.3.2"
|
||||
criterion = "0.3"
|
||||
@ -137,6 +123,22 @@ actix-web-actors = { path = "actix-web-actors" }
|
||||
actix-web-codegen = { path = "actix-web-codegen" }
|
||||
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]]
|
||||
name = "server"
|
||||
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
|
||||
person obtaining a copy of this software and associated
|
||||
|
@ -31,7 +31,7 @@
|
||||
* Static assets
|
||||
* SSL support using OpenSSL or Rustls
|
||||
* 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+
|
||||
|
||||
## Documentation
|
||||
@ -90,7 +90,7 @@ You may consider checking out
|
||||
## Benchmarks
|
||||
|
||||
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
|
||||
|
||||
|
@ -1,11 +1,21 @@
|
||||
# Changes
|
||||
|
||||
## 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
|
||||
* 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
|
||||
* No notable changes.
|
||||
|
@ -17,9 +17,9 @@ name = "actix_files"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "4.0.0-beta.5", default-features = false }
|
||||
actix-service = "2.0.0-beta.4"
|
||||
actix-utils = "3.0.0-beta.4"
|
||||
actix-web = { version = "4.0.0-beta.6", default-features = false }
|
||||
actix-service = "2.0.0"
|
||||
actix-utils = "3.0.0"
|
||||
|
||||
askama_escape = "0.10"
|
||||
bitflags = "1"
|
||||
@ -34,5 +34,5 @@ percent-encoding = "2.1"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "2.2"
|
||||
actix-web = "4.0.0-beta.5"
|
||||
actix-test = "0.1.0-beta.1"
|
||||
actix-web = "4.0.0-beta.6"
|
||||
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;
|
||||
|
||||
/// Errors which can occur when serving static files.
|
||||
@ -16,8 +16,8 @@ pub enum FilesError {
|
||||
|
||||
/// Return `NotFound` for `FilesError`
|
||||
impl ResponseError for FilesError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
HttpResponse::new(StatusCode::NOT_FOUND)
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::NOT_FOUND
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -37,7 +37,8 @@ pub struct Files {
|
||||
renderer: Rc<DirectoryRenderer>,
|
||||
mime_override: Option<Rc<MimeOverride>>,
|
||||
file_flags: named::Flags,
|
||||
guards: Option<Rc<dyn Guard>>,
|
||||
use_guards: Option<Rc<dyn Guard>>,
|
||||
guards: Vec<Rc<dyn Guard>>,
|
||||
hidden_files: bool,
|
||||
}
|
||||
|
||||
@ -59,6 +60,7 @@ impl Clone for Files {
|
||||
file_flags: self.file_flags,
|
||||
path: self.path.clone(),
|
||||
mime_override: self.mime_override.clone(),
|
||||
use_guards: self.use_guards.clone(),
|
||||
guards: self.guards.clone(),
|
||||
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
|
||||
/// be inaccessible. Register more specific handlers and services first.
|
||||
///
|
||||
/// `Files` uses a threadpool for blocking filesystem operations. By default, the pool uses a
|
||||
/// max number of threads equal to `512 * HttpServer::worker`. Real time thread count are
|
||||
/// adjusted with work load. More threads would spawn when need and threads goes idle for a
|
||||
/// period of time would be de-spawned.
|
||||
/// `Files` utilizes the existing Tokio thread-pool for blocking filesystem operations.
|
||||
/// The number of running threads is adjusted over time as needed, up to a maximum of 512 times
|
||||
/// the number of server [workers](actix_web::HttpServer::workers), by default.
|
||||
pub fn new<T: Into<PathBuf>>(mount_path: &str, serve_from: T) -> Files {
|
||||
let orig_dir = serve_from.into();
|
||||
let dir = match orig_dir.canonicalize() {
|
||||
@ -104,7 +105,8 @@ impl Files {
|
||||
renderer: Rc::new(directory_listing),
|
||||
mime_override: None,
|
||||
file_flags: named::Flags::default(),
|
||||
guards: None,
|
||||
use_guards: None,
|
||||
guards: Vec::new(),
|
||||
hidden_files: false,
|
||||
}
|
||||
}
|
||||
@ -156,7 +158,6 @@ impl Files {
|
||||
/// Specifies whether to use ETag or not.
|
||||
///
|
||||
/// Default is true.
|
||||
#[inline]
|
||||
pub fn use_etag(mut self, value: bool) -> Self {
|
||||
self.file_flags.set(named::Flags::ETAG, value);
|
||||
self
|
||||
@ -165,7 +166,6 @@ impl Files {
|
||||
/// Specifies whether to use Last-Modified or not.
|
||||
///
|
||||
/// Default is true.
|
||||
#[inline]
|
||||
pub fn use_last_modified(mut self, value: bool) -> Self {
|
||||
self.file_flags.set(named::Flags::LAST_MD, value);
|
||||
self
|
||||
@ -174,31 +174,74 @@ impl Files {
|
||||
/// Specifies whether text responses should signal a UTF-8 encoding.
|
||||
///
|
||||
/// Default is false (but will default to true in a future version).
|
||||
#[inline]
|
||||
pub fn prefer_utf8(mut self, value: bool) -> Self {
|
||||
self.file_flags.set(named::Flags::PREFER_UTF8, value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies custom guards to use for directory listings and files.
|
||||
/// Adds a routing guard.
|
||||
///
|
||||
/// Default behaviour allows GET and HEAD.
|
||||
#[inline]
|
||||
pub fn use_guards<G: Guard + 'static>(mut self, guards: G) -> Self {
|
||||
self.guards = Some(Rc::new(guards));
|
||||
/// Use this to allow multiple chained file services that respond to strictly different
|
||||
/// properties of a request. Due to the way routing works, if a guard check returns true and the
|
||||
/// request starts being handled by the file service, it will not be able to back-out and try
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// By default Content-Disposition` header is enabled.
|
||||
#[inline]
|
||||
pub fn disable_content_disposition(mut self) -> Self {
|
||||
self.file_flags.remove(named::Flags::CONTENT_DISPOSITION);
|
||||
self
|
||||
}
|
||||
|
||||
/// 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
|
||||
where
|
||||
F: IntoServiceFactory<U, ServiceRequest>,
|
||||
@ -218,7 +261,6 @@ impl Files {
|
||||
}
|
||||
|
||||
/// Enables serving hidden files and directories, allowing a leading dots in url fragments.
|
||||
#[inline]
|
||||
pub fn use_hidden_files(mut self) -> Self {
|
||||
self.hidden_files = true;
|
||||
self
|
||||
@ -226,7 +268,19 @@ impl 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() {
|
||||
*self.default.borrow_mut() = Some(config.default_service());
|
||||
}
|
||||
@ -237,7 +291,7 @@ impl HttpServiceFactory for Files {
|
||||
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(),
|
||||
mime_override: self.mime_override.clone(),
|
||||
file_flags: self.file_flags,
|
||||
guards: self.guards.clone(),
|
||||
guards: self.use_guards.clone(),
|
||||
hidden_files: self.hidden_files,
|
||||
};
|
||||
|
||||
|
@ -532,7 +532,7 @@ mod tests {
|
||||
#[actix_rt::test]
|
||||
async fn test_files_guards() {
|
||||
let srv = test::init_service(
|
||||
App::new().service(Files::new("/", ".").use_guards(guard::Post())),
|
||||
App::new().service(Files::new("/", ".").method_guard(guard::Post())),
|
||||
)
|
||||
.await;
|
||||
|
||||
@ -632,7 +632,7 @@ mod tests {
|
||||
|
||||
#[actix_rt::test]
|
||||
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(
|
||||
App::new().service(Files::new("/", ".").redirect_to_slash_directory()),
|
||||
)
|
||||
@ -654,6 +654,19 @@ mod tests {
|
||||
let resp = test::call_service(&srv, req).await;
|
||||
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
|
||||
let req = TestRequest::with_uri("/not_existing").to_request();
|
||||
let resp = test::call_service(&srv, req).await;
|
||||
@ -754,4 +767,93 @@ mod tests {
|
||||
let res = test::call_service(&srv, req).await;
|
||||
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::io;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
@ -8,14 +11,14 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
use actix_web::{
|
||||
dev::{BodyEncoding, SizedStream},
|
||||
dev::{BodyEncoding, ServiceRequest, ServiceResponse, SizedStream},
|
||||
http::{
|
||||
header::{
|
||||
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
|
||||
},
|
||||
ContentEncoding, StatusCode,
|
||||
},
|
||||
HttpMessage, HttpRequest, HttpResponse, Responder,
|
||||
Error, HttpMessage, HttpRequest, HttpResponse, Responder,
|
||||
};
|
||||
use bitflags::bitflags;
|
||||
use mime_guess::from_path;
|
||||
@ -39,6 +42,29 @@ impl Default for Flags {
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
pub struct NamedFile {
|
||||
path: PathBuf,
|
||||
@ -480,3 +506,53 @@ impl Responder for NamedFile {
|
||||
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
|
||||
let path = match self.directory.join(&real_path).canonicalize() {
|
||||
Ok(path) => path,
|
||||
Err(err) => return Box::pin(self.handle_err(err, req)),
|
||||
};
|
||||
let path = self.directory.join(&real_path);
|
||||
if let Err(err) = path.canonicalize() {
|
||||
return Box::pin(self.handle_err(err, req));
|
||||
}
|
||||
|
||||
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 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);
|
||||
|
||||
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"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "2.0.0-beta.4"
|
||||
actix-codec = "0.4.0-beta.1"
|
||||
actix-service = "2.0.0"
|
||||
actix-codec = "0.4.0"
|
||||
actix-tls = "3.0.0-beta.5"
|
||||
actix-utils = "3.0.0-beta.4"
|
||||
actix-utils = "3.0.0"
|
||||
actix-rt = "2.2"
|
||||
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"
|
||||
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 }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "4.0.0-beta.5", default-features = false, features = ["cookies"] }
|
||||
actix-http = "3.0.0-beta.5"
|
||||
actix-web = { version = "4.0.0-beta.6", default-features = false, features = ["cookies"] }
|
||||
actix-http = "3.0.0-beta.6"
|
||||
|
@ -1,6 +1,72 @@
|
||||
# Changes
|
||||
|
||||
## 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
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "3.0.0-beta.5"
|
||||
version = "3.0.0-beta.6"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "HTTP primitives for the Actix ecosystem"
|
||||
readme = "README.md"
|
||||
@ -16,7 +16,7 @@ edition = "2018"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# features that docs.rs will build with
|
||||
features = ["openssl", "rustls", "compress", "cookies", "secure-cookies"]
|
||||
features = ["openssl", "rustls", "compress"]
|
||||
|
||||
[lib]
|
||||
name = "actix_http"
|
||||
@ -34,19 +34,13 @@ rustls = ["actix-tls/rustls"]
|
||||
# enable compression support
|
||||
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 = ["trust-dns-resolver"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "2.0.0-beta.4"
|
||||
actix-codec = "0.4.0-beta.1"
|
||||
actix-utils = "3.0.0-beta.4"
|
||||
actix-service = "2.0.0"
|
||||
actix-codec = "0.4.0"
|
||||
actix-utils = "3.0.0"
|
||||
actix-rt = "2.2"
|
||||
actix-tls = { version = "3.0.0-beta.5", features = ["accept", "connect"] }
|
||||
|
||||
@ -55,7 +49,6 @@ base64 = "0.13"
|
||||
bitflags = "1.2"
|
||||
bytes = "1"
|
||||
bytestring = "1"
|
||||
cookie = { version = "0.14.1", features = ["percent-encode"], optional = true }
|
||||
derive_more = "0.99.5"
|
||||
encoding_rs = "0.8"
|
||||
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||
@ -64,7 +57,7 @@ h2 = "0.3.1"
|
||||
http = "0.2.2"
|
||||
httparse = "1.3"
|
||||
itoa = "0.4"
|
||||
language-tags = "0.2"
|
||||
language-tags = "0.3"
|
||||
local-channel = "0.1"
|
||||
once_cell = "1.5"
|
||||
log = "0.4"
|
||||
@ -75,8 +68,6 @@ pin-project-lite = "0.2"
|
||||
rand = "0.8"
|
||||
regex = "1.3"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_urlencoded = "0.7"
|
||||
sha-1 = "0.9"
|
||||
smallvec = "1.6"
|
||||
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"
|
||||
env_logger = "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-rustls = { version = "0.19", package = "rustls" }
|
||||
|
||||
|
@ -3,11 +3,11 @@
|
||||
> HTTP primitives for the Actix ecosystem.
|
||||
|
||||
[![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)
|
||||
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http.svg)
|
||||
<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)
|
||||
[![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 bytes::BytesMut;
|
||||
use futures_util::StreamExt as _;
|
||||
@ -9,8 +9,7 @@ use log::info;
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
env::set_var("RUST_LOG", "echo=info");
|
||||
env_logger::init();
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
Server::build()
|
||||
.bind("echo", "127.0.0.1:8080", || {
|
||||
@ -25,7 +24,7 @@ async fn main() -> io::Result<()> {
|
||||
|
||||
info!("request body: {:?}", body);
|
||||
Ok::<_, Error>(
|
||||
Response::Ok()
|
||||
Response::build(StatusCode::OK)
|
||||
.insert_header((
|
||||
"x-head",
|
||||
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_server::Server;
|
||||
use bytes::BytesMut;
|
||||
use futures_util::StreamExt as _;
|
||||
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();
|
||||
while let Some(item) = req.payload().next().await {
|
||||
body.extend_from_slice(&item?)
|
||||
}
|
||||
|
||||
info!("request body: {:?}", body);
|
||||
Ok(Response::Ok()
|
||||
Ok(Response::build(StatusCode::OK)
|
||||
.insert_header(("x-head", HeaderValue::from_static("dummy value!")))
|
||||
.body(body))
|
||||
}
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
env::set_var("RUST_LOG", "echo=info");
|
||||
env_logger::init();
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
Server::build()
|
||||
.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_utils::future;
|
||||
use http::header::HeaderValue;
|
||||
@ -8,8 +8,7 @@ use log::info;
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
env::set_var("RUST_LOG", "hello_world=info");
|
||||
env_logger::init();
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
Server::build()
|
||||
.bind("hello-world", "127.0.0.1:8080", || {
|
||||
@ -18,7 +17,7 @@ async fn main() -> io::Result<()> {
|
||||
.client_disconnect(1000)
|
||||
.finish(|_req| {
|
||||
info!("{:?}", _req);
|
||||
let mut res = Response::Ok();
|
||||
let mut res = Response::build(StatusCode::OK);
|
||||
res.insert_header((
|
||||
"x-head",
|
||||
HeaderValue::from_static("dummy value!"),
|
||||
|
@ -4,14 +4,14 @@
|
||||
extern crate tls_rustls as rustls;
|
||||
|
||||
use std::{
|
||||
env, io,
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
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_server::Server;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
@ -20,8 +20,7 @@ use futures_core::{ready, Stream};
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
env::set_var("RUST_LOG", "actix=info,h2_ws=info");
|
||||
env_logger::init();
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
Server::build()
|
||||
.bind("tcp", ("127.0.0.1", 8080), || {
|
||||
@ -34,14 +33,14 @@ async fn main() -> io::Result<()> {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn handler(req: Request) -> Result<Response, Error> {
|
||||
async fn handler(req: Request) -> Result<Response<BodyStream<Heartbeat>>, Error> {
|
||||
log::info!("handshaking");
|
||||
let mut res = ws::handshake(req.head())?;
|
||||
|
||||
// handshake will always fail under HTTP/2
|
||||
|
||||
log::info!("responding");
|
||||
Ok(res.streaming(Heartbeat::new(ws::Codec::new())))
|
||||
Ok(res.message_body(BodyStream::new(Heartbeat::new(ws::Codec::new())))?)
|
||||
}
|
||||
|
||||
struct Heartbeat {
|
||||
|
@ -1,58 +1,71 @@
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
error::Error as StdError,
|
||||
fmt, mem,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures_core::Stream;
|
||||
use futures_core::{ready, Stream};
|
||||
|
||||
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.
|
||||
pub enum Body {
|
||||
pub enum AnyBody {
|
||||
/// Empty response. `Content-Length` header is not set.
|
||||
None,
|
||||
|
||||
/// Zero sized response body. `Content-Length` header is set to `0`.
|
||||
Empty,
|
||||
|
||||
/// Specific response body.
|
||||
Bytes(Bytes),
|
||||
|
||||
/// Generic message body.
|
||||
Message(Box<dyn MessageBody + Unpin>),
|
||||
Message(BoxAnyBody),
|
||||
}
|
||||
|
||||
impl Body {
|
||||
impl AnyBody {
|
||||
/// Create body from slice (copy)
|
||||
pub fn from_slice(s: &[u8]) -> Body {
|
||||
Body::Bytes(Bytes::copy_from_slice(s))
|
||||
pub fn from_slice(s: &[u8]) -> Self {
|
||||
Self::Bytes(Bytes::copy_from_slice(s))
|
||||
}
|
||||
|
||||
/// Create body from generic message body.
|
||||
pub fn from_message<B: MessageBody + Unpin + 'static>(body: B) -> Body {
|
||||
Body::Message(Box::new(body))
|
||||
pub fn from_message<B>(body: B) -> Self
|
||||
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 {
|
||||
match self {
|
||||
Body::None => BodySize::None,
|
||||
Body::Empty => BodySize::Empty,
|
||||
Body::Bytes(ref bin) => BodySize::Sized(bin.len() as u64),
|
||||
Body::Message(ref body) => body.size(),
|
||||
AnyBody::None => BodySize::None,
|
||||
AnyBody::Empty => BodySize::Empty,
|
||||
AnyBody::Bytes(ref bin) => BodySize::Sized(bin.len() as u64),
|
||||
AnyBody::Message(ref body) => body.size(),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
match self.get_mut() {
|
||||
Body::None => Poll::Ready(None),
|
||||
Body::Empty => Poll::Ready(None),
|
||||
Body::Bytes(ref mut bin) => {
|
||||
AnyBody::None => Poll::Ready(None),
|
||||
AnyBody::Empty => Poll::Ready(None),
|
||||
AnyBody::Bytes(ref mut bin) => {
|
||||
let len = bin.len();
|
||||
if len == 0 {
|
||||
Poll::Ready(None)
|
||||
@ -60,99 +73,158 @@ impl MessageBody for Body {
|
||||
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 {
|
||||
match *self {
|
||||
Body::None => matches!(*other, Body::None),
|
||||
Body::Empty => matches!(*other, Body::Empty),
|
||||
Body::Bytes(ref b) => match *other {
|
||||
Body::Bytes(ref b2) => b == b2,
|
||||
AnyBody::None => matches!(*other, AnyBody::None),
|
||||
AnyBody::Empty => matches!(*other, AnyBody::Empty),
|
||||
AnyBody::Bytes(ref b) => match *other {
|
||||
AnyBody::Bytes(ref b2) => b == b2,
|
||||
_ => 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 {
|
||||
match *self {
|
||||
Body::None => write!(f, "Body::None"),
|
||||
Body::Empty => write!(f, "Body::Empty"),
|
||||
Body::Bytes(ref b) => write!(f, "Body::Bytes({:?})", b),
|
||||
Body::Message(_) => write!(f, "Body::Message(_)"),
|
||||
AnyBody::None => write!(f, "AnyBody::None"),
|
||||
AnyBody::Empty => write!(f, "AnyBody::Empty"),
|
||||
AnyBody::Bytes(ref b) => write!(f, "AnyBody::Bytes({:?})", b),
|
||||
AnyBody::Message(_) => write!(f, "AnyBody::Message(_)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for Body {
|
||||
impl From<&'static str> for AnyBody {
|
||||
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 {
|
||||
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 {
|
||||
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 {
|
||||
s.into_bytes().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a String> for Body {
|
||||
fn from(s: &'a String) -> Body {
|
||||
Body::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&s)))
|
||||
impl From<&'_ String> for AnyBody {
|
||||
fn from(s: &String) -> Body {
|
||||
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 {
|
||||
Body::Bytes(s)
|
||||
AnyBody::Bytes(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BytesMut> for Body {
|
||||
impl From<BytesMut> for AnyBody {
|
||||
fn from(s: BytesMut) -> Body {
|
||||
Body::Bytes(s.freeze())
|
||||
AnyBody::Bytes(s.freeze())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Value> for Body {
|
||||
fn from(v: serde_json::Value) -> Body {
|
||||
Body::Bytes(v.to_string().into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<SizedStream<S>> for Body
|
||||
impl<S> From<SizedStream<S>> for AnyBody
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, Error>> + Unpin + 'static,
|
||||
S: Stream<Item = Result<Bytes, Error>> + 'static,
|
||||
{
|
||||
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
|
||||
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
|
||||
S: Stream<Item = Result<Bytes, E>> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
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 futures_core::{ready, Stream};
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
use super::{BodySize, MessageBody};
|
||||
|
||||
/// Streaming response wrapper.
|
||||
///
|
||||
/// Response does not contain `Content-Length` header and appropriate transfer encoding is used.
|
||||
pub struct BodyStream<S: Unpin> {
|
||||
stream: S,
|
||||
pin_project! {
|
||||
/// Streaming response wrapper.
|
||||
///
|
||||
/// Response does not contain `Content-Length` header and appropriate transfer encoding is used.
|
||||
pub struct BodyStream<S> {
|
||||
#[pin]
|
||||
stream: S,
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, E> BodyStream<S>
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, E>> + Unpin,
|
||||
S: Stream<Item = Result<Bytes, E>>,
|
||||
E: Into<Error>,
|
||||
{
|
||||
pub fn new(stream: S) -> Self {
|
||||
@ -29,9 +33,11 @@ where
|
||||
|
||||
impl<S, E> MessageBody for BodyStream<S>
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, E>> + Unpin,
|
||||
S: Stream<Item = Result<Bytes, E>>,
|
||||
E: Into<Error>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Stream
|
||||
}
|
||||
@ -44,11 +50,11 @@ where
|
||||
fn poll_next(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
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,
|
||||
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.
|
||||
|
||||
use std::{
|
||||
convert::Infallible,
|
||||
mem,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures_core::ready;
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
use super::BodySize;
|
||||
|
||||
/// Type that implement this trait can be streamed to a peer.
|
||||
/// An interface for response bodies.
|
||||
pub trait MessageBody {
|
||||
type Error;
|
||||
|
||||
/// Body size hint.
|
||||
fn size(&self) -> BodySize;
|
||||
|
||||
/// Attempt to pull out the next chunk of body bytes.
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>>;
|
||||
|
||||
downcast_get_type_id!();
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>>;
|
||||
}
|
||||
|
||||
downcast!(MessageBody);
|
||||
|
||||
impl MessageBody for () {
|
||||
type Error = Infallible;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Empty
|
||||
}
|
||||
@ -34,12 +39,18 @@ impl MessageBody for () {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
_: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
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 {
|
||||
self.as_ref().size()
|
||||
}
|
||||
@ -47,12 +58,33 @@ impl<T: MessageBody + Unpin> MessageBody for Box<T> {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
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 {
|
||||
type Error = Infallible;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len() as u64)
|
||||
}
|
||||
@ -60,7 +92,7 @@ impl MessageBody for Bytes {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
_: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
if self.is_empty() {
|
||||
Poll::Ready(None)
|
||||
} else {
|
||||
@ -70,6 +102,8 @@ impl MessageBody for Bytes {
|
||||
}
|
||||
|
||||
impl MessageBody for BytesMut {
|
||||
type Error = Infallible;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len() as u64)
|
||||
}
|
||||
@ -77,7 +111,7 @@ impl MessageBody for BytesMut {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
_: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
if self.is_empty() {
|
||||
Poll::Ready(None)
|
||||
} else {
|
||||
@ -87,6 +121,8 @@ impl MessageBody for BytesMut {
|
||||
}
|
||||
|
||||
impl MessageBody for &'static str {
|
||||
type Error = Infallible;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len() as u64)
|
||||
}
|
||||
@ -94,7 +130,7 @@ impl MessageBody for &'static str {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
_: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
if self.is_empty() {
|
||||
Poll::Ready(None)
|
||||
} else {
|
||||
@ -106,6 +142,8 @@ impl MessageBody for &'static str {
|
||||
}
|
||||
|
||||
impl MessageBody for Vec<u8> {
|
||||
type Error = Infallible;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len() as u64)
|
||||
}
|
||||
@ -113,7 +151,7 @@ impl MessageBody for Vec<u8> {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
_: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
if self.is_empty() {
|
||||
Poll::Ready(None)
|
||||
} else {
|
||||
@ -123,6 +161,8 @@ impl MessageBody for Vec<u8> {
|
||||
}
|
||||
|
||||
impl MessageBody for String {
|
||||
type Error = Infallible;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len() as u64)
|
||||
}
|
||||
@ -130,7 +170,7 @@ impl MessageBody for String {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
_: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
if self.is_empty() {
|
||||
Poll::Ready(None)
|
||||
} 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.
|
||||
|
||||
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)]
|
||||
mod body;
|
||||
mod body_stream;
|
||||
@ -8,13 +15,58 @@ mod response_body;
|
||||
mod size;
|
||||
mod sized_stream;
|
||||
|
||||
pub use self::body::Body;
|
||||
pub use self::body::{AnyBody, Body, BoxAnyBody};
|
||||
pub use self::body_stream::BodyStream;
|
||||
pub use self::message_body::MessageBody;
|
||||
pub(crate) use self::message_body::MessageBodyMapErr;
|
||||
pub use self::response_body::ResponseBody;
|
||||
pub use self::size::BodySize;
|
||||
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)]
|
||||
mod tests {
|
||||
use std::pin::Pin;
|
||||
@ -22,7 +74,6 @@ mod tests {
|
||||
use actix_rt::pin;
|
||||
use actix_utils::future::poll_fn;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures_util::stream;
|
||||
|
||||
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]
|
||||
async fn test_static_str() {
|
||||
assert_eq!(Body::from("").size(), BodySize::Sized(0));
|
||||
@ -174,73 +216,26 @@ mod tests {
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_serde_json() {
|
||||
use serde_json::json;
|
||||
use serde_json::{json, Value};
|
||||
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)
|
||||
);
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn body_stream_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")),
|
||||
);
|
||||
}
|
||||
|
||||
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")),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// down-casting used to be done with a method on MessageBody trait
|
||||
// test is kept to demonstrate equivalence of Any trait
|
||||
#[actix_rt::test]
|
||||
async fn test_body_casting() {
|
||||
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();
|
||||
assert_eq!(body, "hello cast");
|
||||
let body = &mut resp_body.downcast_mut::<String>().unwrap();
|
||||
@ -250,4 +245,15 @@ mod tests {
|
||||
let not_body = resp_body.downcast_ref::<()>();
|
||||
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 futures_core::Stream;
|
||||
use futures_core::{ready, Stream};
|
||||
use pin_project::pin_project;
|
||||
|
||||
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 {
|
||||
match self {
|
||||
ResponseBody::Body(ref body) => body.size(),
|
||||
@ -54,15 +60,16 @@ impl<B: MessageBody> MessageBody for ResponseBody<B> {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
match self.project() {
|
||||
ResponseBodyProj::Body(body) => body.poll_next(cx),
|
||||
ResponseBodyProj::Other(body) => Pin::new(body).poll_next(cx),
|
||||
}
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
Stream::poll_next(self, 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>;
|
||||
|
||||
fn poll_next(
|
||||
@ -70,7 +77,12 @@ impl<B: MessageBody> Stream for ResponseBody<B> {
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Self::Item>> {
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
@ -5,23 +5,27 @@ use std::{
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures_core::{ready, Stream};
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
use super::{BodySize, MessageBody};
|
||||
|
||||
/// 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.
|
||||
pub struct SizedStream<S: Unpin> {
|
||||
size: u64,
|
||||
stream: S,
|
||||
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.
|
||||
pub struct SizedStream<S> {
|
||||
size: u64,
|
||||
#[pin]
|
||||
stream: S,
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SizedStream<S>
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, Error>> + Unpin,
|
||||
S: Stream<Item = Result<Bytes, Error>>,
|
||||
{
|
||||
pub fn new(size: u64, stream: S) -> Self {
|
||||
SizedStream { size, stream }
|
||||
@ -30,8 +34,10 @@ where
|
||||
|
||||
impl<S> MessageBody for SizedStream<S>
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, Error>> + Unpin,
|
||||
S: Stream<Item = Result<Bytes, Error>>,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.size as u64)
|
||||
}
|
||||
@ -44,11 +50,11 @@ where
|
||||
fn poll_next(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
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,
|
||||
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.
|
||||
pub fn h2<F, B>(self, service: F) -> H2Service<T, S, B>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoServiceFactory<S, Request>,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
let cfg = ServiceConfig::new(
|
||||
self.keep_alive,
|
||||
@ -223,11 +225,13 @@ where
|
||||
/// Finish service configuration and create `HttpService` instance.
|
||||
pub fn finish<F, B>(self, service: F) -> HttpService<T, S, B, X, U>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoServiceFactory<S, Request>,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
let cfg = ServiceConfig::new(
|
||||
self.keep_alive,
|
||||
|
@ -12,10 +12,10 @@ use bytes::Bytes;
|
||||
use futures_core::future::LocalBoxFuture;
|
||||
use h2::client::SendRequest;
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::h1::ClientCodec;
|
||||
use crate::message::{RequestHeadType, ResponseHead};
|
||||
use crate::payload::Payload;
|
||||
use crate::{body::MessageBody, Error};
|
||||
|
||||
use super::error::SendRequestError;
|
||||
use super::pool::Acquired;
|
||||
@ -256,8 +256,9 @@ where
|
||||
body: RB,
|
||||
) -> LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>>
|
||||
where
|
||||
RB: MessageBody + 'static,
|
||||
H: Into<RequestHeadType> + 'static,
|
||||
RB: MessageBody + 'static,
|
||||
RB::Error: Into<Error>,
|
||||
{
|
||||
Box::pin(async move {
|
||||
match self {
|
||||
|
@ -11,7 +11,6 @@ use bytes::{Bytes, BytesMut};
|
||||
use futures_core::{ready, Stream};
|
||||
use futures_util::SinkExt as _;
|
||||
|
||||
use crate::error::PayloadError;
|
||||
use crate::h1;
|
||||
use crate::http::{
|
||||
header::{HeaderMap, IntoHeaderValue, EXPECT, HOST},
|
||||
@ -19,6 +18,7 @@ use crate::http::{
|
||||
};
|
||||
use crate::message::{RequestHeadType, ResponseHead};
|
||||
use crate::payload::Payload;
|
||||
use crate::{error::PayloadError, Error};
|
||||
|
||||
use super::connection::{ConnectionIo, H1Connection};
|
||||
use super::error::{ConnectError, SendRequestError};
|
||||
@ -32,6 +32,7 @@ pub(crate) async fn send_request<Io, B>(
|
||||
where
|
||||
Io: ConnectionIo,
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
// set request host header
|
||||
if !head.as_ref().headers.contains_key(HOST)
|
||||
@ -154,6 +155,7 @@ pub(crate) async fn send_body<Io, B>(
|
||||
where
|
||||
Io: ConnectionIo,
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
actix_rt::pin!(body);
|
||||
|
||||
@ -161,9 +163,10 @@ where
|
||||
while !eof {
|
||||
while !eof && !framed.as_ref().is_write_buf_full() {
|
||||
match poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
||||
Some(result) => {
|
||||
framed.as_mut().write(h1::Message::Chunk(Some(result?)))?;
|
||||
Some(Ok(chunk)) => {
|
||||
framed.as_mut().write(h1::Message::Chunk(Some(chunk)))?;
|
||||
}
|
||||
Some(Err(err)) => return Err(err.into().into()),
|
||||
None => {
|
||||
eof = true;
|
||||
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::{request::Request, Method, Version};
|
||||
|
||||
use crate::body::{BodySize, MessageBody};
|
||||
use crate::header::HeaderMap;
|
||||
use crate::message::{RequestHeadType, ResponseHead};
|
||||
use crate::payload::Payload;
|
||||
use crate::{
|
||||
body::{BodySize, MessageBody},
|
||||
header::HeaderMap,
|
||||
message::{RequestHeadType, ResponseHead},
|
||||
payload::Payload,
|
||||
Error,
|
||||
};
|
||||
|
||||
use super::config::ConnectorConfig;
|
||||
use super::connection::{ConnectionIo, H2Connection};
|
||||
use super::error::SendRequestError;
|
||||
use super::{
|
||||
config::ConnectorConfig,
|
||||
connection::{ConnectionIo, H2Connection},
|
||||
error::SendRequestError,
|
||||
};
|
||||
|
||||
pub(crate) async fn send_request<Io, B>(
|
||||
mut io: H2Connection<Io>,
|
||||
@ -26,6 +31,7 @@ pub(crate) async fn send_request<Io, B>(
|
||||
where
|
||||
Io: ConnectionIo,
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
trace!("Sending client request: {:?} {:?}", head, body.size());
|
||||
|
||||
@ -125,10 +131,14 @@ where
|
||||
Ok((head, payload))
|
||||
}
|
||||
|
||||
async fn send_body<B: MessageBody>(
|
||||
async fn send_body<B>(
|
||||
body: B,
|
||||
mut send: SendStream<Bytes>,
|
||||
) -> Result<(), SendRequestError> {
|
||||
) -> Result<(), SendRequestError>
|
||||
where
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
let mut buf = None;
|
||||
actix_rt::pin!(body);
|
||||
loop {
|
||||
@ -138,7 +148,7 @@ async fn send_body<B: MessageBody>(
|
||||
send.reserve_capacity(b.len());
|
||||
buf = Some(b);
|
||||
}
|
||||
Some(Err(e)) => return Err(e.into()),
|
||||
Some(Err(e)) => return Err(e.into().into()),
|
||||
None => {
|
||||
if let Err(e) = send.send_data(Bytes::new(), true) {
|
||||
return Err(e.into());
|
||||
|
@ -1,6 +1,7 @@
|
||||
//! Stream encoders.
|
||||
|
||||
use std::{
|
||||
error::Error as StdError,
|
||||
future::Future,
|
||||
io::{self, Write as _},
|
||||
pin::Pin,
|
||||
@ -10,12 +11,13 @@ use std::{
|
||||
use actix_rt::task::{spawn_blocking, JoinHandle};
|
||||
use brotli2::write::BrotliEncoder;
|
||||
use bytes::Bytes;
|
||||
use derive_more::Display;
|
||||
use flate2::write::{GzEncoder, ZlibEncoder};
|
||||
use futures_core::ready;
|
||||
use pin_project::pin_project;
|
||||
|
||||
use crate::{
|
||||
body::{Body, BodySize, MessageBody, ResponseBody},
|
||||
body::{Body, BodySize, BoxAnyBody, MessageBody, ResponseBody},
|
||||
http::{
|
||||
header::{ContentEncoding, CONTENT_ENCODING},
|
||||
HeaderValue, StatusCode,
|
||||
@ -92,10 +94,16 @@ impl<B: MessageBody> Encoder<B> {
|
||||
enum EncoderBody<B> {
|
||||
Bytes(Bytes),
|
||||
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 {
|
||||
match self {
|
||||
EncoderBody::Bytes(ref b) => b.size(),
|
||||
@ -107,7 +115,7 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
match self.project() {
|
||||
EncoderBodyProj::Bytes(b) => {
|
||||
if b.is_empty() {
|
||||
@ -116,15 +124,32 @@ impl<B: MessageBody> MessageBody for EncoderBody<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) => {
|
||||
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 {
|
||||
if self.encoder.is_none() {
|
||||
self.body.size()
|
||||
@ -136,7 +161,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||
fn poll_next(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Error>>> {
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
let mut this = self.project();
|
||||
loop {
|
||||
if *this.eof {
|
||||
@ -144,8 +169,9 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||
}
|
||||
|
||||
if let Some(ref mut fut) = this.fut {
|
||||
let mut encoder =
|
||||
ready!(Pin::new(fut).poll(cx)).map_err(|_| BlockingError)??;
|
||||
let mut encoder = ready!(Pin::new(fut).poll(cx))
|
||||
.map_err(|_| EncoderError::Blocking(BlockingError))?
|
||||
.map_err(EncoderError::Io)?;
|
||||
|
||||
let chunk = encoder.take();
|
||||
*this.encoder = Some(encoder);
|
||||
@ -164,7 +190,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||
Some(Ok(chunk)) => {
|
||||
if let Some(mut encoder) = this.encoder.take() {
|
||||
if chunk.len() < MAX_CHUNK_SIZE_ENCODE_IN_PLACE {
|
||||
encoder.write(&chunk)?;
|
||||
encoder.write(&chunk).map_err(EncoderError::Io)?;
|
||||
let chunk = encoder.take();
|
||||
*this.encoder = Some(encoder);
|
||||
|
||||
@ -184,7 +210,7 @@ impl<B: MessageBody> MessageBody for Encoder<B> {
|
||||
|
||||
None => {
|
||||
if let Some(encoder) = this.encoder.take() {
|
||||
let chunk = encoder.finish()?;
|
||||
let chunk = encoder.finish().map_err(EncoderError::Io)?;
|
||||
if chunk.is_empty() {
|
||||
return Poll::Ready(None);
|
||||
} 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
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::io::Write;
|
||||
use std::str::Utf8Error;
|
||||
use std::string::FromUtf8Error;
|
||||
use std::{fmt, io, result};
|
||||
use std::{
|
||||
error::Error as StdError,
|
||||
fmt,
|
||||
io::{self, Write as _},
|
||||
str::Utf8Error,
|
||||
string::FromUtf8Error,
|
||||
};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use derive_more::{Display, From};
|
||||
use http::uri::InvalidUri;
|
||||
use http::{header, Error as HttpError, StatusCode};
|
||||
use derive_more::{Display, Error, From};
|
||||
use http::{header, uri::InvalidUri, StatusCode};
|
||||
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::helpers::Writer;
|
||||
use crate::response::{Response, ResponseBuilder};
|
||||
use crate::{body::Body, helpers::Writer, Response};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
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>;
|
||||
pub use http::Error as HttpError;
|
||||
|
||||
/// 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 {
|
||||
/// 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 {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
/// Create response for error
|
||||
/// Creates full response for error.
|
||||
///
|
||||
/// Internal server error is generated by default.
|
||||
fn error_response(&self) -> Response {
|
||||
/// By default, the generated response uses a 500 Internal Server Error status code, a
|
||||
/// `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 buf = BytesMut::new();
|
||||
let _ = write!(Writer(&mut buf), "{}", self);
|
||||
@ -109,14 +99,13 @@ impl From<()> for Error {
|
||||
|
||||
impl From<std::convert::Infallible> for Error {
|
||||
fn from(_: std::convert::Infallible) -> Self {
|
||||
// `std::convert::Infallible` indicates an error
|
||||
// that will never happen
|
||||
// hint that an error that will never happen
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Error` to a `Response` instance
|
||||
impl From<Error> for Response {
|
||||
impl From<Error> for Response<Body> {
|
||||
fn from(err: Error) -> Self {
|
||||
Response::from_error(err)
|
||||
}
|
||||
@ -131,35 +120,17 @@ impl<T: ResponseError + 'static> From<T> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert Response to a Error
|
||||
impl From<Response> for 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")]
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[display(fmt = "Unknown Error")]
|
||||
struct UnitError;
|
||||
|
||||
impl ResponseError for Box<dyn StdError + 'static> {}
|
||||
|
||||
/// Returns [`StatusCode::INTERNAL_SERVER_ERROR`] 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`].
|
||||
#[cfg(feature = "openssl")]
|
||||
impl ResponseError for actix_tls::accept::openssl::SslError {}
|
||||
|
||||
/// 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
|
||||
#[derive(Debug, Display)]
|
||||
/// A set of errors that can occur during parsing HTTP streams.
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum ParseError {
|
||||
/// An invalid `Method`, such as `GE.T`.
|
||||
#[display(fmt = "Invalid Method specified")]
|
||||
Method,
|
||||
|
||||
/// An invalid `Uri`, such as `exam ple.domain`.
|
||||
#[display(fmt = "Uri error: {}", _0)]
|
||||
Uri(InvalidUri),
|
||||
|
||||
/// An invalid `HttpVersion`, such as `HTP/1.1`
|
||||
#[display(fmt = "Invalid HTTP version specified")]
|
||||
Version,
|
||||
|
||||
/// An invalid `Header`.
|
||||
#[display(fmt = "Invalid Header provided")]
|
||||
Header,
|
||||
|
||||
/// A message head is too large to be reasonable.
|
||||
#[display(fmt = "Message head is too large")]
|
||||
TooLarge,
|
||||
|
||||
/// A message reached EOF, but is not complete.
|
||||
#[display(fmt = "Message is incomplete")]
|
||||
Incomplete,
|
||||
|
||||
/// An invalid `Status`, such as `1337 ELITE`.
|
||||
#[display(fmt = "Invalid Status provided")]
|
||||
Status,
|
||||
|
||||
/// A timeout occurred waiting for an IO event.
|
||||
#[allow(dead_code)]
|
||||
#[display(fmt = "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)]
|
||||
Io(io::Error),
|
||||
|
||||
/// Parsing a field as string failed
|
||||
#[display(fmt = "UTF8 error: {}", _0)]
|
||||
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.
|
||||
#[derive(Debug, Display)]
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[display(fmt = "Blocking thread pool is gone")]
|
||||
pub struct BlockingError;
|
||||
|
||||
impl std::error::Error for BlockingError {}
|
||||
|
||||
/// `InternalServerError` 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 {
|
||||
/// A payload reached EOF, but is not complete.
|
||||
#[display(
|
||||
@ -378,16 +357,9 @@ impl ResponseError for PayloadError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `cookie::ParseError`
|
||||
#[cfg(feature = "cookies")]
|
||||
impl ResponseError for crate::cookie::ParseError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Display, From)]
|
||||
/// A set of errors that can occur during dispatching HTTP requests
|
||||
/// A set of errors that can occur during dispatching HTTP requests.
|
||||
#[derive(Debug, Display, Error, From)]
|
||||
#[non_exhaustive]
|
||||
pub enum DispatchError {
|
||||
/// Service error
|
||||
Service(Error),
|
||||
@ -433,516 +405,41 @@ pub enum DispatchError {
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// A set of error that can occur during parsing content type
|
||||
#[derive(PartialEq, Debug, Display)]
|
||||
/// A set of error that can occur during parsing content type.
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum ContentTypeError {
|
||||
/// Can not parse content type
|
||||
#[display(fmt = "Can not parse content type")]
|
||||
ParseError,
|
||||
|
||||
/// Unknown content encoding
|
||||
#[display(fmt = "Unknown content encoding")]
|
||||
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 {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
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)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@ -951,21 +448,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
#[test]
|
||||
fn test_cookie_parse() {
|
||||
let resp: Response = CookieParseError::EmptyName.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_as_response() {
|
||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||
@ -993,7 +483,7 @@ mod tests {
|
||||
fn test_error_http_response() {
|
||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||
let e = Error::from(orig);
|
||||
let resp: Response = e.into();
|
||||
let resp: Response<Body> = e.into();
|
||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
@ -1046,14 +536,6 @@ mod tests {
|
||||
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]
|
||||
fn test_error_casting() {
|
||||
let err = PayloadError::Overflow;
|
||||
@ -1063,124 +545,4 @@ mod tests {
|
||||
let not_err = resp_err.downcast_ref::<ContentTypeError>();
|
||||
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]
|
||||
fn test_parse_chunked_payload_chunk_extension() {
|
||||
let mut buf = BytesMut::from(
|
||||
&"GET /test HTTP/1.1\r\n\
|
||||
transfer-encoding: chunked\r\n\r\n"[..],
|
||||
"GET /test HTTP/1.1\r\n\
|
||||
transfer-encoding: chunked\r\n\
|
||||
\r\n",
|
||||
);
|
||||
|
||||
let mut reader = MessageDecoder::<Request>::default();
|
||||
@ -1233,7 +1234,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_response_http10_read_until_eof() {
|
||||
let mut buf = BytesMut::from(&"HTTP/1.0 200 Ok\r\n\r\ntest data"[..]);
|
||||
let mut buf = BytesMut::from("HTTP/1.0 200 Ok\r\n\r\ntest data");
|
||||
|
||||
let mut reader = MessageDecoder::<ResponseHead>::default();
|
||||
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
|
||||
|
@ -17,10 +17,11 @@ use futures_core::ready;
|
||||
use log::{error, trace};
|
||||
use pin_project::pin_project;
|
||||
|
||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||
use crate::body::{Body, BodySize, MessageBody};
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::error::{DispatchError, Error};
|
||||
use crate::error::{ParseError, PayloadError};
|
||||
use crate::http::StatusCode;
|
||||
use crate::request::Request;
|
||||
use crate::response::Response;
|
||||
use crate::service::HttpFlow;
|
||||
@ -50,9 +51,13 @@ pub struct Dispatcher<T, S, B, X, U>
|
||||
where
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -68,9 +73,13 @@ enum DispatcherState<T, S, B, X, U>
|
||||
where
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -83,9 +92,13 @@ struct InnerDispatcher<T, S, B, X, U>
|
||||
where
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -121,19 +134,25 @@ enum State<S, B, X>
|
||||
where
|
||||
S: Service<Request>,
|
||||
X: Service<Request, Response = Request>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
None,
|
||||
ExpectCall(#[pin] X::Future),
|
||||
ServiceCall(#[pin] S::Future),
|
||||
SendPayload(#[pin] ResponseBody<B>),
|
||||
SendPayload(#[pin] B),
|
||||
SendErrorPayload(#[pin] Body),
|
||||
}
|
||||
|
||||
impl<S, B, X> State<S, B, X>
|
||||
where
|
||||
S: Service<Request>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
fn is_empty(&self) -> bool {
|
||||
matches!(self, State::None)
|
||||
@ -149,12 +168,17 @@ enum PollResponse {
|
||||
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,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -205,12 +229,17 @@ where
|
||||
impl<T, S, B, X, U> InnerDispatcher<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -267,11 +296,11 @@ where
|
||||
io.poll_flush(cx)
|
||||
}
|
||||
|
||||
fn send_response(
|
||||
fn send_response_inner(
|
||||
self: Pin<&mut Self>,
|
||||
message: Response<()>,
|
||||
body: ResponseBody<B>,
|
||||
) -> Result<(), DispatchError> {
|
||||
body: &impl MessageBody,
|
||||
) -> Result<BodySize, DispatchError> {
|
||||
let size = body.size();
|
||||
let mut this = self.project();
|
||||
this.codec
|
||||
@ -284,10 +313,35 @@ where
|
||||
})?;
|
||||
|
||||
this.flags.set(Flags::KEEPALIVE, this.codec.keepalive());
|
||||
match size {
|
||||
BodySize::None | BodySize::Empty => this.state.set(State::None),
|
||||
_ => this.state.set(State::SendPayload(body)),
|
||||
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
@ -325,8 +379,7 @@ where
|
||||
// send_response would update InnerDispatcher state to SendPayload or
|
||||
// None(If response body is empty).
|
||||
// continue loop to poll it.
|
||||
self.as_mut()
|
||||
.send_response(res, ResponseBody::Other(Body::Empty))?;
|
||||
self.as_mut().send_error_response(res, Body::Empty)?;
|
||||
}
|
||||
|
||||
// return with upgrade request and poll it exclusively.
|
||||
@ -346,9 +399,9 @@ where
|
||||
|
||||
// send service call error as response
|
||||
Poll::Ready(Err(err)) => {
|
||||
let res: Response = err.into().into();
|
||||
let res = Response::from_error(err);
|
||||
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.
|
||||
@ -364,6 +417,41 @@ where
|
||||
},
|
||||
|
||||
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,
|
||||
// get blocked or finished.
|
||||
while this.write_buf.len() < super::payload::MAX_BUFFER_SIZE {
|
||||
@ -405,12 +493,14 @@ where
|
||||
let fut = this.flow.service.call(req);
|
||||
this.state.set(State::ServiceCall(fut));
|
||||
}
|
||||
|
||||
// send expect error as response
|
||||
Poll::Ready(Err(err)) => {
|
||||
let res: Response = err.into().into();
|
||||
let res = Response::from_error(err);
|
||||
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.
|
||||
Poll::Pending => return Ok(PollResponse::DoNothing),
|
||||
},
|
||||
@ -456,10 +546,9 @@ where
|
||||
// to notify the dispatcher a new state is set and the outer loop
|
||||
// should be continue.
|
||||
Poll::Ready(Err(err)) => {
|
||||
let err = err.into();
|
||||
let res: Response = err.into();
|
||||
let res = Response::from_error(err);
|
||||
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(()),
|
||||
// see the comment on ExpectCall state branch's 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(());
|
||||
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.messages.push_back(DispatcherMessage::Error(
|
||||
Response::InternalServerError().finish().drop_body(),
|
||||
Response::internal_server_error().drop_body(),
|
||||
));
|
||||
*this.error = Some(DispatchError::InternalError);
|
||||
break;
|
||||
@ -576,7 +665,7 @@ where
|
||||
error!("Internal server error: unexpected eof");
|
||||
this.flags.insert(Flags::READ_DISCONNECT);
|
||||
this.messages.push_back(DispatcherMessage::Error(
|
||||
Response::InternalServerError().finish().drop_body(),
|
||||
Response::internal_server_error().drop_body(),
|
||||
));
|
||||
*this.error = Some(DispatchError::InternalError);
|
||||
break;
|
||||
@ -599,7 +688,10 @@ where
|
||||
}
|
||||
// Requests overflow buffer size should be responded with 431
|
||||
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.error = Some(ParseError::TooLarge.into());
|
||||
@ -612,7 +704,7 @@ where
|
||||
|
||||
// Malformed requests should be responded with 400
|
||||
this.messages.push_back(DispatcherMessage::Error(
|
||||
Response::BadRequest().finish().drop_body(),
|
||||
Response::bad_request().drop_body(),
|
||||
));
|
||||
this.flags.insert(Flags::READ_DISCONNECT);
|
||||
*this.error = Some(err.into());
|
||||
@ -648,11 +740,6 @@ where
|
||||
// go into Some<Pin<&mut Sleep>> branch
|
||||
this.ka_timer.set(Some(sleep_until(deadline)));
|
||||
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 {
|
||||
// timeout on first request (slow request) return 408
|
||||
if !this.flags.contains(Flags::STARTED) {
|
||||
trace!("Slow request timeout");
|
||||
let _ = self.as_mut().send_response(
|
||||
Response::RequestTimeout().finish().drop_body(),
|
||||
ResponseBody::Other(Body::Empty),
|
||||
);
|
||||
this = self.project();
|
||||
} else {
|
||||
trace!("Keep-alive connection timeout");
|
||||
}
|
||||
trace!("Slow request timeout");
|
||||
let _ = self.as_mut().send_error_response(
|
||||
Response::with_body(StatusCode::REQUEST_TIMEOUT, ()),
|
||||
Body::Empty,
|
||||
);
|
||||
this = self.project();
|
||||
this.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
|
||||
this.state.set(State::None);
|
||||
}
|
||||
// still have unfinished task. try to reset and register keep-alive.
|
||||
} else if let Some(deadline) =
|
||||
@ -825,12 +907,17 @@ where
|
||||
impl<T, S, B, X, U> Future for 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,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -952,6 +1039,7 @@ mod tests {
|
||||
|
||||
use actix_service::fn_service;
|
||||
use actix_utils::future::{ready, Ready};
|
||||
use bytes::Bytes;
|
||||
use futures_util::future::lazy;
|
||||
|
||||
use super::*;
|
||||
@ -979,19 +1067,22 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn ok_service() -> impl Service<Request, Response = Response, Error = Error> {
|
||||
fn_service(|_req: Request| ready(Ok::<_, Error>(Response::Ok().finish())))
|
||||
fn ok_service() -> impl Service<Request, Response = Response<Body>, Error = Error> {
|
||||
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| {
|
||||
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| {
|
||||
Box::pin(async move {
|
||||
use futures_util::stream::StreamExt as _;
|
||||
@ -1002,7 +1093,7 @@ mod tests {
|
||||
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() {
|
||||
let mut bytes = BytesMut::with_capacity(2048);
|
||||
|
||||
let mut res: Response<()> =
|
||||
Response::new(StatusCode::SWITCHING_PROTOCOLS).into_body::<()>();
|
||||
let mut res = Response::with_body(StatusCode::SWITCHING_PROTOCOLS, ());
|
||||
res.headers_mut().insert(DATE, HeaderValue::from_static(""));
|
||||
res.headers_mut()
|
||||
.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));
|
||||
|
@ -5,7 +5,9 @@ use std::{fmt, net};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
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 futures_core::future::LocalBoxFuture;
|
||||
|
||||
@ -62,11 +64,15 @@ where
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
|
||||
U: ServiceFactory<(Request, Framed<TcpStream, Codec>), Config = (), Response = ()>,
|
||||
U::Future: 'static,
|
||||
U::Error: fmt::Display + Into<Error>,
|
||||
@ -82,7 +88,7 @@ where
|
||||
Error = DispatchError,
|
||||
InitError = (),
|
||||
> {
|
||||
pipeline_factory(|io: TcpStream| {
|
||||
fn_service(|io: TcpStream| {
|
||||
let peer_addr = io.peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
})
|
||||
@ -107,11 +113,15 @@ mod openssl {
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
|
||||
U: ServiceFactory<
|
||||
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||
Config = (),
|
||||
@ -132,16 +142,14 @@ mod openssl {
|
||||
Error = TlsError<SslError, DispatchError>,
|
||||
InitError = (),
|
||||
> {
|
||||
pipeline_factory(
|
||||
Acceptor::new(acceptor)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!()),
|
||||
)
|
||||
.and_then(|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
Acceptor::new(acceptor)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!())
|
||||
.and_then(|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -165,11 +173,15 @@ mod rustls {
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
|
||||
U: ServiceFactory<
|
||||
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||
Config = (),
|
||||
@ -190,16 +202,14 @@ mod rustls {
|
||||
Error = TlsError<io::Error, DispatchError>,
|
||||
InitError = (),
|
||||
> {
|
||||
pipeline_factory(
|
||||
Acceptor::new(config)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!()),
|
||||
)
|
||||
.and_then(|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
Acceptor::new(config)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!())
|
||||
.and_then(|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
})
|
||||
.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>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||
|
||||
S: ServiceFactory<Request, Config = ()>,
|
||||
S::Future: 'static,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
S::InitError: fmt::Debug,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
|
||||
U: ServiceFactory<(Request, Framed<T, Codec>), Config = (), Response = ()>,
|
||||
U::Future: 'static,
|
||||
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>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, Codec>), Response = ()>,
|
||||
U::Error: fmt::Display + Into<Error>,
|
||||
{
|
||||
|
@ -4,7 +4,7 @@ use std::task::{Context, Poll};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
|
||||
use crate::body::{BodySize, MessageBody, ResponseBody};
|
||||
use crate::body::{BodySize, MessageBody};
|
||||
use crate::error::Error;
|
||||
use crate::h1::{Codec, Message};
|
||||
use crate::response::Response;
|
||||
@ -14,7 +14,7 @@ use crate::response::Response;
|
||||
pub struct SendResponse<T, B> {
|
||||
res: Option<Message<(Response<()>, BodySize)>>,
|
||||
#[pin]
|
||||
body: Option<ResponseBody<B>>,
|
||||
body: Option<B>,
|
||||
#[pin]
|
||||
framed: Option<Framed<T, Codec>>,
|
||||
}
|
||||
@ -22,6 +22,7 @@ pub struct SendResponse<T, B> {
|
||||
impl<T, B> SendResponse<T, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
pub fn new(framed: Framed<T, Codec>, response: Response<B>) -> Self {
|
||||
let (res, body) = response.into_parts();
|
||||
@ -38,6 +39,7 @@ impl<T, B> Future for SendResponse<T, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
B: MessageBody + Unpin,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
type Output = Result<Framed<T, Codec>, Error>;
|
||||
|
||||
@ -60,7 +62,18 @@ where
|
||||
.unwrap()
|
||||
.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) => {
|
||||
// body is done when item is None
|
||||
body_done = item.is_none();
|
||||
|
@ -1,20 +1,26 @@
|
||||
use std::task::{Context, Poll};
|
||||
use std::{cmp, future::Future, marker::PhantomData, net, pin::Pin, rc::Rc};
|
||||
use std::{
|
||||
cmp,
|
||||
future::Future,
|
||||
marker::PhantomData,
|
||||
net,
|
||||
pin::Pin,
|
||||
rc::Rc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_service::Service;
|
||||
use actix_utils::future::poll_fn;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures_core::ready;
|
||||
use h2::{
|
||||
server::{Connection, SendResponse},
|
||||
SendStream,
|
||||
};
|
||||
use h2::server::{Connection, SendResponse};
|
||||
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING};
|
||||
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::error::{DispatchError, Error};
|
||||
use crate::error::Error;
|
||||
use crate::message::ResponseHead;
|
||||
use crate::payload::Payload;
|
||||
use crate::request::Request;
|
||||
@ -24,30 +30,19 @@ use crate::OnConnectData;
|
||||
|
||||
const CHUNK_SIZE: usize = 16_384;
|
||||
|
||||
/// Dispatcher for HTTP/2 protocol.
|
||||
#[pin_project::pin_project]
|
||||
pub struct Dispatcher<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
S: Service<Request>,
|
||||
B: MessageBody,
|
||||
{
|
||||
flow: Rc<HttpFlow<S, X, U>>,
|
||||
connection: Connection<T, Bytes>,
|
||||
on_connect_data: OnConnectData,
|
||||
config: ServiceConfig,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
_phantom: PhantomData<B>,
|
||||
pin_project! {
|
||||
/// Dispatcher for HTTP/2 protocol.
|
||||
pub struct Dispatcher<T, S, B, X, U> {
|
||||
flow: Rc<HttpFlow<S, X, U>>,
|
||||
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>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
B: MessageBody,
|
||||
{
|
||||
impl<T, S, B, X, U> Dispatcher<T, S, B, X, U> {
|
||||
pub(crate) fn new(
|
||||
flow: Rc<HttpFlow<S, X, U>>,
|
||||
connection: Connection<T, Bytes>,
|
||||
@ -55,7 +50,7 @@ where
|
||||
config: ServiceConfig,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
) -> Self {
|
||||
Dispatcher {
|
||||
Self {
|
||||
flow,
|
||||
config,
|
||||
peer_addr,
|
||||
@ -69,269 +64,208 @@ where
|
||||
impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Error: Into<Error>,
|
||||
S::Future: 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
B: MessageBody + 'static,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
type Output = Result<(), DispatchError>;
|
||||
type Output = Result<(), crate::error::DispatchError>;
|
||||
|
||||
#[inline]
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.get_mut();
|
||||
|
||||
loop {
|
||||
match ready!(Pin::new(&mut this.connection).poll_accept(cx)) {
|
||||
None => return Poll::Ready(Ok(())),
|
||||
while let Some((req, tx)) =
|
||||
ready!(Pin::new(&mut this.connection).poll_accept(cx)?)
|
||||
{
|
||||
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))) => {
|
||||
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);
|
||||
// merge on_connect_ext data into request extensions
|
||||
this.on_connect_data.merge_into(&mut req);
|
||||
|
||||
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;
|
||||
let fut = this.flow.service.call(req);
|
||||
let config = this.config.clone();
|
||||
|
||||
// merge on_connect_ext data into request extensions
|
||||
this.on_connect_data.merge_into(&mut req);
|
||||
// multiplex request handling with spawn task
|
||||
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 {
|
||||
state: ServiceResponseState::ServiceCall(
|
||||
this.flow.service.call(req),
|
||||
Some(res),
|
||||
),
|
||||
config: this.config.clone(),
|
||||
buffer: None,
|
||||
_phantom: PhantomData,
|
||||
};
|
||||
// log error.
|
||||
if let Err(err) = res {
|
||||
match err {
|
||||
DispatchError::SendResponse(err) => {
|
||||
trace!("Error sending HTTP/2 response: {:?}", err)
|
||||
}
|
||||
DispatchError::SendData(err) => warn!("{:?}", err),
|
||||
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]
|
||||
struct ServiceResponse<F, I, E, B> {
|
||||
#[pin]
|
||||
state: ServiceResponseState<F, B>,
|
||||
fn prepare_response(
|
||||
config: ServiceConfig,
|
||||
buffer: Option<Bytes>,
|
||||
_phantom: PhantomData<(I, E)>,
|
||||
}
|
||||
head: &ResponseHead,
|
||||
size: &mut BodySize,
|
||||
) -> http::Response<()> {
|
||||
let mut has_date = false;
|
||||
let mut skip_len = size != &BodySize::Stream;
|
||||
|
||||
#[pin_project::pin_project(project = ServiceResponseStateProj)]
|
||||
enum ServiceResponseState<F, B> {
|
||||
ServiceCall(#[pin] F, Option<SendResponse<Bytes>>),
|
||||
SendPayload(SendStream<Bytes>, #[pin] ResponseBody<B>),
|
||||
}
|
||||
let mut res = http::Response::new(());
|
||||
*res.status_mut() = head.status;
|
||||
*res.version_mut() = http::Version::HTTP_2;
|
||||
|
||||
impl<F, I, E, B> ServiceResponse<F, I, E, B>
|
||||
where
|
||||
F: Future<Output = Result<I, E>>,
|
||||
E: Into<Error>,
|
||||
I: Into<Response<B>>,
|
||||
B: MessageBody,
|
||||
{
|
||||
fn prepare_response(
|
||||
&self,
|
||||
head: &ResponseHead,
|
||||
size: &mut BodySize,
|
||||
) -> http::Response<()> {
|
||||
let mut has_date = false;
|
||||
let mut skip_len = size != &BodySize::Stream;
|
||||
// Content length
|
||||
match head.status {
|
||||
http::StatusCode::NO_CONTENT
|
||||
| http::StatusCode::CONTINUE
|
||||
| http::StatusCode::PROCESSING => *size = BodySize::None,
|
||||
http::StatusCode::SWITCHING_PROTOCOLS => {
|
||||
skip_len = true;
|
||||
*size = BodySize::Stream;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let mut res = http::Response::new(());
|
||||
*res.status_mut() = head.status;
|
||||
*res.version_mut() = http::Version::HTTP_2;
|
||||
let _ = match size {
|
||||
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();
|
||||
|
||||
// Content length
|
||||
match head.status {
|
||||
http::StatusCode::NO_CONTENT
|
||||
| http::StatusCode::CONTINUE
|
||||
| http::StatusCode::PROCESSING => *size = BodySize::None,
|
||||
http::StatusCode::SWITCHING_PROTOCOLS => {
|
||||
skip_len = true;
|
||||
*size = BodySize::Stream;
|
||||
}
|
||||
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,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let _ = match size {
|
||||
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
|
||||
res.headers_mut().append(key, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, I, E, B> Future for ServiceResponse<F, I, E, B>
|
||||
where
|
||||
F: Future<Output = Result<I, E>>,
|
||||
E: Into<Error>,
|
||||
I: Into<Response<B>>,
|
||||
B: MessageBody,
|
||||
{
|
||||
type Output = ();
|
||||
|
||||
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(());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// set date header
|
||||
if !has_date {
|
||||
let mut bytes = BytesMut::with_capacity(29);
|
||||
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
|
||||
}
|
||||
|
@ -7,8 +7,8 @@ use std::{net, rc::Rc};
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_rt::net::TcpStream;
|
||||
use actix_service::{
|
||||
fn_factory, fn_service, pipeline_factory, IntoServiceFactory, Service,
|
||||
ServiceFactory,
|
||||
fn_factory, fn_service, IntoServiceFactory, Service, ServiceFactory,
|
||||
ServiceFactoryExt as _,
|
||||
};
|
||||
use actix_utils::future::ready;
|
||||
use bytes::Bytes;
|
||||
@ -40,7 +40,9 @@ where
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
/// Create new `H2Service` instance with config.
|
||||
pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
|
||||
@ -69,7 +71,9 @@ where
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
/// Create plain TCP based service
|
||||
pub fn tcp(
|
||||
@ -81,12 +85,12 @@ where
|
||||
Error = DispatchError,
|
||||
InitError = S::InitError,
|
||||
> {
|
||||
pipeline_factory(fn_factory(|| {
|
||||
fn_factory(|| {
|
||||
ready(Ok::<_, S::InitError>(fn_service(|io: TcpStream| {
|
||||
let peer_addr = io.peer_addr().ok();
|
||||
ready(Ok::<_, DispatchError>((io, peer_addr)))
|
||||
})))
|
||||
}))
|
||||
})
|
||||
.and_then(self)
|
||||
}
|
||||
}
|
||||
@ -106,7 +110,9 @@ mod openssl {
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
/// Create OpenSSL based service
|
||||
pub fn openssl(
|
||||
@ -119,20 +125,18 @@ mod openssl {
|
||||
Error = TlsError<SslError, DispatchError>,
|
||||
InitError = S::InitError,
|
||||
> {
|
||||
pipeline_factory(
|
||||
Acceptor::new(acceptor)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!()),
|
||||
)
|
||||
.and_then(fn_factory(|| {
|
||||
ready(Ok::<_, S::InitError>(fn_service(
|
||||
|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
},
|
||||
)))
|
||||
}))
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
Acceptor::new(acceptor)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!())
|
||||
.and_then(fn_factory(|| {
|
||||
ready(Ok::<_, S::InitError>(fn_service(
|
||||
|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
},
|
||||
)))
|
||||
}))
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -152,7 +156,9 @@ mod rustls {
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
/// Create Rustls based service
|
||||
pub fn rustls(
|
||||
@ -168,20 +174,18 @@ mod rustls {
|
||||
let protos = vec!["h2".to_string().into()];
|
||||
config.set_protocols(&protos);
|
||||
|
||||
pipeline_factory(
|
||||
Acceptor::new(config)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!()),
|
||||
)
|
||||
.and_then(fn_factory(|| {
|
||||
ready(Ok::<_, S::InitError>(fn_service(
|
||||
|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
},
|
||||
)))
|
||||
}))
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
Acceptor::new(config)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!())
|
||||
.and_then(fn_factory(|| {
|
||||
ready(Ok::<_, S::InitError>(fn_service(
|
||||
|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
ready(Ok((io, peer_addr)))
|
||||
},
|
||||
)))
|
||||
}))
|
||||
.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>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||
|
||||
S: ServiceFactory<Request, Config = ()>,
|
||||
S::Future: 'static,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -256,6 +263,7 @@ where
|
||||
S::Future: 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -320,6 +328,7 @@ where
|
||||
S::Future: 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
type Output = Result<(), DispatchError>;
|
||||
|
||||
|
@ -1,9 +1,33 @@
|
||||
//! Typed HTTP headers, pre-defined `HeaderName`s, traits for parsing and conversion, and other
|
||||
//! header utility methods.
|
||||
//! Pre-defined `HeaderName`s, traits for parsing and conversion, and other header utility methods.
|
||||
|
||||
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::HttpMessage;
|
||||
|
@ -104,7 +104,7 @@ impl Display for Charset {
|
||||
impl FromStr for Charset {
|
||||
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() {
|
||||
"US-ASCII" => Us_Ascii,
|
||||
"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");
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
impl<'a, B> io::Write for Writer<'a, B>
|
||||
|
@ -1,19 +1,18 @@
|
||||
use std::cell::{Ref, RefMut};
|
||||
use std::str;
|
||||
use std::{
|
||||
cell::{Ref, RefMut},
|
||||
str,
|
||||
};
|
||||
|
||||
use encoding_rs::{Encoding, UTF_8};
|
||||
use http::header;
|
||||
use mime::Mime;
|
||||
|
||||
use crate::error::{ContentTypeError, ParseError};
|
||||
use crate::extensions::Extensions;
|
||||
use crate::header::{Header, HeaderMap};
|
||||
use crate::payload::Payload;
|
||||
#[cfg(feature = "cookies")]
|
||||
use crate::{cookie::Cookie, error::CookieParseError};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
struct Cookies(Vec<Cookie<'static>>);
|
||||
use crate::{
|
||||
error::{ContentTypeError, ParseError},
|
||||
header::{Header, HeaderMap},
|
||||
payload::Payload,
|
||||
Extensions,
|
||||
};
|
||||
|
||||
/// Trait that implements general purpose operations on HTTP messages.
|
||||
pub trait HttpMessage: Sized {
|
||||
@ -104,41 +103,6 @@ pub trait HttpMessage: Sized {
|
||||
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
|
||||
|
@ -6,13 +6,10 @@
|
||||
//! | `openssl` | TLS support via [OpenSSL]. |
|
||||
//! | `rustls` | TLS support via [rustls]. |
|
||||
//! | `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. |
|
||||
//!
|
||||
//! [OpenSSL]: https://crates.io/crates/openssl
|
||||
//! [rustls]: https://crates.io/crates/rustls
|
||||
//! [cookie]: https://crates.io/crates/cookie
|
||||
//! [trust-dns]: https://crates.io/crates/trust-dns
|
||||
|
||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||
@ -38,14 +35,14 @@ mod config;
|
||||
#[cfg(feature = "compress")]
|
||||
pub mod encoding;
|
||||
mod extensions;
|
||||
mod header;
|
||||
pub mod header;
|
||||
mod helpers;
|
||||
mod http_codes;
|
||||
mod http_message;
|
||||
mod message;
|
||||
mod payload;
|
||||
mod request;
|
||||
mod response;
|
||||
mod response_builder;
|
||||
mod service;
|
||||
mod time_parser;
|
||||
|
||||
@ -55,20 +52,24 @@ pub mod h2;
|
||||
pub mod test;
|
||||
pub mod ws;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
pub use cookie;
|
||||
|
||||
pub use self::builder::HttpServiceBuilder;
|
||||
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::header::ContentEncoding;
|
||||
pub use self::http_message::HttpMessage;
|
||||
pub use self::message::ConnectionType;
|
||||
pub use self::message::{Message, RequestHead, RequestHeadType, ResponseHead};
|
||||
pub use self::payload::{Payload, PayloadStream};
|
||||
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 ::http::{uri, uri::Uri};
|
||||
pub use ::http::{Method, StatusCode, Version};
|
||||
|
||||
// TODO: deprecate this mish-mash of random items
|
||||
pub mod http {
|
||||
//! Various HTTP related types.
|
||||
|
||||
@ -78,8 +79,6 @@ pub mod http {
|
||||
pub use http::{uri, Error, Uri};
|
||||
pub use http::{Method, StatusCode, Version};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
pub use crate::cookie::{Cookie, CookieBuilder};
|
||||
pub use crate::header::HeaderMap;
|
||||
|
||||
/// A collection of HTTP headers and helpers.
|
||||
|
@ -1,4 +1,5 @@
|
||||
#[macro_export]
|
||||
#[doc(hidden)]
|
||||
macro_rules! downcast_get_type_id {
|
||||
() => {
|
||||
/// 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
|
||||
/// this module. This ensures that safe code cannot violate
|
||||
/// 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)]
|
||||
fn __private_get_type_id__(&self) -> (std::any::TypeId, PrivateHelper)
|
||||
fn __private_get_type_id__(
|
||||
&self,
|
||||
_: PrivateHelper,
|
||||
) -> (std::any::TypeId, PrivateHelper)
|
||||
where
|
||||
Self: 'static,
|
||||
{
|
||||
@ -25,6 +33,7 @@ macro_rules! downcast_get_type_id {
|
||||
}
|
||||
|
||||
//Generate implementation for dyn $name
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! downcast {
|
||||
($name:ident) => {
|
||||
@ -37,7 +46,9 @@ macro_rules! downcast {
|
||||
impl dyn $name + 'static {
|
||||
/// Downcasts generic body to a specific type.
|
||||
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
|
||||
// implementation of `__private_get_type_id__`, since
|
||||
// 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.
|
||||
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
|
||||
// implementation of `__private_get_type_id__`, since
|
||||
// it requires returning a private type. We can therefore
|
||||
@ -70,6 +83,7 @@ macro_rules! downcast {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::upper_case_acronyms)]
|
||||
|
||||
trait MB {
|
||||
downcast_get_type_id!();
|
||||
|
@ -1,12 +1,15 @@
|
||||
use std::cell::{Ref, RefCell, RefMut};
|
||||
use std::net;
|
||||
use std::rc::Rc;
|
||||
use std::{
|
||||
cell::{Ref, RefCell, RefMut},
|
||||
net,
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use bitflags::bitflags;
|
||||
|
||||
use crate::extensions::Extensions;
|
||||
use crate::header::HeaderMap;
|
||||
use crate::http::{header, Method, StatusCode, Uri, Version};
|
||||
use crate::{
|
||||
header::{self, HeaderMap},
|
||||
Extensions, Method, StatusCode, Uri, Version,
|
||||
};
|
||||
|
||||
/// Represents various types of connection
|
||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
||||
@ -290,14 +293,14 @@ impl ResponseHead {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Check if keep-alive is enabled
|
||||
#[inline]
|
||||
pub fn keep_alive(&self) -> bool {
|
||||
self.connection_type() == ConnectionType::KeepAlive
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Check upgrade status of this message
|
||||
#[inline]
|
||||
pub fn upgrade(&self) -> bool {
|
||||
self.connection_type() == ConnectionType::Upgrade
|
||||
}
|
||||
@ -345,8 +348,8 @@ impl ResponseHead {
|
||||
}
|
||||
|
||||
pub struct Message<T: Head> {
|
||||
// Rc here should not be cloned by anyone.
|
||||
// It's used to reuse allocation of T and no shared ownership is allowed.
|
||||
/// Rc here should not be cloned by anyone.
|
||||
/// It's used to reuse allocation of T and no shared ownership is allowed.
|
||||
head: Rc<T>,
|
||||
}
|
||||
|
||||
@ -386,12 +389,6 @@ impl BoxedResponseHead {
|
||||
pub fn new(status: StatusCode) -> Self {
|
||||
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 {
|
||||
|
@ -2,16 +2,18 @@
|
||||
|
||||
use std::{
|
||||
cell::{Ref, RefMut},
|
||||
fmt, net,
|
||||
fmt, net, str,
|
||||
};
|
||||
|
||||
use http::{header, Method, Uri, Version};
|
||||
|
||||
use crate::extensions::Extensions;
|
||||
use crate::header::HeaderMap;
|
||||
use crate::message::{Message, RequestHead};
|
||||
use crate::payload::{Payload, PayloadStream};
|
||||
use crate::HttpMessage;
|
||||
use crate::{
|
||||
extensions::Extensions,
|
||||
header::HeaderMap,
|
||||
message::{Message, RequestHead},
|
||||
payload::{Payload, PayloadStream},
|
||||
HttpMessage,
|
||||
};
|
||||
|
||||
/// Request
|
||||
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_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 futures_core::{future::LocalBoxFuture, ready};
|
||||
use h2::server::{handshake, Handshake};
|
||||
@ -57,6 +59,7 @@ where
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
/// Create new `HttpService` instance.
|
||||
pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self {
|
||||
@ -155,6 +158,7 @@ where
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
@ -180,7 +184,7 @@ where
|
||||
Error = DispatchError,
|
||||
InitError = (),
|
||||
> {
|
||||
pipeline_factory(|io: TcpStream| async {
|
||||
fn_service(|io: TcpStream| async {
|
||||
let peer_addr = io.peer_addr().ok();
|
||||
Ok((io, Protocol::Http1, peer_addr))
|
||||
})
|
||||
@ -206,6 +210,7 @@ mod openssl {
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
@ -232,25 +237,23 @@ mod openssl {
|
||||
Error = TlsError<SslError, DispatchError>,
|
||||
InitError = (),
|
||||
> {
|
||||
pipeline_factory(
|
||||
Acceptor::new(acceptor)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!()),
|
||||
)
|
||||
.and_then(|io: TlsStream<TcpStream>| async {
|
||||
let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() {
|
||||
if protos.windows(2).any(|window| window == b"h2") {
|
||||
Protocol::Http2
|
||||
Acceptor::new(acceptor)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!())
|
||||
.and_then(|io: TlsStream<TcpStream>| async {
|
||||
let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() {
|
||||
if protos.windows(2).any(|window| window == b"h2") {
|
||||
Protocol::Http2
|
||||
} else {
|
||||
Protocol::Http1
|
||||
}
|
||||
} else {
|
||||
Protocol::Http1
|
||||
}
|
||||
} else {
|
||||
Protocol::Http1
|
||||
};
|
||||
let peer_addr = io.get_ref().peer_addr().ok();
|
||||
Ok((io, proto, peer_addr))
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
};
|
||||
let peer_addr = io.get_ref().peer_addr().ok();
|
||||
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,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
@ -304,25 +308,24 @@ mod rustls {
|
||||
let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()];
|
||||
config.set_protocols(&protos);
|
||||
|
||||
pipeline_factory(
|
||||
Acceptor::new(config)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!()),
|
||||
)
|
||||
.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") {
|
||||
Protocol::Http2
|
||||
Acceptor::new(config)
|
||||
.map_err(TlsError::Tls)
|
||||
.map_init_err(|_| panic!())
|
||||
.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") {
|
||||
Protocol::Http2
|
||||
} else {
|
||||
Protocol::Http1
|
||||
}
|
||||
} else {
|
||||
Protocol::Http1
|
||||
}
|
||||
} else {
|
||||
Protocol::Http1
|
||||
};
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
Ok((io, proto, peer_addr))
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
};
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
Ok((io, proto, peer_addr))
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -340,6 +343,7 @@ where
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
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>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Future: 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U::Error: fmt::Display + Into<Error>,
|
||||
{
|
||||
@ -523,13 +532,18 @@ where
|
||||
#[pin_project(project = StateProj)]
|
||||
enum State<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
S: Service<Request>,
|
||||
S::Future: 'static,
|
||||
S::Error: Into<Error>,
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -550,13 +564,18 @@ where
|
||||
pub struct HttpServiceHandlerResponse<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Future: 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
B: MessageBody + 'static,
|
||||
|
||||
B: MessageBody,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
@ -567,13 +586,18 @@ where
|
||||
impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin,
|
||||
|
||||
S: Service<Request>,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::Future: 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
B: MessageBody,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
|
||||
X: Service<Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
|
||||
U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
|
@ -13,11 +13,6 @@ use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use http::{Method, Uri, Version};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use crate::{
|
||||
cookie::{Cookie, CookieJar},
|
||||
header::{self, HeaderValue},
|
||||
};
|
||||
use crate::{
|
||||
header::{HeaderMap, IntoHeaderPair},
|
||||
payload::Payload,
|
||||
@ -54,8 +49,6 @@ struct Inner {
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
headers: HeaderMap,
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies: CookieJar,
|
||||
payload: Option<Payload>,
|
||||
}
|
||||
|
||||
@ -66,8 +59,6 @@ impl Default for TestRequest {
|
||||
uri: Uri::from_str("/").unwrap(),
|
||||
version: Version::HTTP_11,
|
||||
headers: HeaderMap::new(),
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies: CookieJar::new(),
|
||||
payload: None,
|
||||
}))
|
||||
}
|
||||
@ -134,13 +125,6 @@ impl TestRequest {
|
||||
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.
|
||||
pub fn set_payload<B: Into<Bytes>>(&mut self, data: B) -> &mut Self {
|
||||
let mut payload = crate::h1::Payload::empty();
|
||||
@ -169,22 +153,6 @@ impl TestRequest {
|
||||
head.version = inner.version;
|
||||
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
|
||||
}
|
||||
}
|
||||
|
@ -9,10 +9,8 @@ use derive_more::{Display, Error, From};
|
||||
use http::{header, Method, StatusCode};
|
||||
|
||||
use crate::{
|
||||
error::ResponseError,
|
||||
header::HeaderValue,
|
||||
message::RequestHead,
|
||||
response::{Response, ResponseBuilder},
|
||||
body::Body, error::ResponseError, header::HeaderValue, message::RequestHead,
|
||||
response::Response, ResponseBuilder,
|
||||
};
|
||||
|
||||
mod codec;
|
||||
@ -101,31 +99,39 @@ pub enum HandshakeError {
|
||||
}
|
||||
|
||||
impl ResponseError for HandshakeError {
|
||||
fn error_response(&self) -> Response {
|
||||
fn error_response(&self) -> Response<Body> {
|
||||
match self {
|
||||
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
|
||||
.insert_header((header::ALLOW, "GET"))
|
||||
.finish(),
|
||||
HandshakeError::GetMethodRequired => {
|
||||
Response::build(StatusCode::METHOD_NOT_ALLOWED)
|
||||
.insert_header((header::ALLOW, "GET"))
|
||||
.finish()
|
||||
}
|
||||
|
||||
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
|
||||
.reason("No WebSocket Upgrade header found")
|
||||
.finish(),
|
||||
HandshakeError::NoWebsocketUpgrade => {
|
||||
Response::build(StatusCode::BAD_REQUEST)
|
||||
.reason("No WebSocket Upgrade header found")
|
||||
.finish()
|
||||
}
|
||||
|
||||
HandshakeError::NoConnectionUpgrade => Response::BadRequest()
|
||||
.reason("No Connection upgrade")
|
||||
.finish(),
|
||||
HandshakeError::NoConnectionUpgrade => {
|
||||
Response::build(StatusCode::BAD_REQUEST)
|
||||
.reason("No Connection upgrade")
|
||||
.finish()
|
||||
}
|
||||
|
||||
HandshakeError::NoVersionHeader => Response::BadRequest()
|
||||
HandshakeError::NoVersionHeader => Response::build(StatusCode::BAD_REQUEST)
|
||||
.reason("WebSocket version header is required")
|
||||
.finish(),
|
||||
|
||||
HandshakeError::UnsupportedVersion => Response::BadRequest()
|
||||
.reason("Unsupported WebSocket version")
|
||||
.finish(),
|
||||
|
||||
HandshakeError::BadWebsocketKey => {
|
||||
Response::BadRequest().reason("Handshake error").finish()
|
||||
HandshakeError::UnsupportedVersion => {
|
||||
Response::build(StatusCode::BAD_REQUEST)
|
||||
.reason("Unsupported WebSocket version")
|
||||
.finish()
|
||||
}
|
||||
|
||||
HandshakeError::BadWebsocketKey => Response::build(StatusCode::BAD_REQUEST)
|
||||
.reason("Handshake error")
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -322,17 +328,17 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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);
|
||||
let resp: Response = HandshakeError::NoWebsocketUpgrade.error_response();
|
||||
let resp = HandshakeError::NoWebsocketUpgrade.error_response();
|
||||
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);
|
||||
let resp: Response = HandshakeError::NoVersionHeader.error_response();
|
||||
let resp = HandshakeError::NoVersionHeader.error_response();
|
||||
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);
|
||||
let resp: Response = HandshakeError::BadWebsocketKey.error_response();
|
||||
let resp = HandshakeError::BadWebsocketKey.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,11 @@
|
||||
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_service::ServiceFactoryExt;
|
||||
use actix_utils::future;
|
||||
use bytes::Bytes;
|
||||
use derive_more::{Display, Error};
|
||||
use futures_util::StreamExt as _;
|
||||
|
||||
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() {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -61,7 +62,7 @@ async fn test_h1_v2() {
|
||||
async fn test_connection_close() {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.tcp()
|
||||
.map(|_| ())
|
||||
})
|
||||
@ -77,9 +78,9 @@ async fn test_with_query_parameter() {
|
||||
HttpService::build()
|
||||
.finish(|req: Request| {
|
||||
if req.uri().query().unwrap().contains("qp=") {
|
||||
future::ok::<_, ()>(Response::Ok().finish())
|
||||
future::ok::<_, ()>(Response::ok())
|
||||
} else {
|
||||
future::ok::<_, ()>(Response::BadRequest().finish())
|
||||
future::ok::<_, ()>(Response::bad_request())
|
||||
}
|
||||
})
|
||||
.tcp()
|
||||
@ -92,6 +93,16 @@ async fn test_with_query_parameter() {
|
||||
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]
|
||||
async fn test_h1_expect() {
|
||||
let srv = test_server(move || {
|
||||
@ -100,7 +111,7 @@ async fn test_h1_expect() {
|
||||
if req.headers().contains_key("AUTH") {
|
||||
Ok(req)
|
||||
} else {
|
||||
Err(error::ErrorExpectationFailed("expect failed"))
|
||||
Err(ExpectFailed)
|
||||
}
|
||||
})
|
||||
.h1(|req: Request| async move {
|
||||
@ -112,7 +123,7 @@ async fn test_h1_expect() {
|
||||
let str = std::str::from_utf8(&buf).unwrap();
|
||||
assert_eq!(str, "expect body");
|
||||
|
||||
Ok::<_, ()>(Response::Ok().finish())
|
||||
Ok::<_, ()>(Response::ok())
|
||||
})
|
||||
.tcp()
|
||||
})
|
||||
@ -134,7 +145,7 @@ async fn test_h1_expect() {
|
||||
let response = request.send_body("expect body").await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::EXPECTATION_FAILED);
|
||||
|
||||
// test exepct would continue
|
||||
// test expect would continue
|
||||
let request = srv
|
||||
.request(http::Method::GET, srv.url("/"))
|
||||
.insert_header(("Expect", "100-continue"))
|
||||
|
@ -4,15 +4,20 @@ extern crate tls_openssl as openssl;
|
||||
|
||||
use std::io;
|
||||
|
||||
use actix_http::error::{ErrorBadRequest, PayloadError};
|
||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
||||
use actix_http::http::{Method, StatusCode, Version};
|
||||
use actix_http::HttpMessage;
|
||||
use actix_http::{body, Error, HttpService, Request, Response};
|
||||
use actix_http::{
|
||||
body::{Body, SizedStream},
|
||||
error::PayloadError,
|
||||
http::{
|
||||
header::{self, HeaderName, HeaderValue},
|
||||
Method, StatusCode, Version,
|
||||
},
|
||||
Error, HttpMessage, HttpService, Request, Response, ResponseError,
|
||||
};
|
||||
use actix_http_test::test_server;
|
||||
use actix_service::{fn_service, ServiceFactoryExt};
|
||||
use actix_utils::future::{err, ok, ready};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use derive_more::{Display, Error};
|
||||
use futures_core::Stream;
|
||||
use futures_util::stream::{once, StreamExt as _};
|
||||
use openssl::{
|
||||
@ -67,7 +72,7 @@ fn tls_config() -> SslAcceptor {
|
||||
async fn test_h2() -> io::Result<()> {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Error>(Response::Ok().finish()))
|
||||
.h2(|_| ok::<_, Error>(Response::ok()))
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
})
|
||||
@ -85,7 +90,7 @@ async fn test_h2_1() -> io::Result<()> {
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
ok::<_, Error>(Response::Ok().finish())
|
||||
ok::<_, Error>(Response::ok())
|
||||
})
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
@ -104,7 +109,7 @@ async fn test_h2_body() -> io::Result<()> {
|
||||
HttpService::build()
|
||||
.h2(|mut req: Request<_>| async move {
|
||||
let body = load_body(req.take_payload()).await?;
|
||||
Ok::<_, Error>(Response::Ok().body(body))
|
||||
Ok::<_, Error>(Response::ok().set_body(body))
|
||||
})
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
@ -182,7 +187,7 @@ async fn test_h2_headers() {
|
||||
let mut srv = test_server(move || {
|
||||
let data = data.clone();
|
||||
HttpService::build().h2(move |_| {
|
||||
let mut builder = Response::Ok();
|
||||
let mut builder = Response::build(StatusCode::OK);
|
||||
for idx in 0..90 {
|
||||
builder.insert_header(
|
||||
(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() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
})
|
||||
@ -259,7 +264,7 @@ async fn test_h2_body2() {
|
||||
async fn test_h2_head_empty() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
})
|
||||
@ -283,7 +288,7 @@ async fn test_h2_head_empty() {
|
||||
async fn test_h2_head_binary() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
})
|
||||
@ -306,7 +311,7 @@ async fn test_h2_head_binary() {
|
||||
async fn test_h2_head_binary2() {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
})
|
||||
@ -328,7 +333,7 @@ async fn test_h2_body_length() {
|
||||
.h2(|_| {
|
||||
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
||||
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())
|
||||
@ -351,7 +356,7 @@ async fn test_h2_body_chunked_explicit() {
|
||||
.h2(|_| {
|
||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
Response::build(StatusCode::OK)
|
||||
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||
.streaming(body),
|
||||
)
|
||||
@ -379,7 +384,7 @@ async fn test_h2_response_http_error_handling() {
|
||||
.h2(fn_service(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
Response::build(StatusCode::OK)
|
||||
.insert_header((header::CONTENT_TYPE, broken_header))
|
||||
.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"));
|
||||
}
|
||||
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[display(fmt = "error")]
|
||||
struct BadRequest;
|
||||
|
||||
impl ResponseError for BadRequest {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_h2_service_error() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| err::<Response, Error>(ErrorBadRequest("error")))
|
||||
.h2(|_| err::<Response<Body>, _>(BadRequest))
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
})
|
||||
@ -424,7 +439,7 @@ async fn test_h2_on_connect() {
|
||||
})
|
||||
.h2(|req: Request| {
|
||||
assert!(req.extensions().contains::<isize>());
|
||||
ok::<_, ()>(Response::Ok().finish())
|
||||
ok::<_, ()>(Response::ok())
|
||||
})
|
||||
.openssl(tls_config())
|
||||
.map_err(|_| ())
|
||||
|
@ -2,15 +2,20 @@
|
||||
|
||||
extern crate tls_rustls as rustls;
|
||||
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
||||
use actix_http::http::{Method, StatusCode, Version};
|
||||
use actix_http::{body, error, Error, HttpService, Request, Response};
|
||||
use actix_http::{
|
||||
body::{Body, SizedStream},
|
||||
error::PayloadError,
|
||||
http::{
|
||||
header::{self, HeaderName, HeaderValue},
|
||||
Method, StatusCode, Version,
|
||||
},
|
||||
Error, HttpService, Request, Response, ResponseError,
|
||||
};
|
||||
use actix_http_test::test_server;
|
||||
use actix_service::{fn_factory_with_config, fn_service};
|
||||
use actix_utils::future::{err, ok};
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use derive_more::{Display, Error};
|
||||
use futures_core::Stream;
|
||||
use futures_util::stream::{once, StreamExt as _};
|
||||
use rustls::{
|
||||
@ -51,7 +56,7 @@ fn tls_config() -> RustlsServerConfig {
|
||||
async fn test_h1() -> io::Result<()> {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, Error>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, Error>(Response::ok()))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
@ -65,7 +70,7 @@ async fn test_h1() -> io::Result<()> {
|
||||
async fn test_h2() -> io::Result<()> {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Error>(Response::Ok().finish()))
|
||||
.h2(|_| ok::<_, Error>(Response::ok()))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
@ -82,7 +87,7 @@ async fn test_h1_1() -> io::Result<()> {
|
||||
.h1(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), Version::HTTP_11);
|
||||
ok::<_, Error>(Response::Ok().finish())
|
||||
ok::<_, Error>(Response::ok())
|
||||
})
|
||||
.rustls(tls_config())
|
||||
})
|
||||
@ -100,7 +105,7 @@ async fn test_h2_1() -> io::Result<()> {
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
ok::<_, Error>(Response::Ok().finish())
|
||||
ok::<_, Error>(Response::ok())
|
||||
})
|
||||
.rustls(tls_config())
|
||||
})
|
||||
@ -118,7 +123,7 @@ async fn test_h2_body1() -> io::Result<()> {
|
||||
HttpService::build()
|
||||
.h2(|mut req: Request<_>| async move {
|
||||
let body = load_body(req.take_payload()).await?;
|
||||
Ok::<_, Error>(Response::Ok().body(body))
|
||||
Ok::<_, Error>(Response::ok().set_body(body))
|
||||
})
|
||||
.rustls(tls_config())
|
||||
})
|
||||
@ -194,7 +199,7 @@ async fn test_h2_headers() {
|
||||
let mut srv = test_server(move || {
|
||||
let data = data.clone();
|
||||
HttpService::build().h2(move |_| {
|
||||
let mut config = Response::Ok();
|
||||
let mut config = Response::build(StatusCode::OK);
|
||||
for idx in 0..90 {
|
||||
config.insert_header((
|
||||
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() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
@ -269,7 +274,7 @@ async fn test_h2_body2() {
|
||||
async fn test_h2_head_empty() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
@ -295,7 +300,7 @@ async fn test_h2_head_empty() {
|
||||
async fn test_h2_head_binary() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
@ -320,7 +325,7 @@ async fn test_h2_head_binary() {
|
||||
async fn test_h2_head_binary2() {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
@ -344,7 +349,7 @@ async fn test_h2_body_length() {
|
||||
.h2(|_| {
|
||||
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
||||
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())
|
||||
@ -366,7 +371,7 @@ async fn test_h2_body_chunked_explicit() {
|
||||
.h2(|_| {
|
||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
Response::build(StatusCode::OK)
|
||||
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||
.streaming(body),
|
||||
)
|
||||
@ -394,7 +399,7 @@ async fn test_h2_response_http_error_handling() {
|
||||
ok::<_, ()>(fn_service(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
Response::build(StatusCode::OK)
|
||||
.insert_header((http::header::CONTENT_TYPE, broken_header))
|
||||
.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"));
|
||||
}
|
||||
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[display(fmt = "error")]
|
||||
struct BadRequest;
|
||||
|
||||
impl ResponseError for BadRequest {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_h2_service_error() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| err::<Response, Error>(error::ErrorBadRequest("error")))
|
||||
.h2(|_| err::<Response<Body>, _>(BadRequest))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
@ -433,7 +448,7 @@ async fn test_h2_service_error() {
|
||||
async fn test_h1_service_error() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h1(|_| err::<Response, Error>(error::ErrorBadRequest("error")))
|
||||
.h1(|_| err::<Response<Body>, _>(BadRequest))
|
||||
.rustls(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
@ -2,20 +2,22 @@ use std::io::{Read, Write};
|
||||
use std::time::Duration;
|
||||
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_rt::time::sleep;
|
||||
use actix_service::fn_service;
|
||||
use actix_utils::future::{err, ok, ready};
|
||||
use bytes::Bytes;
|
||||
use derive_more::{Display, Error};
|
||||
use futures_util::stream::{once, StreamExt as _};
|
||||
use futures_util::FutureExt as _;
|
||||
use regex::Regex;
|
||||
|
||||
use actix_http::HttpMessage;
|
||||
use actix_http::{
|
||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
||||
};
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_h1() {
|
||||
let srv = test_server(|| {
|
||||
@ -25,7 +27,7 @@ async fn test_h1() {
|
||||
.client_disconnect(1000)
|
||||
.h1(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
ok::<_, ()>(Response::Ok().finish())
|
||||
ok::<_, ()>(Response::ok())
|
||||
})
|
||||
.tcp()
|
||||
})
|
||||
@ -45,7 +47,7 @@ async fn test_h1_2() {
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), http::Version::HTTP_11);
|
||||
ok::<_, ()>(Response::Ok().finish())
|
||||
ok::<_, ()>(Response::ok())
|
||||
})
|
||||
.tcp()
|
||||
})
|
||||
@ -55,6 +57,16 @@ async fn test_h1_2() {
|
||||
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]
|
||||
async fn test_expect_continue() {
|
||||
let srv = test_server(|| {
|
||||
@ -63,10 +75,10 @@ async fn test_expect_continue() {
|
||||
if req.head().uri.query() == Some("yes=") {
|
||||
ok(req)
|
||||
} else {
|
||||
err(error::ErrorPreconditionFailed("error"))
|
||||
err(ExpectFailed)
|
||||
}
|
||||
}))
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.finish(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -93,11 +105,11 @@ async fn test_expect_continue_h1() {
|
||||
if req.head().uri.query() == Some("yes=") {
|
||||
ok(req)
|
||||
} else {
|
||||
err(error::ErrorPreconditionFailed("error"))
|
||||
err(ExpectFailed)
|
||||
}
|
||||
})
|
||||
}))
|
||||
.h1(fn_service(|_| ok::<_, ()>(Response::Ok().finish())))
|
||||
.h1(fn_service(|_| ok::<_, ()>(Response::ok())))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -131,7 +143,9 @@ async fn test_chunked_payload() {
|
||||
})
|
||||
.fold(0usize, |acc, chunk| ready(acc + chunk.len()))
|
||||
.map(|req_size| {
|
||||
Ok::<_, Error>(Response::Ok().body(format!("size={}", req_size)))
|
||||
Ok::<_, Error>(
|
||||
Response::ok().set_body(format!("size={}", req_size)),
|
||||
)
|
||||
})
|
||||
}))
|
||||
.tcp()
|
||||
@ -176,7 +190,7 @@ async fn test_slow_request() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.client_timeout(100)
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.finish(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -192,7 +206,7 @@ async fn test_slow_request() {
|
||||
async fn test_http1_malformed_request() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -208,7 +222,7 @@ async fn test_http1_malformed_request() {
|
||||
async fn test_http1_keepalive() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -230,7 +244,7 @@ async fn test_http1_keepalive_timeout() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.keep_alive(1)
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -251,7 +265,7 @@ async fn test_http1_keepalive_timeout() {
|
||||
async fn test_http1_keepalive_close() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -272,7 +286,7 @@ async fn test_http1_keepalive_close() {
|
||||
async fn test_http10_keepalive_default_close() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -292,7 +306,7 @@ async fn test_http10_keepalive_default_close() {
|
||||
async fn test_http10_keepalive() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -320,7 +334,7 @@ async fn test_http1_keepalive_disabled() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.keep_alive(KeepAlive::Disabled)
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().finish()))
|
||||
.h1(|_| ok::<_, ()>(Response::ok()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -391,7 +405,7 @@ async fn test_h1_headers() {
|
||||
let mut srv = test_server(move || {
|
||||
let data = data.clone();
|
||||
HttpService::build().h1(move |_| {
|
||||
let mut builder = Response::Ok();
|
||||
let mut builder = Response::build(StatusCode::OK);
|
||||
for idx in 0..90 {
|
||||
builder.insert_header((
|
||||
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() {
|
||||
let mut srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -465,7 +479,7 @@ async fn test_h1_body() {
|
||||
async fn test_h1_head_empty() {
|
||||
let mut srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -490,7 +504,7 @@ async fn test_h1_head_empty() {
|
||||
async fn test_h1_head_binary() {
|
||||
let mut srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -515,7 +529,7 @@ async fn test_h1_head_binary() {
|
||||
async fn test_h1_head_binary2() {
|
||||
let srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -539,7 +553,7 @@ async fn test_h1_body_length() {
|
||||
.h1(|_| {
|
||||
let body = once(ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.tcp()
|
||||
@ -561,7 +575,7 @@ async fn test_h1_body_chunked_explicit() {
|
||||
.h1(|_| {
|
||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
Response::build(StatusCode::OK)
|
||||
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||
.streaming(body),
|
||||
)
|
||||
@ -595,7 +609,7 @@ async fn test_h1_body_chunked_implicit() {
|
||||
HttpService::build()
|
||||
.h1(|_| {
|
||||
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(Response::Ok().streaming(body))
|
||||
ok::<_, ()>(Response::build(StatusCode::OK).streaming(body))
|
||||
})
|
||||
.tcp()
|
||||
})
|
||||
@ -625,7 +639,7 @@ async fn test_h1_response_http_error_handling() {
|
||||
.h1(fn_service(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
Response::build(StatusCode::OK)
|
||||
.insert_header((http::header::CONTENT_TYPE, broken_header))
|
||||
.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"));
|
||||
}
|
||||
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[display(fmt = "error")]
|
||||
struct BadRequest;
|
||||
|
||||
impl ResponseError for BadRequest {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_h1_service_error() {
|
||||
let mut srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.h1(|_| err::<Response, _>(error::ErrorBadRequest("error")))
|
||||
.h1(|_| err::<Response<Body>, _>(BadRequest))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
@ -668,7 +692,7 @@ async fn test_h1_on_connect() {
|
||||
})
|
||||
.h1(|req: Request| {
|
||||
assert!(req.extensions().contains::<isize>());
|
||||
ok::<_, ()>(Response::Ok().finish())
|
||||
ok::<_, ()>(Response::ok())
|
||||
})
|
||||
.tcp()
|
||||
})
|
||||
|
@ -1,193 +1,163 @@
|
||||
use std::cell::Cell;
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
use std::{
|
||||
cell::Cell,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
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_service::{fn_factory, Service};
|
||||
use actix_utils::future;
|
||||
use bytes::Bytes;
|
||||
use futures_core::future::LocalBoxFuture;
|
||||
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<T> WsService<T> {
|
||||
impl WsService {
|
||||
fn new() -> Self {
|
||||
WsService(Arc::new(Mutex::new((PhantomData, Cell::new(false)))))
|
||||
WsService(Cell::new(false))
|
||||
}
|
||||
|
||||
fn set_polled(&self) {
|
||||
*self.0.lock().unwrap().1.get_mut() = true;
|
||||
self.0.set(true);
|
||||
}
|
||||
|
||||
fn was_polled(&self) -> bool {
|
||||
self.0.lock().unwrap().1.get()
|
||||
self.0.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for WsService<T> {
|
||||
fn clone(&self) -> Self {
|
||||
WsService(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service<(Request, Framed<T, h1::Codec>)> for WsService<T>
|
||||
impl<T> Service<(Request, Framed<T, h1::Codec>)> for WsService
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||
{
|
||||
type Response = ();
|
||||
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();
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&self, (req, mut framed): (Request, Framed<T, h1::Codec>)) -> Self::Future {
|
||||
let fut = async move {
|
||||
let res = ws::handshake(req.head()).unwrap().message_body(());
|
||||
assert!(self.was_polled());
|
||||
|
||||
framed
|
||||
.send((res, body::BodySize::None).into())
|
||||
.await
|
||||
.unwrap();
|
||||
Box::pin(async move {
|
||||
let res = ws::handshake(req.head())?.message_body(())?;
|
||||
|
||||
Dispatcher::with(framed.replace_codec(ws::Codec::new()), service)
|
||||
.await
|
||||
.map_err(|_| panic!())
|
||||
};
|
||||
framed.send((res, BodySize::None).into()).await?;
|
||||
|
||||
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 {
|
||||
ws::Frame::Ping(msg) => ws::Message::Pong(msg),
|
||||
ws::Frame::Text(text) => {
|
||||
ws::Message::Text(String::from_utf8_lossy(&text).into_owned().into())
|
||||
Frame::Ping(msg) => Message::Pong(msg),
|
||||
Frame::Text(text) => {
|
||||
Message::Text(String::from_utf8_lossy(&text).into_owned().into())
|
||||
}
|
||||
ws::Frame::Binary(bin) => ws::Message::Binary(bin),
|
||||
ws::Frame::Continuation(item) => ws::Message::Continuation(item),
|
||||
ws::Frame::Close(reason) => ws::Message::Close(reason),
|
||||
_ => panic!(),
|
||||
Frame::Binary(bin) => Message::Binary(bin),
|
||||
Frame::Continuation(item) => Message::Continuation(item),
|
||||
Frame::Close(reason) => Message::Close(reason),
|
||||
_ => return Err(Error::from(ws::ProtocolError::BadOpCode)),
|
||||
};
|
||||
|
||||
Ok(msg)
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_simple() {
|
||||
let ws_service = WsService::new();
|
||||
let mut srv = test_server({
|
||||
let ws_service = ws_service.clone();
|
||||
move || {
|
||||
let ws_service = ws_service.clone();
|
||||
HttpService::build()
|
||||
.upgrade(fn_factory(move || future::ok::<_, ()>(ws_service.clone())))
|
||||
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
|
||||
.tcp()
|
||||
}
|
||||
let mut srv = test_server(|| {
|
||||
HttpService::build()
|
||||
.upgrade(fn_factory(|| async { Ok::<_, ()>(WsService::new()) }))
|
||||
.finish(|_| async { Ok::<_, ()>(Response::not_found()) })
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
|
||||
// client service
|
||||
let mut framed = srv.ws().await.unwrap();
|
||||
framed.send(ws::Message::Text("text".into())).await.unwrap();
|
||||
let (item, mut framed) = framed.into_future().await;
|
||||
assert_eq!(
|
||||
item.unwrap().unwrap(),
|
||||
ws::Frame::Text(Bytes::from_static(b"text"))
|
||||
);
|
||||
framed.send(Message::Text("text".into())).await.unwrap();
|
||||
|
||||
let item = framed.next().await.unwrap().unwrap();
|
||||
assert_eq!(item, 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
|
||||
.send(ws::Message::Binary("text".into()))
|
||||
.send(Message::Continuation(Item::FirstText("text".into())))
|
||||
.await
|
||||
.unwrap();
|
||||
let (item, mut framed) = framed.into_future().await;
|
||||
let item = framed.next().await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
item.unwrap().unwrap(),
|
||||
ws::Frame::Binary(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")))
|
||||
item,
|
||||
Frame::Continuation(Item::FirstText(Bytes::from_static(b"text")))
|
||||
);
|
||||
|
||||
assert!(framed
|
||||
.send(ws::Message::Continuation(ws::Item::FirstText(
|
||||
"text".into()
|
||||
)))
|
||||
.send(Message::Continuation(Item::FirstText("text".into())))
|
||||
.await
|
||||
.is_err());
|
||||
assert!(framed
|
||||
.send(ws::Message::Continuation(ws::Item::FirstBinary(
|
||||
"text".into()
|
||||
)))
|
||||
.send(Message::Continuation(Item::FirstBinary("text".into())))
|
||||
.await
|
||||
.is_err());
|
||||
|
||||
framed
|
||||
.send(ws::Message::Continuation(ws::Item::Continue("text".into())))
|
||||
.send(Message::Continuation(Item::Continue("text".into())))
|
||||
.await
|
||||
.unwrap();
|
||||
let (item, mut framed) = framed.into_future().await;
|
||||
let item = framed.next().await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
item.unwrap().unwrap(),
|
||||
ws::Frame::Continuation(ws::Item::Continue(Bytes::from_static(b"text")))
|
||||
item,
|
||||
Frame::Continuation(Item::Continue(Bytes::from_static(b"text")))
|
||||
);
|
||||
|
||||
framed
|
||||
.send(ws::Message::Continuation(ws::Item::Last("text".into())))
|
||||
.send(Message::Continuation(Item::Last("text".into())))
|
||||
.await
|
||||
.unwrap();
|
||||
let (item, mut framed) = framed.into_future().await;
|
||||
let item = framed.next().await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
item.unwrap().unwrap(),
|
||||
ws::Frame::Continuation(ws::Item::Last(Bytes::from_static(b"text")))
|
||||
item,
|
||||
Frame::Continuation(Item::Last(Bytes::from_static(b"text")))
|
||||
);
|
||||
|
||||
assert!(framed
|
||||
.send(ws::Message::Continuation(ws::Item::Continue("text".into())))
|
||||
.send(Message::Continuation(Item::Continue("text".into())))
|
||||
.await
|
||||
.is_err());
|
||||
|
||||
assert!(framed
|
||||
.send(ws::Message::Continuation(ws::Item::Last("text".into())))
|
||||
.send(Message::Continuation(Item::Last("text".into())))
|
||||
.await
|
||||
.is_err());
|
||||
|
||||
framed
|
||||
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
|
||||
.send(Message::Close(Some(CloseCode::Normal.into())))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (item, _framed) = framed.into_future().await;
|
||||
assert_eq!(
|
||||
item.unwrap().unwrap(),
|
||||
ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
|
||||
);
|
||||
|
||||
assert!(ws_service.was_polled());
|
||||
let item = framed.next().await.unwrap().unwrap();
|
||||
assert_eq!(item, Frame::Close(Some(CloseCode::Normal.into())));
|
||||
}
|
||||
|
@ -16,8 +16,8 @@ name = "actix_multipart"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "4.0.0-beta.5", default-features = false }
|
||||
actix-utils = "3.0.0-beta.4"
|
||||
actix-web = { version = "4.0.0-beta.6", default-features = false }
|
||||
actix-utils = "3.0.0"
|
||||
|
||||
bytes = "1"
|
||||
derive_more = "0.99.5"
|
||||
@ -31,6 +31,6 @@ twoway = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "2.2"
|
||||
actix-http = "3.0.0-beta.5"
|
||||
actix-http = "3.0.0-beta.6"
|
||||
tokio = { version = "1", features = ["sync"] }
|
||||
tokio-stream = "0.1"
|
||||
|
@ -45,11 +45,10 @@ impl ResponseError for MultipartError {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use actix_web::HttpResponse;
|
||||
|
||||
#[test]
|
||||
fn test_multipart_error() {
|
||||
let resp: HttpResponse = MultipartError::Boundary.error_response();
|
||||
let resp = MultipartError::Boundary.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
@ -3,6 +3,10 @@
|
||||
## 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
|
||||
* Move integration testing structs from `actix-web`. [#2112]
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-test"
|
||||
version = "0.1.0-beta.1"
|
||||
version = "0.1.0-beta.2"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Rob Ede <robjtede@icloud.com>",
|
||||
@ -19,14 +19,14 @@ rustls = ["tls-rustls", "actix-http/rustls"]
|
||||
openssl = ["tls-openssl", "actix-http/openssl"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.4.0-beta.1"
|
||||
actix-http = { version = "3.0.0-beta.5", features = ["cookies"] }
|
||||
actix-codec = "0.4.0"
|
||||
actix-http = "3.0.0-beta.6"
|
||||
actix-http-test = { version = "3.0.0-beta.4", features = [] }
|
||||
actix-service = "2.0.0-beta.4"
|
||||
actix-utils = "3.0.0-beta.2"
|
||||
actix-web = { version = "4.0.0-beta.5", default-features = false, features = ["cookies"] }
|
||||
actix-service = "2.0.0"
|
||||
actix-utils = "3.0.0"
|
||||
actix-web = { version = "4.0.0-beta.6", default-features = false, features = ["cookies"] }
|
||||
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-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;
|
||||
use actix_http::{
|
||||
http::{HeaderMap, Method},
|
||||
ws, HttpService, Request,
|
||||
ws, HttpService, Request, Response,
|
||||
};
|
||||
use actix_service::{map_config, IntoServiceFactory, ServiceFactory};
|
||||
use actix_web::{
|
||||
dev::{AppConfig, MessageBody, Server, Service},
|
||||
rt, web, Error, HttpResponse,
|
||||
rt, web, Error,
|
||||
};
|
||||
use awc::{error::PayloadError, Client, ClientRequest, ClientResponse, Connector};
|
||||
use futures_core::Stream;
|
||||
@ -83,9 +83,10 @@ where
|
||||
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<HttpResponse<B>> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
start_with(TestServerConfig::default(), factory)
|
||||
}
|
||||
@ -122,9 +123,10 @@ where
|
||||
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
||||
S::Error: Into<Error> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<HttpResponse<B>> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
|
@ -17,9 +17,9 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = { version = "0.11.0-beta.3", default-features = false }
|
||||
actix-codec = "0.4.0-beta.1"
|
||||
actix-http = "3.0.0-beta.5"
|
||||
actix-web = { version = "4.0.0-beta.5", default-features = false }
|
||||
actix-codec = "0.4.0"
|
||||
actix-http = "3.0.0-beta.6"
|
||||
actix-web = { version = "4.0.0-beta.6", default-features = false }
|
||||
|
||||
bytes = "1"
|
||||
bytestring = "1"
|
||||
@ -29,8 +29,8 @@ tokio = { version = "1", features = ["sync"] }
|
||||
|
||||
[dev-dependencies]
|
||||
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"
|
||||
futures-util = { version = "0.3.7", default-features = false }
|
||||
|
@ -22,9 +22,9 @@ use actix_http::{
|
||||
http::HeaderValue,
|
||||
ws::{hash_key, Codec},
|
||||
};
|
||||
use actix_web::dev::HttpResponseBuilder;
|
||||
use actix_web::error::{Error, PayloadError};
|
||||
use actix_web::http::{header, Method, StatusCode};
|
||||
use actix_web::HttpResponseBuilder;
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use bytestring::ByteString;
|
||||
|
@ -20,9 +20,9 @@ proc-macro2 = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "2.2"
|
||||
actix-test = "0.1.0-beta.1"
|
||||
actix-utils = "3.0.0-beta.4"
|
||||
actix-web = "4.0.0-beta.5"
|
||||
actix-test = "0.1.0-beta.2"
|
||||
actix-utils = "3.0.0"
|
||||
actix-web = "4.0.0-beta.6"
|
||||
|
||||
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
|
||||
trybuild = "1"
|
||||
|
@ -1,10 +1,15 @@
|
||||
use std::future::Future;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_utils::future;
|
||||
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
|
||||
use actix_web::http::header::{HeaderName, HeaderValue};
|
||||
use actix_web::{http, web::Path, App, Error, HttpResponse, Responder};
|
||||
use actix_utils::future::{ok, Ready};
|
||||
use actix_web::{
|
||||
dev::{Service, ServiceRequest, ServiceResponse, Transform},
|
||||
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 futures_core::future::LocalBoxFuture;
|
||||
|
||||
@ -56,26 +61,26 @@ async fn trace_test() -> impl Responder {
|
||||
|
||||
#[get("/test")]
|
||||
fn auto_async() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
ok(HttpResponse::Ok().finish())
|
||||
}
|
||||
|
||||
#[get("/test")]
|
||||
fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
ok(HttpResponse::Ok().finish())
|
||||
}
|
||||
|
||||
#[put("/test/{param}")]
|
||||
async fn put_param_test(_: Path<String>) -> impl Responder {
|
||||
async fn put_param_test(_: web::Path<String>) -> impl Responder {
|
||||
HttpResponse::Created()
|
||||
}
|
||||
|
||||
#[delete("/test/{param}")]
|
||||
async fn delete_param_test(_: Path<String>) -> impl Responder {
|
||||
async fn delete_param_test(_: web::Path<String>) -> impl Responder {
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[get("/test/{param}")]
|
||||
async fn get_param_test(_: Path<String>) -> impl Responder {
|
||||
async fn get_param_test(_: web::Path<String>) -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
@ -103,10 +108,10 @@ where
|
||||
type Error = Error;
|
||||
type Transform = ChangeStatusCodeMiddleware<S>;
|
||||
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 {
|
||||
future::ok(ChangeStatusCodeMiddleware { service })
|
||||
ok(ChangeStatusCodeMiddleware { service })
|
||||
}
|
||||
}
|
||||
|
||||
@ -124,9 +129,7 @@ where
|
||||
type Error = Error;
|
||||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||
|
||||
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
self.service.poll_ready(cx)
|
||||
}
|
||||
actix_web::dev::forward_ready!(service);
|
||||
|
||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||
let fut = self.service.call(req);
|
||||
@ -143,7 +146,8 @@ where
|
||||
}
|
||||
|
||||
#[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()
|
||||
}
|
||||
|
||||
@ -257,6 +261,10 @@ async fn test_wrap() {
|
||||
let srv = actix_test::start(|| App::new().service(get_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"));
|
||||
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]
|
||||
fn compile_macros() {
|
||||
let t = trybuild::TestCases::new();
|
||||
@ -12,11 +13,3 @@ fn compile_macros() {
|
||||
|
||||
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
|
||||
|
||||
|
||||
## 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
|
||||
### Added
|
||||
* Add `Client::headers` to get default mut reference of `HeaderMap` of client object. [#2114]
|
||||
|
@ -1,22 +1,20 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "3.0.0-beta.4"
|
||||
version = "3.0.0-beta.5"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"fakeshadow <24548779@qq.com>",
|
||||
]
|
||||
description = "Async HTTP and WebSocket client library built on the Actix ecosystem"
|
||||
readme = "README.md"
|
||||
keywords = ["actix", "http", "framework", "async", "web"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
documentation = "https://docs.rs/awc/"
|
||||
categories = [
|
||||
"network-programming",
|
||||
"asynchronous",
|
||||
"web-programming::http-client",
|
||||
"web-programming::websocket",
|
||||
]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2018"
|
||||
|
||||
@ -41,19 +39,20 @@ rustls = ["tls-rustls", "actix-http/rustls"]
|
||||
compress = ["actix-http/compress"]
|
||||
|
||||
# cookie parsing and cookie jar
|
||||
cookies = ["actix-http/cookies"]
|
||||
cookies = ["cookie"]
|
||||
|
||||
# trust-dns as dns resolver
|
||||
trust-dns = ["actix-http/trust-dns"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.4.0-beta.1"
|
||||
actix-service = "2.0.0-beta.4"
|
||||
actix-http = "3.0.0-beta.5"
|
||||
actix-codec = "0.4.0"
|
||||
actix-service = "2.0.0"
|
||||
actix-http = "3.0.0-beta.6"
|
||||
actix-rt = { version = "2.1", default-features = false }
|
||||
|
||||
base64 = "0.13"
|
||||
bytes = "1"
|
||||
cookie = { version = "0.15", features = ["percent-encode"], optional = true }
|
||||
derive_more = "0.99.5"
|
||||
futures-core = { version = "0.3.7", default-features = false }
|
||||
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"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "4.0.0-beta.5", features = ["openssl"] }
|
||||
actix-http = { version = "3.0.0-beta.5", features = ["openssl"] }
|
||||
actix-web = { version = "4.0.0-beta.6", features = ["openssl"] }
|
||||
actix-http = { version = "3.0.0-beta.6", 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-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"
|
||||
env_logger = "0.8"
|
||||
|
@ -93,12 +93,11 @@
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
|
||||
use std::convert::TryFrom;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
use std::{convert::TryFrom, rc::Rc, time::Duration};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
pub use actix_http::cookie;
|
||||
pub use cookie;
|
||||
|
||||
pub use actix_http::{client::Connector, http};
|
||||
|
||||
use actix_http::{
|
||||
|
@ -8,14 +8,14 @@ use futures_core::Stream;
|
||||
use serde::Serialize;
|
||||
|
||||
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::{
|
||||
uri, ConnectionType, Error as HttpError, HeaderMap, HeaderValue, Method, Uri, Version,
|
||||
};
|
||||
use actix_http::{Error, RequestHead};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use crate::cookie::{Cookie, CookieJar};
|
||||
use crate::error::{FreezeRequestError, InvalidUrl};
|
||||
use crate::frozen::FrozenClientRequest;
|
||||
use crate::sender::{PrepForSendingError, RequestSender, SendClientRequest};
|
||||
@ -271,7 +271,7 @@ impl ClientRequest {
|
||||
/// async fn main() {
|
||||
/// let resp = awc::Client::new().get("https://www.rust-lang.org")
|
||||
/// .cookie(
|
||||
/// awc::http::Cookie::build("name", "value")
|
||||
/// awc::cookie::Cookie::build("name", "value")
|
||||
/// .domain("www.rust-lang.org")
|
||||
/// .path("/")
|
||||
/// .secure(true)
|
||||
@ -311,34 +311,6 @@ impl ClientRequest {
|
||||
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
|
||||
pub fn query<T: Serialize>(
|
||||
mut self,
|
||||
@ -494,7 +466,7 @@ impl ClientRequest {
|
||||
let cookie: String = jar
|
||||
.delta()
|
||||
// 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<_>>()
|
||||
.join("; ");
|
||||
|
||||
|
@ -20,8 +20,7 @@ use futures_core::{ready, Stream};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use actix_http::{cookie::Cookie, error::CookieParseError};
|
||||
|
||||
use crate::cookie::{Cookie, ParseError as CookieParseError};
|
||||
use crate::error::JsonPayloadError;
|
||||
|
||||
/// Client Response
|
||||
@ -80,24 +79,6 @@ impl<S> HttpMessage for ClientResponse<S> {
|
||||
fn extensions_mut(&self) -> RefMut<'_, Extensions> {
|
||||
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> {
|
||||
@ -180,6 +161,37 @@ impl<S> ClientResponse<S> {
|
||||
self.timeout = ResponseTimeout::Disabled(timeout);
|
||||
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>
|
||||
|
@ -1,6 +1,6 @@
|
||||
use std::{
|
||||
future::Future,
|
||||
net,
|
||||
io, net,
|
||||
pin::Pin,
|
||||
rc::Rc,
|
||||
task::{Context, Poll},
|
||||
@ -209,7 +209,8 @@ impl RequestSender {
|
||||
) -> SendClientRequest {
|
||||
let body = match serde_json::to_string(value) {
|
||||
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") {
|
||||
@ -235,7 +236,8 @@ impl RequestSender {
|
||||
) -> SendClientRequest {
|
||||
let body = match serde_urlencoded::to_string(value) {
|
||||
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
|
||||
|
@ -1,14 +1,11 @@
|
||||
//! Test helpers for actix http client to use during testing.
|
||||
use actix_http::http::header::IntoHeaderPair;
|
||||
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 bytes::Bytes;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use crate::cookie::{Cookie, CookieJar};
|
||||
use crate::ClientResponse;
|
||||
|
||||
/// Test `ClientResponse` builder
|
||||
@ -92,6 +89,8 @@ impl TestResponse {
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
for cookie in self.cookies.delta() {
|
||||
use actix_http::http::header::{self, HeaderValue};
|
||||
|
||||
head.headers.insert(
|
||||
header::SET_COOKIE,
|
||||
HeaderValue::from_str(&cookie.encoded().to_string()).unwrap(),
|
||||
|
@ -31,8 +31,6 @@ use std::net::SocketAddr;
|
||||
use std::{fmt, str};
|
||||
|
||||
use actix_codec::Framed;
|
||||
#[cfg(feature = "cookies")]
|
||||
use actix_http::cookie::{Cookie, CookieJar};
|
||||
use actix_http::{ws, Payload, RequestHead};
|
||||
use actix_rt::time::timeout;
|
||||
use actix_service::Service;
|
||||
@ -40,6 +38,8 @@ use actix_service::Service;
|
||||
pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message};
|
||||
|
||||
use crate::connect::{BoxedSocket, ConnectRequest};
|
||||
#[cfg(feature = "cookies")]
|
||||
use crate::cookie::{Cookie, CookieJar};
|
||||
use crate::error::{InvalidUrl, SendRequestError, WsClientError};
|
||||
use crate::http::header::{self, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION};
|
||||
use crate::http::{ConnectionType, Error as HttpError, Method, StatusCode, Uri, Version};
|
||||
@ -280,7 +280,7 @@ impl WebsocketsRequest {
|
||||
let cookie: String = jar
|
||||
.delta()
|
||||
// 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<_>>()
|
||||
.join("; ");
|
||||
|
||||
|
@ -8,6 +8,7 @@ use std::time::Duration;
|
||||
use actix_utils::future::ok;
|
||||
use brotli2::write::BrotliEncoder;
|
||||
use bytes::Bytes;
|
||||
use cookie::Cookie;
|
||||
use flate2::read::GzDecoder;
|
||||
use flate2::write::GzEncoder;
|
||||
use flate2::Compression;
|
||||
@ -19,12 +20,12 @@ use actix_http::{
|
||||
HttpService,
|
||||
};
|
||||
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::{
|
||||
dev::{AppConfig, BodyEncoding},
|
||||
http::{header, Cookie},
|
||||
http::header,
|
||||
middleware::Compress,
|
||||
web, App, Error, HttpMessage, HttpRequest, HttpResponse,
|
||||
web, App, Error, HttpRequest, HttpResponse,
|
||||
};
|
||||
use awc::error::{JsonPayloadError, PayloadError, SendRequestError};
|
||||
|
||||
@ -238,7 +239,7 @@ async fn test_connection_reuse() {
|
||||
|
||||
let srv = test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
@ -275,7 +276,7 @@ async fn test_connection_force_close() {
|
||||
|
||||
let srv = test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
@ -312,7 +313,7 @@ async fn test_connection_server_close() {
|
||||
|
||||
let srv = test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
@ -352,7 +353,7 @@ async fn test_connection_wait_queue() {
|
||||
|
||||
let srv = test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
@ -400,7 +401,7 @@ async fn test_connection_wait_queue_force_close() {
|
||||
|
||||
let srv = test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
|
@ -12,7 +12,7 @@ use std::{
|
||||
|
||||
use actix_http::HttpService;
|
||||
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_web::{dev::AppConfig, http::Version, web, App, HttpResponse};
|
||||
use rustls::internal::pemfile::{certs, pkcs8_private_keys};
|
||||
@ -57,7 +57,7 @@ async fn test_connection_reuse_h2() {
|
||||
|
||||
let srv = test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
|
@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use actix_http::HttpService;
|
||||
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_web::http::Version;
|
||||
use actix_web::{dev::AppConfig, web, App, HttpResponse};
|
||||
@ -48,7 +48,7 @@ async fn test_connection_reuse_h2() {
|
||||
|
||||
let srv = test_server(move || {
|
||||
let num2 = num2.clone();
|
||||
pipeline_factory(move |io| {
|
||||
fn_service(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
ok(io)
|
||||
})
|
||||
|
@ -36,7 +36,7 @@ async fn test_simple() {
|
||||
ws::Dispatcher::with(framed, ws_service).await
|
||||
}
|
||||
})
|
||||
.finish(|_| ok::<_, Error>(Response::NotFound()))
|
||||
.finish(|_| ok::<_, Error>(Response::not_found()))
|
||||
.tcp()
|
||||
})
|
||||
.await;
|
||||
|
@ -1,4 +1,4 @@
|
||||
use actix_web::{test, web, App, HttpResponse};
|
||||
use actix_web::{web, App, HttpResponse};
|
||||
use awc::Client;
|
||||
use criterion::{criterion_group, criterion_main, Criterion};
|
||||
use futures_util::future::join_all;
|
||||
|
@ -1,20 +1,23 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::{Extensions, Request, Response};
|
||||
use actix_http::{Extensions, Request};
|
||||
use actix_router::{Path, ResourceDef, Router, Url};
|
||||
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
|
||||
use actix_service::{fn_service, Service, ServiceFactory};
|
||||
use futures_core::future::LocalBoxFuture;
|
||||
use futures_util::future::join_all;
|
||||
|
||||
use crate::config::{AppConfig, AppService};
|
||||
use crate::data::FnDataFactory;
|
||||
use crate::error::Error;
|
||||
use crate::guard::Guard;
|
||||
use crate::request::{HttpRequest, HttpRequestPool};
|
||||
use crate::rmap::ResourceMap;
|
||||
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
|
||||
use crate::{
|
||||
config::{AppConfig, AppService},
|
||||
HttpResponse,
|
||||
};
|
||||
|
||||
type Guards = Vec<Box<dyn Guard>>;
|
||||
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
|
||||
@ -64,7 +67,7 @@ where
|
||||
// if no user defined default service exists.
|
||||
let default = self.default.clone().unwrap_or_else(|| {
|
||||
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 {
|
||||
rmap,
|
||||
config,
|
||||
// TODO: AppConfig can be used to pass user defined HttpRequestPool
|
||||
// capacity.
|
||||
// TODO: AppConfig can be used to pass user defined HttpRequestPool capacity.
|
||||
pool: HttpRequestPool::default(),
|
||||
})
|
||||
}
|
||||
|
13
src/data.rs
13
src/data.rs
@ -1,16 +1,13 @@
|
||||
use std::any::type_name;
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
use std::{any::type_name, ops::Deref, sync::Arc};
|
||||
|
||||
use actix_http::error::{Error, ErrorInternalServerError};
|
||||
use actix_http::Extensions;
|
||||
use actix_http::{error::Error, Extensions};
|
||||
use actix_utils::future::{err, ok, Ready};
|
||||
use futures_core::future::LocalBoxFuture;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::dev::Payload;
|
||||
use crate::extract::FromRequest;
|
||||
use crate::request::HttpRequest;
|
||||
use crate::{
|
||||
dev::Payload, error::ErrorInternalServerError, extract::FromRequest, request::HttpRequest,
|
||||
};
|
||||
|
||||
/// Data factory.
|
||||
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::*;
|
||||
use derive_more::{Display, Error, From};
|
||||
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 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.
|
||||
#[derive(Debug, PartialEq, Display, From)]
|
||||
#[derive(Debug, PartialEq, Display, Error, From)]
|
||||
#[non_exhaustive]
|
||||
pub enum UrlGenerationError {
|
||||
/// Resource not found
|
||||
#[display(fmt = "Resource not found")]
|
||||
@ -23,13 +35,11 @@ pub enum UrlGenerationError {
|
||||
ParseError(UrlParseError),
|
||||
}
|
||||
|
||||
impl std::error::Error for UrlGenerationError {}
|
||||
|
||||
/// `InternalServerError` for `UrlGeneratorError`
|
||||
impl ResponseError for UrlGenerationError {}
|
||||
|
||||
/// A set of errors that can occur during parsing urlencoded payloads
|
||||
#[derive(Debug, Display, Error, From)]
|
||||
#[non_exhaustive]
|
||||
pub enum UrlencodedError {
|
||||
/// Can not decode chunked transfer encoding.
|
||||
#[display(fmt = "Can not decode chunked transfer encoding.")]
|
||||
@ -52,64 +62,84 @@ pub enum UrlencodedError {
|
||||
ContentType,
|
||||
|
||||
/// Parse error.
|
||||
#[display(fmt = "Parse error.")]
|
||||
Parse,
|
||||
#[display(fmt = "Parse error: {}.", _0)]
|
||||
Parse(FormDeError),
|
||||
|
||||
/// Encoding error.
|
||||
#[display(fmt = "Encoding error.")]
|
||||
Encoding,
|
||||
|
||||
/// Serialize error.
|
||||
#[display(fmt = "Serialize error: {}.", _0)]
|
||||
Serialize(FormError),
|
||||
|
||||
/// Payload error.
|
||||
#[display(fmt = "Error that occur during reading payload: {}.", _0)]
|
||||
Payload(PayloadError),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `UrlencodedError`
|
||||
impl ResponseError for UrlencodedError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match *self {
|
||||
UrlencodedError::Overflow { .. } => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
UrlencodedError::UnknownLength => StatusCode::LENGTH_REQUIRED,
|
||||
match self {
|
||||
Self::Overflow { .. } => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
Self::UnknownLength => StatusCode::LENGTH_REQUIRED,
|
||||
Self::Payload(err) => err.status_code(),
|
||||
_ => StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of errors that can occur during parsing json payloads
|
||||
#[derive(Debug, Display, From)]
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum JsonPayloadError {
|
||||
/// Payload size is bigger than allowed. (default: 32kB)
|
||||
#[display(fmt = "Json payload size is bigger than allowed")]
|
||||
Overflow,
|
||||
|
||||
/// Content type error
|
||||
#[display(fmt = "Content type error")]
|
||||
ContentType,
|
||||
|
||||
/// Deserialize error
|
||||
#[display(fmt = "Json deserialize error: {}", _0)]
|
||||
Deserialize(JsonError),
|
||||
|
||||
/// Serialize error
|
||||
#[display(fmt = "Json serialize error: {}", _0)]
|
||||
Serialize(JsonError),
|
||||
|
||||
/// Payload error
|
||||
#[display(fmt = "Error that occur during reading payload: {}", _0)]
|
||||
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 {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
JsonPayloadError::Overflow => HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE),
|
||||
_ => HttpResponse::new(StatusCode::BAD_REQUEST),
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
Self::Overflow => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
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
|
||||
#[derive(Debug, Display, From)]
|
||||
#[derive(Debug, Display, Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum PathError {
|
||||
/// Deserialize error
|
||||
#[display(fmt = "Path deserialize error: {}", _0)]
|
||||
Deserialize(serde::de::value::Error),
|
||||
}
|
||||
|
||||
impl std::error::Error for PathError {}
|
||||
|
||||
/// Return `BadRequest` for `PathError`
|
||||
impl ResponseError for PathError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
@ -119,13 +149,13 @@ impl ResponseError for PathError {
|
||||
|
||||
/// A set of errors that can occur during parsing query strings.
|
||||
#[derive(Debug, Display, Error, From)]
|
||||
#[non_exhaustive]
|
||||
pub enum QueryPayloadError {
|
||||
/// Query deserialize error.
|
||||
#[display(fmt = "Query deserialize error: {}", _0)]
|
||||
Deserialize(serde::de::value::Error),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `QueryPayloadError`
|
||||
impl ResponseError for QueryPayloadError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
@ -133,26 +163,26 @@ impl ResponseError for QueryPayloadError {
|
||||
}
|
||||
|
||||
/// Error type returned when reading body as lines.
|
||||
#[derive(From, Display, Debug)]
|
||||
#[derive(Debug, Display, Error, From)]
|
||||
#[non_exhaustive]
|
||||
pub enum ReadlinesError {
|
||||
/// Error when decoding a line.
|
||||
#[display(fmt = "Encoding error")]
|
||||
/// Payload size is bigger than allowed. (default: 256kB)
|
||||
EncodingError,
|
||||
|
||||
/// Payload error.
|
||||
#[display(fmt = "Error that occur during reading payload: {}", _0)]
|
||||
Payload(PayloadError),
|
||||
|
||||
/// Line limit exceeded.
|
||||
#[display(fmt = "Line limit exceeded")]
|
||||
LimitOverflow,
|
||||
|
||||
/// ContentType error.
|
||||
#[display(fmt = "Content-type error")]
|
||||
ContentTypeError(ContentTypeError),
|
||||
}
|
||||
|
||||
impl std::error::Error for ReadlinesError {}
|
||||
|
||||
/// Return `BadRequest` for `ReadlinesError`
|
||||
impl ResponseError for ReadlinesError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match *self {
|
||||
@ -168,26 +198,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_urlencoded_error() {
|
||||
let resp: HttpResponse =
|
||||
UrlencodedError::Overflow { size: 0, limit: 0 }.error_response();
|
||||
let resp = UrlencodedError::Overflow { size: 0, limit: 0 }.error_response();
|
||||
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);
|
||||
let resp: HttpResponse = UrlencodedError::ContentType.error_response();
|
||||
let resp = UrlencodedError::ContentType.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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);
|
||||
let resp: HttpResponse = JsonPayloadError::ContentType.error_response();
|
||||
let resp = JsonPayloadError::ContentType.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_query_payload_error() {
|
||||
let resp: HttpResponse = QueryPayloadError::Deserialize(
|
||||
let resp = QueryPayloadError::Deserialize(
|
||||
serde_urlencoded::from_str::<i32>("bad query").unwrap_err(),
|
||||
)
|
||||
.error_response();
|
||||
@ -196,9 +225,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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);
|
||||
let resp: HttpResponse = ReadlinesError::EncodingError.error_response();
|
||||
let resp = ReadlinesError::EncodingError.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
@ -26,6 +26,8 @@
|
||||
//! ```
|
||||
#![allow(non_snake_case)]
|
||||
use std::convert::TryFrom;
|
||||
use std::ops::Deref;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::http::{self, header, uri::Uri};
|
||||
use actix_http::RequestHead;
|
||||
@ -40,6 +42,12 @@ pub trait Guard {
|
||||
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.
|
||||
///
|
||||
/// ```
|
||||
|
@ -3,20 +3,23 @@ use std::marker::PhantomData;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_http::{Error, Response};
|
||||
use actix_http::Error;
|
||||
use actix_service::{Service, ServiceFactory};
|
||||
use actix_utils::future::{ready, Ready};
|
||||
use futures_core::ready;
|
||||
use pin_project::pin_project;
|
||||
|
||||
use crate::extract::FromRequest;
|
||||
use crate::request::HttpRequest;
|
||||
use crate::responder::Responder;
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::{
|
||||
extract::FromRequest,
|
||||
request::HttpRequest,
|
||||
responder::Responder,
|
||||
response::HttpResponse,
|
||||
service::{ServiceRequest, ServiceResponse},
|
||||
};
|
||||
|
||||
/// 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
|
||||
/// an [`HttpResponse`](crate::HttpResponse) (ie, [`impl Responder`](crate::Responder)).
|
||||
/// A request handler is an async function that accepts zero or more parameters that can be
|
||||
/// extracted from a request (i.e., [`impl FromRequest`](crate::FromRequest)) and returns a type
|
||||
/// 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
|
||||
/// a valid handler. See [Request Handlers](https://actix.rs/docs/handlers/) for more information.
|
||||
@ -102,9 +105,7 @@ where
|
||||
type Error = Error;
|
||||
type Future = HandlerServiceFuture<F, T, R>;
|
||||
|
||||
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
actix_service::always_ready!();
|
||||
|
||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||
let (req, mut payload) = req.into_parts();
|
||||
@ -147,9 +148,9 @@ where
|
||||
let state = HandlerServiceFuture::Handle(fut, req.take());
|
||||
self.as_mut().set(state);
|
||||
}
|
||||
Err(e) => {
|
||||
let res: Response = e.into().into();
|
||||
Err(err) => {
|
||||
let req = req.take().unwrap();
|
||||
let res = HttpResponse::from_error(err.into());
|
||||
return Poll::Ready(Ok(ServiceResponse::new(req, res)));
|
||||
}
|
||||
};
|
||||
|
@ -5,7 +5,7 @@ use mime::Mime;
|
||||
use super::{qitem, QualityItem};
|
||||
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)
|
||||
///
|
||||
/// The `Accept` header field can be used by user agents to specify
|
||||
@ -81,14 +81,14 @@ crate::header! {
|
||||
|
||||
test_accept {
|
||||
// Tests from the RFC
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test1,
|
||||
vec![b"audio/*; q=0.2, audio/basic"],
|
||||
Some(Accept(vec![
|
||||
QualityItem::new("audio/*".parse().unwrap(), q(200)),
|
||||
qitem("audio/basic".parse().unwrap()),
|
||||
])));
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test2,
|
||||
vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"],
|
||||
Some(Accept(vec![
|
||||
@ -100,13 +100,13 @@ crate::header! {
|
||||
qitem("text/x-c".parse().unwrap()),
|
||||
])));
|
||||
// Custom tests
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test3,
|
||||
vec![b"text/plain; charset=utf-8"],
|
||||
Some(Accept(vec![
|
||||
qitem(mime::TEXT_PLAIN_UTF_8),
|
||||
])));
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test4,
|
||||
vec![b"text/plain; charset=utf-8; q=0.5"],
|
||||
Some(Accept(vec![
|
||||
|
@ -1,6 +1,6 @@
|
||||
use super::{Charset, QualityItem, ACCEPT_CHARSET};
|
||||
|
||||
crate::header! {
|
||||
crate::__define_common_header! {
|
||||
/// `Accept-Charset` header, defined in
|
||||
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3)
|
||||
///
|
||||
@ -57,6 +57,6 @@ crate::header! {
|
||||
|
||||
test_accept_charset {
|
||||
// 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 {
|
||||
// From the RFC
|
||||
test_header!(test1, vec![b"compress, gzip"]);
|
||||
test_header!(test2, vec![b""], Some(AcceptEncoding(vec![])));
|
||||
test_header!(test3, vec![b"*"]);
|
||||
crate::__common_header_test!(test1, vec![b"compress, gzip"]);
|
||||
crate::__common_header_test!(test2, vec![b""], Some(AcceptEncoding(vec![])));
|
||||
crate::__common_header_test!(test3, vec![b"*"]);
|
||||
// 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
|
||||
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;
|
||||
|
||||
crate::header! {
|
||||
use super::{QualityItem, ACCEPT_LANGUAGE};
|
||||
|
||||
crate::__define_common_header! {
|
||||
/// `Accept-Language` header, defined in
|
||||
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
|
||||
///
|
||||
@ -23,14 +24,11 @@ crate::header! {
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use language_tags::langtag;
|
||||
/// use actix_web::HttpResponse;
|
||||
/// use actix_web::http::header::{AcceptLanguage, LanguageTag, qitem};
|
||||
///
|
||||
/// let mut builder = HttpResponse::Ok();
|
||||
/// let mut langtag: LanguageTag = Default::default();
|
||||
/// langtag.language = Some("en".to_owned());
|
||||
/// langtag.region = Some("US".to_owned());
|
||||
/// let langtag = LanguageTag::parse("en-US").unwrap();
|
||||
/// builder.insert_header(
|
||||
/// AcceptLanguage(vec![
|
||||
/// qitem(langtag),
|
||||
@ -39,16 +37,15 @@ crate::header! {
|
||||
/// ```
|
||||
///
|
||||
/// ```
|
||||
/// use language_tags::langtag;
|
||||
/// 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();
|
||||
/// builder.insert_header(
|
||||
/// AcceptLanguage(vec![
|
||||
/// qitem(langtag!(da)),
|
||||
/// QualityItem::new(langtag!(en;;;GB), q(800)),
|
||||
/// QualityItem::new(langtag!(en), q(700)),
|
||||
/// qitem(LanguageTag::parse("da").unwrap()),
|
||||
/// QualityItem::new(LanguageTag::parse("en-GB").unwrap(), q(800)),
|
||||
/// QualityItem::new(LanguageTag::parse("en").unwrap(), q(700)),
|
||||
/// ])
|
||||
/// );
|
||||
/// ```
|
||||
@ -56,9 +53,9 @@ crate::header! {
|
||||
|
||||
test_accept_language {
|
||||
// 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
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test2, vec![b"en-US, en; q=0.5, fr"],
|
||||
Some(AcceptLanguage(vec![
|
||||
qitem("en-US".parse().unwrap()),
|
||||
|
@ -1,7 +1,7 @@
|
||||
use actix_http::http::Method;
|
||||
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)
|
||||
///
|
||||
/// The `Allow` header field lists the set of methods advertised as
|
||||
@ -49,12 +49,12 @@ crate::header! {
|
||||
|
||||
test_allow {
|
||||
// From the RFC
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test1,
|
||||
vec![b"GET, HEAD, PUT"],
|
||||
Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT])));
|
||||
// Own tests
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test2,
|
||||
vec![b"OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH"],
|
||||
Some(HeaderField(vec![
|
||||
@ -67,7 +67,7 @@ crate::header! {
|
||||
Method::TRACE,
|
||||
Method::CONNECT,
|
||||
Method::PATCH])));
|
||||
test_header!(
|
||||
crate::__common_header_test!(
|
||||
test3,
|
||||
vec![b""],
|
||||
Some(HeaderField(Vec::<Method>::new())));
|
||||
|
@ -1,9 +1,7 @@
|
||||
use std::fmt::{self, Write};
|
||||
use std::str::FromStr;
|
||||
|
||||
use super::{
|
||||
fmt_comma_delimited, from_comma_delimited, Header, IntoHeaderValue, Writer,
|
||||
};
|
||||
use super::{fmt_comma_delimited, from_comma_delimited, Header, IntoHeaderValue, Writer};
|
||||
|
||||
use crate::http::header;
|
||||
|
||||
@ -51,9 +49,9 @@ use crate::http::header;
|
||||
#[derive(PartialEq, Clone, Debug)]
|
||||
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 {
|
||||
fn name() -> header::HeaderName {
|
||||
header::CACHE_CONTROL
|
||||
@ -75,7 +73,7 @@ impl Header for CacheControl {
|
||||
|
||||
impl fmt::Display for CacheControl {
|
||||
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),
|
||||
("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
|
||||
("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
|
||||
(left, right) => {
|
||||
Ok(Extension(left.to_owned(), Some(right.to_owned())))
|
||||
}
|
||||
(left, right) => Ok(Extension(left.to_owned(), Some(right.to_owned()))),
|
||||
}
|
||||
}
|
||||
Some(_) => Err(None),
|
||||
|
@ -10,8 +10,8 @@ use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use std::fmt::{self, Write};
|
||||
|
||||
use crate::http::header;
|
||||
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.
|
||||
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.
|
||||
pub fn is_ext<T: AsRef<str>>(&self, disp_type: T) -> bool {
|
||||
match self.disposition {
|
||||
DispositionType::Ext(ref t)
|
||||
if t.eq_ignore_ascii_case(disp_type.as_ref()) =>
|
||||
{
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
pub fn is_ext(&self, disp_type: impl AsRef<str>) -> bool {
|
||||
matches!(
|
||||
self.disposition,
|
||||
DispositionType::Ext(ref t) if t.eq_ignore_ascii_case(disp_type.as_ref())
|
||||
)
|
||||
}
|
||||
|
||||
/// Return the value of *name* if exists.
|
||||
@ -434,7 +430,7 @@ impl ContentDisposition {
|
||||
}
|
||||
|
||||
/// 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();
|
||||
self.parameters
|
||||
.iter()
|
||||
@ -443,7 +439,7 @@ impl ContentDisposition {
|
||||
}
|
||||
|
||||
/// 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();
|
||||
self.parameters
|
||||
.iter()
|
||||
@ -521,7 +517,8 @@ impl fmt::Display for DispositionParam {
|
||||
//
|
||||
//
|
||||
// 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 {
|
||||
DispositionParam::Name(ref value) => write!(f, "name={}", value),
|
||||
DispositionParam::Filename(ref value) => {
|
||||
@ -555,8 +552,7 @@ impl fmt::Display for ContentDisposition {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ContentDisposition, DispositionParam, DispositionType};
|
||||
use crate::http::header::Charset;
|
||||
use crate::http::header::{ExtendedValue, HeaderValue};
|
||||
use crate::http::header::{Charset, ExtendedValue, HeaderValue};
|
||||
|
||||
#[test]
|
||||
fn test_from_raw_basic() {
|
||||
@ -618,8 +614,8 @@ mod tests {
|
||||
charset: Charset::Ext(String::from("UTF-8")),
|
||||
language_tag: None,
|
||||
value: vec![
|
||||
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20,
|
||||
b'r', b'a', b't', b'e', b's',
|
||||
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r',
|
||||
b'a', b't', b'e', b's',
|
||||
],
|
||||
})],
|
||||
};
|
||||
@ -635,8 +631,8 @@ mod tests {
|
||||
charset: Charset::Ext(String::from("UTF-8")),
|
||||
language_tag: None,
|
||||
value: vec![
|
||||
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20,
|
||||
b'r', b'a', b't', b'e', b's',
|
||||
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r',
|
||||
b'a', b't', b'e', b's',
|
||||
],
|
||||
})],
|
||||
};
|
||||
@ -698,26 +694,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_from_raw_only_disp() {
|
||||
let a = ContentDisposition::from_raw(&HeaderValue::from_static("attachment"))
|
||||
.unwrap();
|
||||
let a = ContentDisposition::from_raw(&HeaderValue::from_static("attachment")).unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::Attachment,
|
||||
parameters: vec![],
|
||||
};
|
||||
assert_eq!(a, b);
|
||||
|
||||
let a =
|
||||
ContentDisposition::from_raw(&HeaderValue::from_static("inline ;")).unwrap();
|
||||
let a = ContentDisposition::from_raw(&HeaderValue::from_static("inline ;")).unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::Inline,
|
||||
parameters: vec![],
|
||||
};
|
||||
assert_eq!(a, b);
|
||||
|
||||
let a = ContentDisposition::from_raw(&HeaderValue::from_static(
|
||||
"unknown-disp-param",
|
||||
))
|
||||
.unwrap();
|
||||
let a = ContentDisposition::from_raw(&HeaderValue::from_static("unknown-disp-param"))
|
||||
.unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::Ext(String::from("unknown-disp-param")),
|
||||
parameters: vec![],
|
||||
@ -756,8 +748,8 @@ mod tests {
|
||||
Mainstream browsers like Firefox (gecko) and Chrome use UTF-8 directly as above.
|
||||
(And now, only UTF-8 is handled by this implementation.)
|
||||
*/
|
||||
let a = HeaderValue::from_str("form-data; name=upload; filename=\"文件.webp\"")
|
||||
.unwrap();
|
||||
let a =
|
||||
HeaderValue::from_str("form-data; name=upload; filename=\"文件.webp\"").unwrap();
|
||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::FormData,
|
||||
@ -808,8 +800,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_from_raw_semicolon() {
|
||||
let a =
|
||||
HeaderValue::from_static("form-data; filename=\"A semicolon here;.pdf\"");
|
||||
let a = HeaderValue::from_static("form-data; filename=\"A semicolon here;.pdf\"");
|
||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::FormData,
|
||||
@ -845,9 +836,8 @@ mod tests {
|
||||
};
|
||||
assert_eq!(a, b);
|
||||
|
||||
let a = HeaderValue::from_static(
|
||||
"form-data; name=photo; filename=\"%74%65%73%74.png\"",
|
||||
);
|
||||
let a =
|
||||
HeaderValue::from_static("form-data; name=photo; filename=\"%74%65%73%74.png\"");
|
||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::FormData,
|
||||
@ -892,8 +882,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_display_extended() {
|
||||
let as_string =
|
||||
"attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
|
||||
let as_string = "attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
|
||||
let a = HeaderValue::from_static(as_string);
|
||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||
let display_rendered = format!("{}", a);
|
||||
|
@ -1,7 +1,7 @@
|
||||
use super::{QualityItem, CONTENT_LANGUAGE};
|
||||
use language_tags::LanguageTag;
|
||||
|
||||
crate::header! {
|
||||
crate::__define_common_header! {
|
||||
/// `Content-Language` header, defined in
|
||||
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
|
||||
///
|
||||
@ -24,35 +24,33 @@ crate::header! {
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use language_tags::langtag;
|
||||
/// use actix_web::HttpResponse;
|
||||
/// use actix_web::http::header::{ContentLanguage, qitem};
|
||||
/// use actix_web::http::header::{ContentLanguage, LanguageTag, qitem};
|
||||
///
|
||||
/// let mut builder = HttpResponse::Ok();
|
||||
/// builder.insert_header(
|
||||
/// ContentLanguage(vec![
|
||||
/// qitem(langtag!(en)),
|
||||
/// qitem(LanguageTag::parse("en").unwrap()),
|
||||
/// ])
|
||||
/// );
|
||||
/// ```
|
||||
///
|
||||
/// ```
|
||||
/// use language_tags::langtag;
|
||||
/// use actix_web::HttpResponse;
|
||||
/// use actix_web::http::header::{ContentLanguage, qitem};
|
||||
/// use actix_web::http::header::{ContentLanguage, LanguageTag, qitem};
|
||||
///
|
||||
/// let mut builder = HttpResponse::Ok();
|
||||
/// builder.insert_header(
|
||||
/// ContentLanguage(vec![
|
||||
/// qitem(langtag!(da)),
|
||||
/// qitem(langtag!(en;;;GB)),
|
||||
/// qitem(LanguageTag::parse("da").unwrap()),
|
||||
/// qitem(LanguageTag::parse("en-GB").unwrap()),
|
||||
/// ])
|
||||
/// );
|
||||
/// ```
|
||||
(ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+
|
||||
|
||||
test_content_language {
|
||||
test_header!(test1, vec![b"da"]);
|
||||
test_header!(test2, vec![b"mi, en"]);
|
||||
crate::__common_header_test!(test1, vec![b"da"]);
|
||||
crate::__common_header_test!(test2, vec![b"mi, en"]);
|
||||
}
|
||||
}
|
||||
|
@ -1,70 +1,68 @@
|
||||
use std::fmt::{self, Display, Write};
|
||||
use std::str::FromStr;
|
||||
|
||||
use super::{HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE};
|
||||
use crate::error::ParseError;
|
||||
use super::{
|
||||
HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE,
|
||||
};
|
||||
|
||||
crate::header! {
|
||||
crate::__define_common_header! {
|
||||
/// `Content-Range` header, defined in
|
||||
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2)
|
||||
(ContentRange, CONTENT_RANGE) => [ContentRangeSpec]
|
||||
|
||||
test_content_range {
|
||||
test_header!(test_bytes,
|
||||
crate::__common_header_test!(test_bytes,
|
||||
vec![b"bytes 0-499/500"],
|
||||
Some(ContentRange(ContentRangeSpec::Bytes {
|
||||
range: Some((0, 499)),
|
||||
instance_length: Some(500)
|
||||
})));
|
||||
|
||||
test_header!(test_bytes_unknown_len,
|
||||
crate::__common_header_test!(test_bytes_unknown_len,
|
||||
vec![b"bytes 0-499/*"],
|
||||
Some(ContentRange(ContentRangeSpec::Bytes {
|
||||
range: Some((0, 499)),
|
||||
instance_length: None
|
||||
})));
|
||||
|
||||
test_header!(test_bytes_unknown_range,
|
||||
crate::__common_header_test!(test_bytes_unknown_range,
|
||||
vec![b"bytes */500"],
|
||||
Some(ContentRange(ContentRangeSpec::Bytes {
|
||||
range: None,
|
||||
instance_length: Some(500)
|
||||
})));
|
||||
|
||||
test_header!(test_unregistered,
|
||||
crate::__common_header_test!(test_unregistered,
|
||||
vec![b"seconds 1-2"],
|
||||
Some(ContentRange(ContentRangeSpec::Unregistered {
|
||||
unit: "seconds".to_owned(),
|
||||
resp: "1-2".to_owned()
|
||||
})));
|
||||
|
||||
test_header!(test_no_len,
|
||||
crate::__common_header_test!(test_no_len,
|
||||
vec![b"bytes 0-499"],
|
||||
None::<ContentRange>);
|
||||
|
||||
test_header!(test_only_unit,
|
||||
crate::__common_header_test!(test_only_unit,
|
||||
vec![b"bytes"],
|
||||
None::<ContentRange>);
|
||||
|
||||
test_header!(test_end_less_than_start,
|
||||
crate::__common_header_test!(test_end_less_than_start,
|
||||
vec![b"bytes 499-0/500"],
|
||||
None::<ContentRange>);
|
||||
|
||||
test_header!(test_blank,
|
||||
crate::__common_header_test!(test_blank,
|
||||
vec![b""],
|
||||
None::<ContentRange>);
|
||||
|
||||
test_header!(test_bytes_many_spaces,
|
||||
crate::__common_header_test!(test_bytes_many_spaces,
|
||||
vec![b"bytes 1-2/500 3"],
|
||||
None::<ContentRange>);
|
||||
|
||||
test_header!(test_bytes_many_slashes,
|
||||
crate::__common_header_test!(test_bytes_many_slashes,
|
||||
vec![b"bytes 1-2/500/600"],
|
||||
None::<ContentRange>);
|
||||
|
||||
test_header!(test_bytes_many_dashes,
|
||||
crate::__common_header_test!(test_bytes_many_dashes,
|
||||
vec![b"bytes 1-2-3/500"],
|
||||
None::<ContentRange>);
|
||||
|
||||
@ -141,8 +139,7 @@ impl FromStr for ContentRangeSpec {
|
||||
} else {
|
||||
let (first_byte, last_byte) =
|
||||
split_in_two(range, '-').ok_or(ParseError::Header)?;
|
||||
let first_byte =
|
||||
first_byte.parse().map_err(|_| ParseError::Header)?;
|
||||
let first_byte = first_byte.parse().map_err(|_| ParseError::Header)?;
|
||||
let last_byte = last_byte.parse().map_err(|_| ParseError::Header)?;
|
||||
if last_byte < first_byte {
|
||||
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