Merge branch 'master' into style/h1_poll_response_loop

This commit is contained in:
fakeshadow 2021-04-22 00:56:36 -07:00 committed by GitHub
commit 8a7d996b11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
88 changed files with 2489 additions and 2370 deletions

View File

@ -1,11 +1,15 @@
# Changes # Changes
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
## 4.0.0-beta.6 - 2021-04-17
### Added ### Added
* `HttpResponse` and `HttpResponseBuilder` structs. [#2065] * `HttpResponse` and `HttpResponseBuilder` structs. [#2065]
### Changed ### Changed
* Most error types are now marked `#[non_exhaustive]`. [#2148] * 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 [#2065]: https://github.com/actix/actix-web/pull/2065
[#2148]: https://github.com/actix/actix-web/pull/2148 [#2148]: https://github.com/actix/actix-web/pull/2148

View File

@ -1,16 +1,17 @@
[package] [package]
name = "actix-web" name = "actix-web"
version = "4.0.0-beta.5" version = "4.0.0-beta.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust" description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
readme = "README.md"
keywords = ["actix", "http", "web", "framework", "async"] keywords = ["actix", "http", "web", "framework", "async"]
homepage = "https://actix.rs" categories = [
repository = "https://github.com/actix/actix-web.git" "network-programming",
documentation = "https://docs.rs/actix-web/" "asynchronous",
categories = ["network-programming", "asynchronous",
"web-programming::http-server", "web-programming::http-server",
"web-programming::websocket"] "web-programming::websocket"
]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
edition = "2018" edition = "2018"
@ -56,17 +57,17 @@ openssl = ["actix-http/openssl", "actix-tls/accept", "actix-tls/openssl"]
rustls = ["actix-http/rustls", "actix-tls/accept", "actix-tls/rustls"] rustls = ["actix-http/rustls", "actix-tls/accept", "actix-tls/rustls"]
[dependencies] [dependencies]
actix-codec = "0.4.0-beta.1" actix-codec = "0.4.0"
actix-macros = "0.2.0" actix-macros = "0.2.0"
actix-router = "0.2.7" actix-router = "0.2.7"
actix-rt = "2.2" actix-rt = "2.2"
actix-server = "2.0.0-beta.3" actix-server = "2.0.0-beta.3"
actix-service = "2.0.0-beta.4" actix-service = "2.0.0"
actix-utils = "3.0.0-beta.4" actix-utils = "3.0.0"
actix-tls = { version = "3.0.0-beta.5", default-features = false, optional = true } actix-tls = { version = "3.0.0-beta.5", default-features = false, optional = true }
actix-web-codegen = "0.5.0-beta.2" actix-web-codegen = "0.5.0-beta.2"
actix-http = "3.0.0-beta.5" actix-http = "3.0.0-beta.6"
ahash = "0.7" ahash = "0.7"
bytes = "1" bytes = "1"
@ -92,8 +93,8 @@ time = { version = "0.2.23", default-features = false, features = ["std"] }
url = "2.1" url = "2.1"
[dev-dependencies] [dev-dependencies]
actix-test = { version = "0.1.0-beta.1", features = ["openssl", "rustls"] } actix-test = { version = "0.1.0-beta.2", features = ["openssl", "rustls"] }
awc = { version = "3.0.0-beta.4", features = ["openssl"] } awc = { version = "3.0.0-beta.5", features = ["openssl"] }
brotli2 = "0.3.2" brotli2 = "0.3.2"
criterion = "0.3" criterion = "0.3"

View File

@ -31,7 +31,7 @@
* Static assets * Static assets
* SSL support using OpenSSL or Rustls * SSL support using OpenSSL or Rustls
* Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/)) * Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
* Includes an async [HTTP client](https://docs.rs/actix-web/latest/actix_web/client/index.html) * Includes an async [HTTP client](https://docs.rs/awc/)
* Runs on stable Rust 1.46+ * Runs on stable Rust 1.46+
## Documentation ## Documentation
@ -90,7 +90,7 @@ You may consider checking out
## Benchmarks ## Benchmarks
One of the fastest web frameworks available according to the One of the fastest web frameworks available according to the
[TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r19). [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r20&test=composite).
## License ## License

View File

@ -1,8 +1,10 @@
# Changes # Changes
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
* `NamedFile` now implements `ServiceFactory` and `HttpServiceFactory` making it much more useful in routing. For example, it can be used directly as a default service. [#2135]
* For symbolic links, `Content-Disposition` header no longer shows the filename of the original file. [#2156] * For symbolic links, `Content-Disposition` header no longer shows the filename of the original file. [#2156]
[#2135]: https://github.com/actix/actix-web/pull/2135
[#2156]: https://github.com/actix/actix-web/pull/2156 [#2156]: https://github.com/actix/actix-web/pull/2156

View File

@ -17,9 +17,9 @@ name = "actix_files"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "4.0.0-beta.5", default-features = false } actix-web = { version = "4.0.0-beta.6", default-features = false }
actix-service = "2.0.0-beta.4" actix-service = "2.0.0"
actix-utils = "3.0.0-beta.4" actix-utils = "3.0.0"
askama_escape = "0.10" askama_escape = "0.10"
bitflags = "1" bitflags = "1"
@ -34,5 +34,5 @@ percent-encoding = "2.1"
[dev-dependencies] [dev-dependencies]
actix-rt = "2.2" actix-rt = "2.2"
actix-web = "4.0.0-beta.5" actix-web = "4.0.0-beta.6"
actix-test = "0.1.0-beta.1" actix-test = "0.1.0-beta.2"

View File

@ -199,6 +199,18 @@ impl Files {
} }
/// Sets default handler which is used when no matched file could be found. /// Sets default handler which is used when no matched file could be found.
///
/// For example, you could set a fall back static file handler:
/// ```rust
/// use actix_files::{Files, NamedFile};
///
/// # fn run() -> Result<(), actix_web::Error> {
/// let files = Files::new("/", "./static")
/// .index_file("index.html")
/// .default_handler(NamedFile::open("./static/404.html")?);
/// # Ok(())
/// # }
/// ```
pub fn default_handler<F, U>(mut self, f: F) -> Self pub fn default_handler<F, U>(mut self, f: F) -> Self
where where
F: IntoServiceFactory<U, ServiceRequest>, F: IntoServiceFactory<U, ServiceRequest>,

View File

@ -755,6 +755,80 @@ mod tests {
assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.status(), StatusCode::OK);
} }
#[actix_rt::test]
async fn test_serve_named_file() {
let srv =
test::init_service(App::new().service(NamedFile::open("Cargo.toml").unwrap()))
.await;
let req = TestRequest::get().uri("/Cargo.toml").to_request();
let res = test::call_service(&srv, req).await;
assert_eq!(res.status(), StatusCode::OK);
let bytes = test::read_body(res).await;
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
assert_eq!(bytes, data);
let req = TestRequest::get().uri("/test/unknown").to_request();
let res = test::call_service(&srv, req).await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn test_serve_named_file_prefix() {
let srv = test::init_service(
App::new()
.service(web::scope("/test").service(NamedFile::open("Cargo.toml").unwrap())),
)
.await;
let req = TestRequest::get().uri("/test/Cargo.toml").to_request();
let res = test::call_service(&srv, req).await;
assert_eq!(res.status(), StatusCode::OK);
let bytes = test::read_body(res).await;
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
assert_eq!(bytes, data);
let req = TestRequest::get().uri("/Cargo.toml").to_request();
let res = test::call_service(&srv, req).await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn test_named_file_default_service() {
let srv = test::init_service(
App::new().default_service(NamedFile::open("Cargo.toml").unwrap()),
)
.await;
for route in ["/foobar", "/baz", "/"].iter() {
let req = TestRequest::get().uri(route).to_request();
let res = test::call_service(&srv, req).await;
assert_eq!(res.status(), StatusCode::OK);
let bytes = test::read_body(res).await;
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
assert_eq!(bytes, data);
}
}
#[actix_rt::test]
async fn test_default_handler_named_file() {
let st = Files::new("/", ".")
.default_handler(NamedFile::open("Cargo.toml").unwrap())
.new_service(())
.await
.unwrap();
let req = TestRequest::with_uri("/missing").to_srv_request();
let resp = test::call_service(&st, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let bytes = test::read_body(resp).await;
let data = Bytes::from(fs::read("Cargo.toml").unwrap());
assert_eq!(bytes, data);
}
#[actix_rt::test] #[actix_rt::test]
async fn test_symlinks() { async fn test_symlinks() {
let srv = test::init_service(App::new().service(Files::new("test", "."))).await; let srv = test::init_service(App::new().service(Files::new("test", "."))).await;

View File

@ -1,3 +1,6 @@
use actix_service::{Service, ServiceFactory};
use actix_utils::future::{ok, ready, Ready};
use actix_web::dev::{AppService, HttpServiceFactory, ResourceDef};
use std::fs::{File, Metadata}; use std::fs::{File, Metadata};
use std::io; use std::io;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
@ -8,14 +11,14 @@ use std::time::{SystemTime, UNIX_EPOCH};
use std::os::unix::fs::MetadataExt; use std::os::unix::fs::MetadataExt;
use actix_web::{ use actix_web::{
dev::{BodyEncoding, SizedStream}, dev::{BodyEncoding, ServiceRequest, ServiceResponse, SizedStream},
http::{ http::{
header::{ header::{
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue, self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
}, },
ContentEncoding, StatusCode, ContentEncoding, StatusCode,
}, },
HttpMessage, HttpRequest, HttpResponse, Responder, Error, HttpMessage, HttpRequest, HttpResponse, Responder,
}; };
use bitflags::bitflags; use bitflags::bitflags;
use mime_guess::from_path; use mime_guess::from_path;
@ -39,6 +42,29 @@ impl Default for Flags {
} }
/// A file with an associated name. /// A file with an associated name.
///
/// `NamedFile` can be registered as services:
/// ```
/// use actix_web::App;
/// use actix_files::NamedFile;
///
/// # fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let app = App::new()
/// .service(NamedFile::open("./static/index.html")?);
/// # Ok(())
/// # }
/// ```
///
/// They can also be returned from handlers:
/// ```
/// use actix_web::{Responder, get};
/// use actix_files::NamedFile;
///
/// #[get("/")]
/// async fn index() -> impl Responder {
/// NamedFile::open("./static/index.html")
/// }
/// ```
#[derive(Debug)] #[derive(Debug)]
pub struct NamedFile { pub struct NamedFile {
path: PathBuf, path: PathBuf,
@ -480,3 +506,53 @@ impl Responder for NamedFile {
self.into_response(req) self.into_response(req)
} }
} }
impl ServiceFactory<ServiceRequest> for NamedFile {
type Response = ServiceResponse;
type Error = Error;
type Config = ();
type InitError = ();
type Service = NamedFileService;
type Future = Ready<Result<Self::Service, ()>>;
fn new_service(&self, _: ()) -> Self::Future {
ok(NamedFileService {
path: self.path.clone(),
})
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct NamedFileService {
path: PathBuf,
}
impl Service<ServiceRequest> for NamedFileService {
type Response = ServiceResponse;
type Error = Error;
type Future = Ready<Result<Self::Response, Self::Error>>;
actix_service::always_ready!();
fn call(&self, req: ServiceRequest) -> Self::Future {
let (req, _) = req.into_parts();
ready(
NamedFile::open(&self.path)
.map_err(|e| e.into())
.map(|f| f.into_response(&req))
.map(|res| ServiceResponse::new(req, res)),
)
}
}
impl HttpServiceFactory for NamedFile {
fn register(self, config: &mut AppService) {
config.register_service(
ResourceDef::root_prefix(self.path.to_string_lossy().as_ref()),
None,
self,
None,
)
}
}

View File

@ -29,13 +29,13 @@ default = []
openssl = ["tls-openssl", "awc/openssl"] openssl = ["tls-openssl", "awc/openssl"]
[dependencies] [dependencies]
actix-service = "2.0.0-beta.4" actix-service = "2.0.0"
actix-codec = "0.4.0-beta.1" actix-codec = "0.4.0"
actix-tls = "3.0.0-beta.5" actix-tls = "3.0.0-beta.5"
actix-utils = "3.0.0-beta.4" actix-utils = "3.0.0"
actix-rt = "2.2" actix-rt = "2.2"
actix-server = "2.0.0-beta.3" actix-server = "2.0.0-beta.3"
awc = { version = "3.0.0-beta.4", default-features = false } awc = { version = "3.0.0-beta.5", default-features = false }
base64 = "0.13" base64 = "0.13"
bytes = "1" bytes = "1"
@ -51,5 +51,5 @@ time = { version = "0.2.23", default-features = false, features = ["std"] }
tls-openssl = { version = "0.10.9", package = "openssl", optional = true } tls-openssl = { version = "0.10.9", package = "openssl", optional = true }
[dev-dependencies] [dev-dependencies]
actix-web = { version = "4.0.0-beta.5", default-features = false, features = ["cookies"] } actix-web = { version = "4.0.0-beta.6", default-features = false, features = ["cookies"] }
actix-http = "3.0.0-beta.5" actix-http = "3.0.0-beta.6"

View File

@ -1,6 +1,33 @@
# Changes # Changes
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
### Added
* 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]
### Changed
* `header` mod is now public. [#2171]
* `uri` mod is now public. [#2171]
### Removed
* Stop re-exporting `http` crate's `HeaderMap` types in addition to ours. [#2171]
[#2171]: https://github.com/actix/actix-web/pull/2171
## 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 ### Removed
* `cookies` feature flag. [#2065] * `cookies` feature flag. [#2065]
* Top-level `cookies` mod (re-export). [#2065] * Top-level `cookies` mod (re-export). [#2065]
@ -10,9 +37,15 @@
* `ResponseBuilder::json`. [#2148] * `ResponseBuilder::json`. [#2148]
* `ResponseBuilder::{set_header, header}`. [#2148] * `ResponseBuilder::{set_header, header}`. [#2148]
* `impl From<serde_json::Value> for Body`. [#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 [#2065]: https://github.com/actix/actix-web/pull/2065
[#2148]: https://github.com/actix/actix-web/pull/2148 [#2148]: https://github.com/actix/actix-web/pull/2148
[#2152]: https://github.com/actix/actix-web/pull/2152
[#2159]: https://github.com/actix/actix-web/pull/2159
[#2158]: https://github.com/actix/actix-web/pull/2158
[#2161]: https://github.com/actix/actix-web/pull/2161
## 3.0.0-beta.5 - 2021-04-02 ## 3.0.0-beta.5 - 2021-04-02

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-http" name = "actix-http"
version = "3.0.0-beta.5" version = "3.0.0-beta.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "HTTP primitives for the Actix ecosystem" description = "HTTP primitives for the Actix ecosystem"
readme = "README.md" readme = "README.md"
@ -38,9 +38,9 @@ compress = ["flate2", "brotli2"]
trust-dns = ["trust-dns-resolver"] trust-dns = ["trust-dns-resolver"]
[dependencies] [dependencies]
actix-service = "2.0.0-beta.4" actix-service = "2.0.0"
actix-codec = "0.4.0-beta.1" actix-codec = "0.4.0"
actix-utils = "3.0.0-beta.4" actix-utils = "3.0.0"
actix-rt = "2.2" actix-rt = "2.2"
actix-tls = { version = "3.0.0-beta.5", features = ["accept", "connect"] } actix-tls = { version = "3.0.0-beta.5", features = ["accept", "connect"] }
@ -62,6 +62,7 @@ local-channel = "0.1"
once_cell = "1.5" once_cell = "1.5"
log = "0.4" log = "0.4"
mime = "0.3" mime = "0.3"
paste = "1"
percent-encoding = "2.1" percent-encoding = "2.1"
pin-project = "1.0.0" pin-project = "1.0.0"
pin-project-lite = "0.2" pin-project-lite = "0.2"

View File

@ -3,11 +3,11 @@
> HTTP primitives for the Actix ecosystem. > HTTP primitives for the Actix ecosystem.
[![crates.io](https://img.shields.io/crates/v/actix-http?label=latest)](https://crates.io/crates/actix-http) [![crates.io](https://img.shields.io/crates/v/actix-http?label=latest)](https://crates.io/crates/actix-http)
[![Documentation](https://docs.rs/actix-http/badge.svg?version=3.0.0-beta.5)](https://docs.rs/actix-http/3.0.0-beta.5) [![Documentation](https://docs.rs/actix-http/badge.svg?version=3.0.0-beta.6)](https://docs.rs/actix-http/3.0.0-beta.6)
[![Version](https://img.shields.io/badge/rustc-1.46+-ab6000.svg)](https://blog.rust-lang.org/2020/03/12/Rust-1.46.html) [![Version](https://img.shields.io/badge/rustc-1.46+-ab6000.svg)](https://blog.rust-lang.org/2020/03/12/Rust-1.46.html)
![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http.svg) ![MIT or Apache 2.0 licensed](https://img.shields.io/crates/l/actix-http.svg)
<br /> <br />
[![dependency status](https://deps.rs/crate/actix-http/3.0.0-beta.5/status.svg)](https://deps.rs/crate/actix-http/3.0.0-beta.5) [![dependency status](https://deps.rs/crate/actix-http/3.0.0-beta.6/status.svg)](https://deps.rs/crate/actix-http/3.0.0-beta.6)
[![Download](https://img.shields.io/crates/d/actix-http.svg)](https://crates.io/crates/actix-http) [![Download](https://img.shields.io/crates/d/actix-http.svg)](https://crates.io/crates/actix-http)
[![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

View File

@ -1,6 +1,6 @@
use std::{env, io}; use std::{env, io};
use actix_http::{Error, HttpService, Request, Response}; use actix_http::{http::StatusCode, Error, HttpService, Request, Response};
use actix_server::Server; use actix_server::Server;
use bytes::BytesMut; use bytes::BytesMut;
use futures_util::StreamExt as _; use futures_util::StreamExt as _;
@ -25,7 +25,7 @@ async fn main() -> io::Result<()> {
info!("request body: {:?}", body); info!("request body: {:?}", body);
Ok::<_, Error>( Ok::<_, Error>(
Response::Ok() Response::build(StatusCode::OK)
.insert_header(( .insert_header((
"x-head", "x-head",
HeaderValue::from_static("dummy value!"), HeaderValue::from_static("dummy value!"),

View File

@ -1,20 +1,20 @@
use std::{env, io}; use std::{env, io};
use actix_http::http::HeaderValue; use actix_http::{body::Body, http::HeaderValue, http::StatusCode};
use actix_http::{Error, HttpService, Request, Response}; use actix_http::{Error, HttpService, Request, Response};
use actix_server::Server; use actix_server::Server;
use bytes::BytesMut; use bytes::BytesMut;
use futures_util::StreamExt as _; use futures_util::StreamExt as _;
use log::info; use log::info;
async fn handle_request(mut req: Request) -> Result<Response, Error> { async fn handle_request(mut req: Request) -> Result<Response<Body>, Error> {
let mut body = BytesMut::new(); let mut body = BytesMut::new();
while let Some(item) = req.payload().next().await { while let Some(item) = req.payload().next().await {
body.extend_from_slice(&item?) body.extend_from_slice(&item?)
} }
info!("request body: {:?}", body); info!("request body: {:?}", body);
Ok(Response::Ok() Ok(Response::build(StatusCode::OK)
.insert_header(("x-head", HeaderValue::from_static("dummy value!"))) .insert_header(("x-head", HeaderValue::from_static("dummy value!")))
.body(body)) .body(body))
} }

View File

@ -1,6 +1,6 @@
use std::{env, io}; use std::{env, io};
use actix_http::{HttpService, Response}; use actix_http::{http::StatusCode, HttpService, Response};
use actix_server::Server; use actix_server::Server;
use actix_utils::future; use actix_utils::future;
use http::header::HeaderValue; use http::header::HeaderValue;
@ -18,7 +18,7 @@ async fn main() -> io::Result<()> {
.client_disconnect(1000) .client_disconnect(1000)
.finish(|_req| { .finish(|_req| {
info!("{:?}", _req); info!("{:?}", _req);
let mut res = Response::Ok(); let mut res = Response::build(StatusCode::OK);
res.insert_header(( res.insert_header((
"x-head", "x-head",
HeaderValue::from_static("dummy value!"), HeaderValue::from_static("dummy value!"),

View File

@ -1,4 +1,5 @@
use std::{ use std::{
borrow::Cow,
fmt, mem, fmt, mem,
pin::Pin, pin::Pin,
task::{Context, Poll}, task::{Context, Poll},
@ -12,15 +13,19 @@ use crate::error::Error;
use super::{BodySize, BodyStream, MessageBody, SizedStream}; use super::{BodySize, BodyStream, MessageBody, SizedStream};
/// Represents various types of HTTP message body. /// Represents various types of HTTP message body.
// #[deprecated(since = "4.0.0", note = "Use body types directly.")]
pub enum Body { pub enum Body {
/// Empty response. `Content-Length` header is not set. /// Empty response. `Content-Length` header is not set.
None, None,
/// Zero sized response body. `Content-Length` header is set to `0`. /// Zero sized response body. `Content-Length` header is set to `0`.
Empty, Empty,
/// Specific response body. /// Specific response body.
Bytes(Bytes), Bytes(Bytes),
/// Generic message body. /// Generic message body.
Message(Box<dyn MessageBody + Unpin>), Message(Pin<Box<dyn MessageBody>>),
} }
impl Body { impl Body {
@ -30,8 +35,8 @@ impl Body {
} }
/// Create body from generic message body. /// Create body from generic message body.
pub fn from_message<B: MessageBody + Unpin + 'static>(body: B) -> Body { pub fn from_message<B: MessageBody + 'static>(body: B) -> Body {
Body::Message(Box::new(body)) Body::Message(Box::pin(body))
} }
} }
@ -60,7 +65,7 @@ impl MessageBody for Body {
Poll::Ready(Some(Ok(mem::take(bin)))) Poll::Ready(Some(Ok(mem::take(bin))))
} }
} }
Body::Message(body) => Pin::new(&mut **body).poll_next(cx), Body::Message(body) => body.as_mut().poll_next(cx),
} }
} }
} }
@ -114,12 +119,23 @@ impl From<String> for Body {
} }
} }
impl<'a> From<&'a String> for Body { impl From<&'_ String> for Body {
fn from(s: &'a String) -> Body { fn from(s: &String) -> Body {
Body::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&s))) Body::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&s)))
} }
} }
impl From<Cow<'_, str>> for Body {
fn from(s: Cow<'_, str>) -> Body {
match s {
Cow::Owned(s) => Body::from(s),
Cow::Borrowed(s) => {
Body::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(s)))
}
}
}
}
impl From<Bytes> for Body { impl From<Bytes> for Body {
fn from(s: Bytes) -> Body { fn from(s: Bytes) -> Body {
Body::Bytes(s) Body::Bytes(s)
@ -134,7 +150,7 @@ impl From<BytesMut> for Body {
impl<S> From<SizedStream<S>> for Body impl<S> From<SizedStream<S>> for Body
where where
S: Stream<Item = Result<Bytes, Error>> + Unpin + 'static, S: Stream<Item = Result<Bytes, Error>> + 'static,
{ {
fn from(s: SizedStream<S>) -> Body { fn from(s: SizedStream<S>) -> Body {
Body::from_message(s) Body::from_message(s)
@ -143,7 +159,7 @@ where
impl<S, E> From<BodyStream<S>> for Body impl<S, E> From<BodyStream<S>> for Body
where where
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static, S: Stream<Item = Result<Bytes, E>> + 'static,
E: Into<Error> + 'static, E: Into<Error> + 'static,
{ {
fn from(s: BodyStream<S>) -> Body { fn from(s: BodyStream<S>) -> Body {

View File

@ -5,21 +5,25 @@ use std::{
use bytes::Bytes; use bytes::Bytes;
use futures_core::{ready, Stream}; use futures_core::{ready, Stream};
use pin_project_lite::pin_project;
use crate::error::Error; use crate::error::Error;
use super::{BodySize, MessageBody}; use super::{BodySize, MessageBody};
pin_project! {
/// Streaming response wrapper. /// Streaming response wrapper.
/// ///
/// Response does not contain `Content-Length` header and appropriate transfer encoding is used. /// Response does not contain `Content-Length` header and appropriate transfer encoding is used.
pub struct BodyStream<S: Unpin> { pub struct BodyStream<S> {
#[pin]
stream: S, stream: S,
} }
}
impl<S, E> BodyStream<S> impl<S, E> BodyStream<S>
where where
S: Stream<Item = Result<Bytes, E>> + Unpin, S: Stream<Item = Result<Bytes, E>>,
E: Into<Error>, E: Into<Error>,
{ {
pub fn new(stream: S) -> Self { pub fn new(stream: S) -> Self {
@ -29,7 +33,7 @@ where
impl<S, E> MessageBody for BodyStream<S> impl<S, E> MessageBody for BodyStream<S>
where where
S: Stream<Item = Result<Bytes, E>> + Unpin, S: Stream<Item = Result<Bytes, E>>,
E: Into<Error>, E: Into<Error>,
{ {
fn size(&self) -> BodySize { fn size(&self) -> BodySize {
@ -46,9 +50,9 @@ where
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> { ) -> Poll<Option<Result<Bytes, Error>>> {
loop { loop {
let stream = &mut self.as_mut().stream; let stream = self.as_mut().project().stream;
let chunk = match ready!(Pin::new(stream).poll_next(cx)) { let chunk = match ready!(stream.poll_next(cx)) {
Some(Ok(ref bytes)) if bytes.is_empty() => continue, Some(Ok(ref bytes)) if bytes.is_empty() => continue,
opt => opt.map(|res| res.map_err(Into::into)), opt => opt.map(|res| res.map_err(Into::into)),
}; };
@ -57,3 +61,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")));
}
}

View File

@ -12,10 +12,12 @@ use crate::error::Error;
use super::BodySize; use super::BodySize;
/// Type that implement this trait can be streamed to a peer. /// An interface for response bodies.
pub trait MessageBody { pub trait MessageBody {
/// Body size hint.
fn size(&self) -> BodySize; fn size(&self) -> BodySize;
/// Attempt to pull out the next chunk of body bytes.
fn poll_next( fn poll_next(
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut Context<'_>,
@ -52,6 +54,19 @@ impl<T: MessageBody + Unpin> MessageBody for Box<T> {
} }
} }
impl<T: MessageBody> MessageBody for Pin<Box<T>> {
fn size(&self) -> BodySize {
self.as_ref().size()
}
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> {
self.as_mut().poll_next(cx)
}
}
impl MessageBody for Bytes { impl MessageBody for Bytes {
fn size(&self) -> BodySize { fn size(&self) -> BodySize {
BodySize::Sized(self.len() as u64) BodySize::Sized(self.len() as u64)

View File

@ -1,5 +1,12 @@
//! Traits and structures to aid consuming and writing HTTP payloads. //! Traits and structures to aid consuming and writing HTTP payloads.
use std::task::Poll;
use actix_rt::pin;
use actix_utils::future::poll_fn;
use bytes::{Bytes, BytesMut};
use futures_core::ready;
#[allow(clippy::module_inception)] #[allow(clippy::module_inception)]
mod body; mod body;
mod body_stream; mod body_stream;
@ -15,6 +22,50 @@ pub use self::response_body::ResponseBody;
pub use self::size::BodySize; pub use self::size::BodySize;
pub use self::sized_stream::SizedStream; pub use self::sized_stream::SizedStream;
/// Collects the body produced by a `MessageBody` implementation into `Bytes`.
///
/// Any errors produced by the body stream are returned immediately.
///
/// # Examples
/// ```
/// use actix_http::body::{Body, to_bytes};
/// use bytes::Bytes;
///
/// # async fn test_to_bytes() {
/// let body = Body::Empty;
/// let bytes = to_bytes(body).await.unwrap();
/// assert!(bytes.is_empty());
///
/// let body = Body::Bytes(Bytes::from_static(b"123"));
/// let bytes = to_bytes(body).await.unwrap();
/// assert_eq!(bytes, b"123"[..]);
/// # }
/// ```
pub async fn to_bytes(body: impl MessageBody) -> Result<Bytes, crate::Error> {
let cap = match body.size() {
BodySize::None | BodySize::Empty | BodySize::Sized(0) => return Ok(Bytes::new()),
BodySize::Sized(size) => size as usize,
BodySize::Stream => 32_768,
};
let mut buf = BytesMut::with_capacity(cap);
pin!(body);
poll_fn(|cx| loop {
let body = body.as_mut();
match ready!(body.poll_next(cx)) {
Some(Ok(bytes)) => buf.extend_from_slice(&*bytes),
None => return Poll::Ready(Ok(())),
Some(Err(err)) => return Poll::Ready(Err(err)),
}
})
.await?;
Ok(buf.freeze())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::pin::Pin; use std::pin::Pin;
@ -22,7 +73,6 @@ mod tests {
use actix_rt::pin; use actix_rt::pin;
use actix_utils::future::poll_fn; use actix_utils::future::poll_fn;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures_util::stream;
use super::*; use super::*;
@ -187,58 +237,6 @@ mod tests {
); );
} }
#[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")),
);
}
}
#[actix_rt::test] #[actix_rt::test]
async fn test_body_casting() { async fn test_body_casting() {
let mut body = String::from("hello cast"); let mut body = String::from("hello cast");
@ -252,4 +250,15 @@ mod tests {
let not_body = resp_body.downcast_ref::<()>(); let not_body = resp_body.downcast_ref::<()>();
assert!(not_body.is_none()); assert!(not_body.is_none());
} }
#[actix_rt::test]
async fn test_to_bytes() {
let body = Body::Empty;
let bytes = to_bytes(body).await.unwrap();
assert!(bytes.is_empty());
let body = Body::Bytes(Bytes::from_static(b"123"));
let bytes = to_bytes(body).await.unwrap();
assert_eq!(bytes, b"123"[..]);
}
} }

View File

@ -55,10 +55,7 @@ impl<B: MessageBody> MessageBody for ResponseBody<B> {
self: Pin<&mut Self>, self: Pin<&mut Self>,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> { ) -> Poll<Option<Result<Bytes, Error>>> {
match self.project() { Stream::poll_next(self, cx)
ResponseBodyProj::Body(body) => body.poll_next(cx),
ResponseBodyProj::Other(body) => Pin::new(body).poll_next(cx),
}
} }
} }

View File

@ -5,23 +5,27 @@ use std::{
use bytes::Bytes; use bytes::Bytes;
use futures_core::{ready, Stream}; use futures_core::{ready, Stream};
use pin_project_lite::pin_project;
use crate::error::Error; use crate::error::Error;
use super::{BodySize, MessageBody}; use super::{BodySize, MessageBody};
pin_project! {
/// Known sized streaming response wrapper. /// Known sized streaming response wrapper.
/// ///
/// This body implementation should be used if total size of stream is known. Data get sent as is /// This body implementation should be used if total size of stream is known. Data get sent as is
/// without using transfer encoding. /// without using transfer encoding.
pub struct SizedStream<S: Unpin> { pub struct SizedStream<S> {
size: u64, size: u64,
#[pin]
stream: S, stream: S,
} }
}
impl<S> SizedStream<S> impl<S> SizedStream<S>
where where
S: Stream<Item = Result<Bytes, Error>> + Unpin, S: Stream<Item = Result<Bytes, Error>>,
{ {
pub fn new(size: u64, stream: S) -> Self { pub fn new(size: u64, stream: S) -> Self {
SizedStream { size, stream } SizedStream { size, stream }
@ -30,7 +34,7 @@ where
impl<S> MessageBody for SizedStream<S> impl<S> MessageBody for SizedStream<S>
where where
S: Stream<Item = Result<Bytes, Error>> + Unpin, S: Stream<Item = Result<Bytes, Error>>,
{ {
fn size(&self) -> BodySize { fn size(&self) -> BodySize {
BodySize::Sized(self.size as u64) BodySize::Sized(self.size as u64)
@ -46,9 +50,9 @@ where
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<Option<Result<Bytes, Error>>> { ) -> Poll<Option<Result<Bytes, Error>>> {
loop { loop {
let stream = &mut self.as_mut().stream; let stream = self.as_mut().project().stream;
let chunk = match ready!(Pin::new(stream).poll_next(cx)) { let chunk = match ready!(stream.poll_next(cx)) {
Some(Ok(ref bytes)) if bytes.is_empty() => continue, Some(Ok(ref bytes)) if bytes.is_empty() => continue,
val => val, val => val,
}; };
@ -57,3 +61,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")));
}
}

View File

@ -92,7 +92,7 @@ impl<B: MessageBody> Encoder<B> {
enum EncoderBody<B> { enum EncoderBody<B> {
Bytes(Bytes), Bytes(Bytes),
Stream(#[pin] B), Stream(#[pin] B),
BoxedStream(Box<dyn MessageBody + Unpin>), BoxedStream(Pin<Box<dyn MessageBody>>),
} }
impl<B: MessageBody> MessageBody for EncoderBody<B> { impl<B: MessageBody> MessageBody for EncoderBody<B> {
@ -117,9 +117,7 @@ impl<B: MessageBody> MessageBody for EncoderBody<B> {
} }
} }
EncoderBodyProj::Stream(b) => b.poll_next(cx), EncoderBodyProj::Stream(b) => b.poll_next(cx),
EncoderBodyProj::BoxedStream(ref mut b) => { EncoderBodyProj::BoxedStream(ref mut b) => b.as_mut().poll_next(cx),
Pin::new(b.as_mut()).poll_next(cx)
}
} }
} }
} }

View File

@ -10,18 +10,17 @@ use std::{
use bytes::BytesMut; use bytes::BytesMut;
use derive_more::{Display, Error, From}; use derive_more::{Display, Error, From};
use http::uri::InvalidUri; use http::{header, uri::InvalidUri, StatusCode};
use http::{header, Error as HttpError, StatusCode};
use serde::de::value::Error as DeError; use serde::de::value::Error as DeError;
use crate::{body::Body, helpers::Writer, Response, ResponseBuilder}; use crate::{body::Body, helpers::Writer, Response, ResponseBuilder};
/// A specialized [`std::result::Result`] pub use http::Error as HttpError;
/// for actix web operations
/// A specialized [`std::result::Result`] for Actix Web operations.
/// ///
/// This typedef is generally used to avoid writing out /// This typedef is generally used to avoid writing out `actix_http::error::Error` directly and is
/// `actix_http::error::Error` directly and is otherwise a direct mapping to /// otherwise a direct mapping to `Result`.
/// `Result`.
pub type Result<T, E = Error> = std::result::Result<T, E>; pub type Result<T, E = Error> = std::result::Result<T, E>;
/// General purpose actix web error. /// General purpose actix web error.
@ -50,19 +49,21 @@ impl Error {
} }
} }
/// Error that can be converted to `Response` /// Errors that can generate responses.
pub trait ResponseError: fmt::Debug + fmt::Display { pub trait ResponseError: fmt::Debug + fmt::Display {
/// Response's status code /// Returns appropriate status code for error.
/// ///
/// Internal server error is generated by default. /// A 500 Internal Server Error is used by default. If [error_response](Self::error_response) is
/// also implemented and does not call `self.status_code()`, then this will not be used.
fn status_code(&self) -> StatusCode { fn status_code(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR StatusCode::INTERNAL_SERVER_ERROR
} }
/// Create response for error /// Creates full response for error.
/// ///
/// Internal server error is generated by default. /// By default, the generated response uses a 500 Internal Server Error status code, a
fn error_response(&self) -> Response { /// `Content-Type` of `text/plain`, and the body is set to `Self`'s `Display` impl.
fn error_response(&self) -> Response<Body> {
let mut resp = Response::new(self.status_code()); let mut resp = Response::new(self.status_code());
let mut buf = BytesMut::new(); let mut buf = BytesMut::new();
let _ = write!(Writer(&mut buf), "{}", self); let _ = write!(Writer(&mut buf), "{}", self);
@ -111,7 +112,7 @@ impl From<std::convert::Infallible> for Error {
} }
/// Convert `Error` to a `Response` instance /// Convert `Error` to a `Response` instance
impl From<Error> for Response { impl From<Error> for Response<Body> {
fn from(err: Error) -> Self { fn from(err: Error) -> Self {
Response::from_error(err) Response::from_error(err)
} }
@ -127,8 +128,8 @@ impl<T: ResponseError + 'static> From<T> for Error {
} }
/// Convert Response to a Error /// Convert Response to a Error
impl From<Response> for Error { impl From<Response<Body>> for Error {
fn from(res: Response) -> Error { fn from(res: Response<Body>) -> Error {
InternalError::from_response("", res).into() InternalError::from_response("", res).into()
} }
} }
@ -140,7 +141,7 @@ impl From<ResponseBuilder> for Error {
} }
} }
#[derive(Debug, Display)] #[derive(Debug, Display, Error)]
#[display(fmt = "Unknown Error")] #[display(fmt = "Unknown Error")]
struct UnitError; struct UnitError;
@ -190,38 +191,47 @@ impl ResponseError for header::InvalidHeaderValue {
} }
} }
/// A set of errors that can occur during parsing HTTP streams /// A set of errors that can occur during parsing HTTP streams.
#[derive(Debug, Display)] #[derive(Debug, Display, Error)]
#[non_exhaustive]
pub enum ParseError { pub enum ParseError {
/// An invalid `Method`, such as `GE.T`. /// An invalid `Method`, such as `GE.T`.
#[display(fmt = "Invalid Method specified")] #[display(fmt = "Invalid Method specified")]
Method, Method,
/// An invalid `Uri`, such as `exam ple.domain`. /// An invalid `Uri`, such as `exam ple.domain`.
#[display(fmt = "Uri error: {}", _0)] #[display(fmt = "Uri error: {}", _0)]
Uri(InvalidUri), Uri(InvalidUri),
/// An invalid `HttpVersion`, such as `HTP/1.1` /// An invalid `HttpVersion`, such as `HTP/1.1`
#[display(fmt = "Invalid HTTP version specified")] #[display(fmt = "Invalid HTTP version specified")]
Version, Version,
/// An invalid `Header`. /// An invalid `Header`.
#[display(fmt = "Invalid Header provided")] #[display(fmt = "Invalid Header provided")]
Header, Header,
/// A message head is too large to be reasonable. /// A message head is too large to be reasonable.
#[display(fmt = "Message head is too large")] #[display(fmt = "Message head is too large")]
TooLarge, TooLarge,
/// A message reached EOF, but is not complete. /// A message reached EOF, but is not complete.
#[display(fmt = "Message is incomplete")] #[display(fmt = "Message is incomplete")]
Incomplete, Incomplete,
/// An invalid `Status`, such as `1337 ELITE`. /// An invalid `Status`, such as `1337 ELITE`.
#[display(fmt = "Invalid Status provided")] #[display(fmt = "Invalid Status provided")]
Status, Status,
/// A timeout occurred waiting for an IO event. /// A timeout occurred waiting for an IO event.
#[allow(dead_code)] #[allow(dead_code)]
#[display(fmt = "Timeout")] #[display(fmt = "Timeout")]
Timeout, Timeout,
/// An `io::Error` that occurred while trying to read or write to a network
/// stream. /// An `io::Error` that occurred while trying to read or write to a network stream.
#[display(fmt = "IO error: {}", _0)] #[display(fmt = "IO error: {}", _0)]
Io(io::Error), Io(io::Error),
/// Parsing a field as string failed /// Parsing a field as string failed
#[display(fmt = "UTF8 error: {}", _0)] #[display(fmt = "UTF8 error: {}", _0)]
Utf8(Utf8Error), Utf8(Utf8Error),
@ -273,17 +283,16 @@ impl From<httparse::Error> for ParseError {
} }
/// A set of errors that can occur running blocking tasks in thread pool. /// A set of errors that can occur running blocking tasks in thread pool.
#[derive(Debug, Display)] #[derive(Debug, Display, Error)]
#[display(fmt = "Blocking thread pool is gone")] #[display(fmt = "Blocking thread pool is gone")]
pub struct BlockingError; pub struct BlockingError;
impl std::error::Error for BlockingError {}
/// `InternalServerError` for `BlockingError` /// `InternalServerError` for `BlockingError`
impl ResponseError for BlockingError {} impl ResponseError for BlockingError {}
#[derive(Display, Debug)] /// A set of errors that can occur during payload parsing.
/// A set of errors that can occur during payload parsing #[derive(Debug, Display)]
#[non_exhaustive]
pub enum PayloadError { pub enum PayloadError {
/// A payload reached EOF, but is not complete. /// A payload reached EOF, but is not complete.
#[display( #[display(
@ -367,8 +376,9 @@ impl ResponseError for PayloadError {
} }
} }
#[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 { pub enum DispatchError {
/// Service error /// Service error
Service(Error), Service(Error),
@ -414,8 +424,9 @@ pub enum DispatchError {
Unknown, Unknown,
} }
/// A set of error that can occur during parsing content type /// A set of error that can occur during parsing content type.
#[derive(Debug, PartialEq, Display, Error)] #[derive(Debug, Display, Error)]
#[non_exhaustive]
pub enum ContentTypeError { pub enum ContentTypeError {
/// Can not parse content type /// Can not parse content type
#[display(fmt = "Can not parse content type")] #[display(fmt = "Can not parse content type")]
@ -426,6 +437,22 @@ pub enum ContentTypeError {
UnknownEncoding, UnknownEncoding,
} }
#[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` /// Return `BadRequest` for `ContentTypeError`
impl ResponseError for ContentTypeError { impl ResponseError for ContentTypeError {
fn status_code(&self) -> StatusCode { fn status_code(&self) -> StatusCode {
@ -454,7 +481,7 @@ pub struct InternalError<T> {
enum InternalErrorType { enum InternalErrorType {
Status(StatusCode), Status(StatusCode),
Response(RefCell<Option<Response>>), Response(RefCell<Option<Response<Body>>>),
} }
impl<T> InternalError<T> { impl<T> InternalError<T> {
@ -467,7 +494,7 @@ impl<T> InternalError<T> {
} }
/// Create `InternalError` with predefined `Response`. /// Create `InternalError` with predefined `Response`.
pub fn from_response(cause: T, response: Response) -> Self { pub fn from_response(cause: T, response: Response<Body>) -> Self {
InternalError { InternalError {
cause, cause,
status: InternalErrorType::Response(RefCell::new(Some(response))), status: InternalErrorType::Response(RefCell::new(Some(response))),
@ -510,7 +537,7 @@ where
} }
} }
fn error_response(&self) -> Response { fn error_response(&self) -> Response<Body> {
match self.status { match self.status {
InternalErrorType::Status(st) => { InternalErrorType::Status(st) => {
let mut res = Response::new(st); let mut res = Response::new(st);
@ -533,395 +560,72 @@ where
} }
} }
/// Helper function that creates wrapper of any error and generate *BAD macro_rules! error_helper {
/// REQUEST* response. ($name:ident, $status:ident) => {
paste::paste! {
#[doc = "Helper function that wraps any error and generates a `" $status "` response."]
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn ErrorBadRequest<T>(err: T) -> Error pub fn $name<T>(err: T) -> Error
where where
T: fmt::Debug + fmt::Display + 'static, T: fmt::Debug + fmt::Display + 'static,
{ {
InternalError::new(err, StatusCode::BAD_REQUEST).into() InternalError::new(err, StatusCode::$status).into()
}
}
}
} }
/// Helper function that creates wrapper of any error and generate error_helper!(ErrorBadRequest, BAD_REQUEST);
/// *UNAUTHORIZED* response. error_helper!(ErrorUnauthorized, UNAUTHORIZED);
#[allow(non_snake_case)] error_helper!(ErrorPaymentRequired, PAYMENT_REQUIRED);
pub fn ErrorUnauthorized<T>(err: T) -> Error error_helper!(ErrorForbidden, FORBIDDEN);
where error_helper!(ErrorNotFound, NOT_FOUND);
T: fmt::Debug + fmt::Display + 'static, error_helper!(ErrorMethodNotAllowed, METHOD_NOT_ALLOWED);
{ error_helper!(ErrorNotAcceptable, NOT_ACCEPTABLE);
InternalError::new(err, StatusCode::UNAUTHORIZED).into() error_helper!(
} ErrorProxyAuthenticationRequired,
PROXY_AUTHENTICATION_REQUIRED
/// Helper function that creates wrapper of any error and generate );
/// *PAYMENT_REQUIRED* response. error_helper!(ErrorRequestTimeout, REQUEST_TIMEOUT);
#[allow(non_snake_case)] error_helper!(ErrorConflict, CONFLICT);
pub fn ErrorPaymentRequired<T>(err: T) -> Error error_helper!(ErrorGone, GONE);
where error_helper!(ErrorLengthRequired, LENGTH_REQUIRED);
T: fmt::Debug + fmt::Display + 'static, error_helper!(ErrorPayloadTooLarge, PAYLOAD_TOO_LARGE);
{ error_helper!(ErrorUriTooLong, URI_TOO_LONG);
InternalError::new(err, StatusCode::PAYMENT_REQUIRED).into() error_helper!(ErrorUnsupportedMediaType, UNSUPPORTED_MEDIA_TYPE);
} error_helper!(ErrorRangeNotSatisfiable, RANGE_NOT_SATISFIABLE);
error_helper!(ErrorImATeapot, IM_A_TEAPOT);
/// Helper function that creates wrapper of any error and generate *FORBIDDEN* error_helper!(ErrorMisdirectedRequest, MISDIRECTED_REQUEST);
/// response. error_helper!(ErrorUnprocessableEntity, UNPROCESSABLE_ENTITY);
#[allow(non_snake_case)] error_helper!(ErrorLocked, LOCKED);
pub fn ErrorForbidden<T>(err: T) -> Error error_helper!(ErrorFailedDependency, FAILED_DEPENDENCY);
where error_helper!(ErrorUpgradeRequired, UPGRADE_REQUIRED);
T: fmt::Debug + fmt::Display + 'static, error_helper!(ErrorPreconditionFailed, PRECONDITION_FAILED);
{ error_helper!(ErrorPreconditionRequired, PRECONDITION_REQUIRED);
InternalError::new(err, StatusCode::FORBIDDEN).into() error_helper!(ErrorTooManyRequests, TOO_MANY_REQUESTS);
} error_helper!(
ErrorRequestHeaderFieldsTooLarge,
/// Helper function that creates wrapper of any error and generate *NOT FOUND* REQUEST_HEADER_FIELDS_TOO_LARGE
/// response. );
#[allow(non_snake_case)] error_helper!(
pub fn ErrorNotFound<T>(err: T) -> Error ErrorUnavailableForLegalReasons,
where UNAVAILABLE_FOR_LEGAL_REASONS
T: fmt::Debug + fmt::Display + 'static, );
{ error_helper!(ErrorExpectationFailed, EXPECTATION_FAILED);
InternalError::new(err, StatusCode::NOT_FOUND).into() error_helper!(ErrorInternalServerError, INTERNAL_SERVER_ERROR);
} error_helper!(ErrorNotImplemented, NOT_IMPLEMENTED);
error_helper!(ErrorBadGateway, BAD_GATEWAY);
/// Helper function that creates wrapper of any error and generate *METHOD NOT error_helper!(ErrorServiceUnavailable, SERVICE_UNAVAILABLE);
/// ALLOWED* response. error_helper!(ErrorGatewayTimeout, GATEWAY_TIMEOUT);
#[allow(non_snake_case)] error_helper!(ErrorHttpVersionNotSupported, HTTP_VERSION_NOT_SUPPORTED);
pub fn ErrorMethodNotAllowed<T>(err: T) -> Error error_helper!(ErrorVariantAlsoNegotiates, VARIANT_ALSO_NEGOTIATES);
where error_helper!(ErrorInsufficientStorage, INSUFFICIENT_STORAGE);
T: fmt::Debug + fmt::Display + 'static, error_helper!(ErrorLoopDetected, LOOP_DETECTED);
{ error_helper!(ErrorNotExtended, NOT_EXTENDED);
InternalError::new(err, StatusCode::METHOD_NOT_ALLOWED).into() error_helper!(
} ErrorNetworkAuthenticationRequired,
NETWORK_AUTHENTICATION_REQUIRED
/// Helper function that creates wrapper of any error and generate *NOT );
/// ACCEPTABLE* response.
#[allow(non_snake_case)]
pub fn ErrorNotAcceptable<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::NOT_ACCEPTABLE).into()
}
/// Helper function that creates wrapper of any error and generate *PROXY
/// AUTHENTICATION REQUIRED* response.
#[allow(non_snake_case)]
pub fn ErrorProxyAuthenticationRequired<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::PROXY_AUTHENTICATION_REQUIRED).into()
}
/// Helper function that creates wrapper of any error and generate *REQUEST
/// TIMEOUT* response.
#[allow(non_snake_case)]
pub fn ErrorRequestTimeout<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::REQUEST_TIMEOUT).into()
}
/// Helper function that creates wrapper of any error and generate *CONFLICT*
/// response.
#[allow(non_snake_case)]
pub fn ErrorConflict<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::CONFLICT).into()
}
/// Helper function that creates wrapper of any error and generate *GONE*
/// response.
#[allow(non_snake_case)]
pub fn ErrorGone<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::GONE).into()
}
/// Helper function that creates wrapper of any error and generate *LENGTH
/// REQUIRED* response.
#[allow(non_snake_case)]
pub fn ErrorLengthRequired<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::LENGTH_REQUIRED).into()
}
/// Helper function that creates wrapper of any error and generate
/// *PAYLOAD TOO LARGE* response.
#[allow(non_snake_case)]
pub fn ErrorPayloadTooLarge<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::PAYLOAD_TOO_LARGE).into()
}
/// Helper function that creates wrapper of any error and generate
/// *URI TOO LONG* response.
#[allow(non_snake_case)]
pub fn ErrorUriTooLong<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::URI_TOO_LONG).into()
}
/// Helper function that creates wrapper of any error and generate
/// *UNSUPPORTED MEDIA TYPE* response.
#[allow(non_snake_case)]
pub fn ErrorUnsupportedMediaType<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::UNSUPPORTED_MEDIA_TYPE).into()
}
/// Helper function that creates wrapper of any error and generate
/// *RANGE NOT SATISFIABLE* response.
#[allow(non_snake_case)]
pub fn ErrorRangeNotSatisfiable<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::RANGE_NOT_SATISFIABLE).into()
}
/// Helper function that creates wrapper of any error and generate
/// *IM A TEAPOT* response.
#[allow(non_snake_case)]
pub fn ErrorImATeapot<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::IM_A_TEAPOT).into()
}
/// Helper function that creates wrapper of any error and generate
/// *MISDIRECTED REQUEST* response.
#[allow(non_snake_case)]
pub fn ErrorMisdirectedRequest<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::MISDIRECTED_REQUEST).into()
}
/// Helper function that creates wrapper of any error and generate
/// *UNPROCESSABLE ENTITY* response.
#[allow(non_snake_case)]
pub fn ErrorUnprocessableEntity<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::UNPROCESSABLE_ENTITY).into()
}
/// Helper function that creates wrapper of any error and generate
/// *LOCKED* response.
#[allow(non_snake_case)]
pub fn ErrorLocked<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::LOCKED).into()
}
/// Helper function that creates wrapper of any error and generate
/// *FAILED DEPENDENCY* response.
#[allow(non_snake_case)]
pub fn ErrorFailedDependency<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::FAILED_DEPENDENCY).into()
}
/// Helper function that creates wrapper of any error and generate
/// *UPGRADE REQUIRED* response.
#[allow(non_snake_case)]
pub fn ErrorUpgradeRequired<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::UPGRADE_REQUIRED).into()
}
/// Helper function that creates wrapper of any error and generate
/// *PRECONDITION FAILED* response.
#[allow(non_snake_case)]
pub fn ErrorPreconditionFailed<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::PRECONDITION_FAILED).into()
}
/// Helper function that creates wrapper of any error and generate
/// *PRECONDITION REQUIRED* response.
#[allow(non_snake_case)]
pub fn ErrorPreconditionRequired<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::PRECONDITION_REQUIRED).into()
}
/// Helper function that creates wrapper of any error and generate
/// *TOO MANY REQUESTS* response.
#[allow(non_snake_case)]
pub fn ErrorTooManyRequests<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::TOO_MANY_REQUESTS).into()
}
/// Helper function that creates wrapper of any error and generate
/// *REQUEST HEADER FIELDS TOO LARGE* response.
#[allow(non_snake_case)]
pub fn ErrorRequestHeaderFieldsTooLarge<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE).into()
}
/// Helper function that creates wrapper of any error and generate
/// *UNAVAILABLE FOR LEGAL REASONS* response.
#[allow(non_snake_case)]
pub fn ErrorUnavailableForLegalReasons<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS).into()
}
/// Helper function that creates wrapper of any error and generate
/// *EXPECTATION FAILED* response.
#[allow(non_snake_case)]
pub fn ErrorExpectationFailed<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::EXPECTATION_FAILED).into()
}
/// Helper function that creates wrapper of any error and
/// generate *INTERNAL SERVER ERROR* response.
#[allow(non_snake_case)]
pub fn ErrorInternalServerError<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::INTERNAL_SERVER_ERROR).into()
}
/// Helper function that creates wrapper of any error and
/// generate *NOT IMPLEMENTED* response.
#[allow(non_snake_case)]
pub fn ErrorNotImplemented<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::NOT_IMPLEMENTED).into()
}
/// Helper function that creates wrapper of any error and
/// generate *BAD GATEWAY* response.
#[allow(non_snake_case)]
pub fn ErrorBadGateway<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::BAD_GATEWAY).into()
}
/// Helper function that creates wrapper of any error and
/// generate *SERVICE UNAVAILABLE* response.
#[allow(non_snake_case)]
pub fn ErrorServiceUnavailable<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::SERVICE_UNAVAILABLE).into()
}
/// Helper function that creates wrapper of any error and
/// generate *GATEWAY TIMEOUT* response.
#[allow(non_snake_case)]
pub fn ErrorGatewayTimeout<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::GATEWAY_TIMEOUT).into()
}
/// Helper function that creates wrapper of any error and
/// generate *HTTP VERSION NOT SUPPORTED* response.
#[allow(non_snake_case)]
pub fn ErrorHttpVersionNotSupported<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::HTTP_VERSION_NOT_SUPPORTED).into()
}
/// Helper function that creates wrapper of any error and
/// generate *VARIANT ALSO NEGOTIATES* response.
#[allow(non_snake_case)]
pub fn ErrorVariantAlsoNegotiates<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::VARIANT_ALSO_NEGOTIATES).into()
}
/// Helper function that creates wrapper of any error and
/// generate *INSUFFICIENT STORAGE* response.
#[allow(non_snake_case)]
pub fn ErrorInsufficientStorage<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::INSUFFICIENT_STORAGE).into()
}
/// Helper function that creates wrapper of any error and
/// generate *LOOP DETECTED* response.
#[allow(non_snake_case)]
pub fn ErrorLoopDetected<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::LOOP_DETECTED).into()
}
/// Helper function that creates wrapper of any error and
/// generate *NOT EXTENDED* response.
#[allow(non_snake_case)]
pub fn ErrorNotExtended<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::NOT_EXTENDED).into()
}
/// Helper function that creates wrapper of any error and
/// generate *NETWORK AUTHENTICATION REQUIRED* response.
#[allow(non_snake_case)]
pub fn ErrorNetworkAuthenticationRequired<T>(err: T) -> Error
where
T: fmt::Debug + fmt::Display + 'static,
{
InternalError::new(err, StatusCode::NETWORK_AUTHENTICATION_REQUIRED).into()
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@ -931,11 +635,11 @@ mod tests {
#[test] #[test]
fn test_into_response() { fn test_into_response() {
let resp: Response = ParseError::Incomplete.error_response(); let resp: Response<Body> = ParseError::Incomplete.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into(); let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
let resp: Response = err.error_response(); let resp: Response<Body> = err.error_response();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} }
@ -966,7 +670,7 @@ mod tests {
fn test_error_http_response() { fn test_error_http_response() {
let orig = io::Error::new(io::ErrorKind::Other, "other"); let orig = io::Error::new(io::ErrorKind::Other, "other");
let e = Error::from(orig); let e = Error::from(orig);
let resp: Response = e.into(); let resp: Response<Body> = e.into();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} }
@ -1021,9 +725,8 @@ mod tests {
#[test] #[test]
fn test_internal_error() { fn test_internal_error() {
let err = let err = InternalError::from_response(ParseError::Method, Response::ok());
InternalError::from_response(ParseError::Method, Response::Ok().into()); let resp: Response<Body> = err.error_response();
let resp: Response = err.error_response();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
@ -1039,121 +742,121 @@ mod tests {
#[test] #[test]
fn test_error_helpers() { fn test_error_helpers() {
let r: Response = ErrorBadRequest("err").into(); let res: Response<Body> = ErrorBadRequest("err").into();
assert_eq!(r.status(), StatusCode::BAD_REQUEST); assert_eq!(res.status(), StatusCode::BAD_REQUEST);
let r: Response = ErrorUnauthorized("err").into(); let res: Response<Body> = ErrorUnauthorized("err").into();
assert_eq!(r.status(), StatusCode::UNAUTHORIZED); assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
let r: Response = ErrorPaymentRequired("err").into(); let res: Response<Body> = ErrorPaymentRequired("err").into();
assert_eq!(r.status(), StatusCode::PAYMENT_REQUIRED); assert_eq!(res.status(), StatusCode::PAYMENT_REQUIRED);
let r: Response = ErrorForbidden("err").into(); let res: Response<Body> = ErrorForbidden("err").into();
assert_eq!(r.status(), StatusCode::FORBIDDEN); assert_eq!(res.status(), StatusCode::FORBIDDEN);
let r: Response = ErrorNotFound("err").into(); let res: Response<Body> = ErrorNotFound("err").into();
assert_eq!(r.status(), StatusCode::NOT_FOUND); assert_eq!(res.status(), StatusCode::NOT_FOUND);
let r: Response = ErrorMethodNotAllowed("err").into(); let res: Response<Body> = ErrorMethodNotAllowed("err").into();
assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED); assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
let r: Response = ErrorNotAcceptable("err").into(); let res: Response<Body> = ErrorNotAcceptable("err").into();
assert_eq!(r.status(), StatusCode::NOT_ACCEPTABLE); assert_eq!(res.status(), StatusCode::NOT_ACCEPTABLE);
let r: Response = ErrorProxyAuthenticationRequired("err").into(); let res: Response<Body> = ErrorProxyAuthenticationRequired("err").into();
assert_eq!(r.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED); assert_eq!(res.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);
let r: Response = ErrorRequestTimeout("err").into(); let res: Response<Body> = ErrorRequestTimeout("err").into();
assert_eq!(r.status(), StatusCode::REQUEST_TIMEOUT); assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
let r: Response = ErrorConflict("err").into(); let res: Response<Body> = ErrorConflict("err").into();
assert_eq!(r.status(), StatusCode::CONFLICT); assert_eq!(res.status(), StatusCode::CONFLICT);
let r: Response = ErrorGone("err").into(); let res: Response<Body> = ErrorGone("err").into();
assert_eq!(r.status(), StatusCode::GONE); assert_eq!(res.status(), StatusCode::GONE);
let r: Response = ErrorLengthRequired("err").into(); let res: Response<Body> = ErrorLengthRequired("err").into();
assert_eq!(r.status(), StatusCode::LENGTH_REQUIRED); assert_eq!(res.status(), StatusCode::LENGTH_REQUIRED);
let r: Response = ErrorPreconditionFailed("err").into(); let res: Response<Body> = ErrorPreconditionFailed("err").into();
assert_eq!(r.status(), StatusCode::PRECONDITION_FAILED); assert_eq!(res.status(), StatusCode::PRECONDITION_FAILED);
let r: Response = ErrorPayloadTooLarge("err").into(); let res: Response<Body> = ErrorPayloadTooLarge("err").into();
assert_eq!(r.status(), StatusCode::PAYLOAD_TOO_LARGE); assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
let r: Response = ErrorUriTooLong("err").into(); let res: Response<Body> = ErrorUriTooLong("err").into();
assert_eq!(r.status(), StatusCode::URI_TOO_LONG); assert_eq!(res.status(), StatusCode::URI_TOO_LONG);
let r: Response = ErrorUnsupportedMediaType("err").into(); let res: Response<Body> = ErrorUnsupportedMediaType("err").into();
assert_eq!(r.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
let r: Response = ErrorRangeNotSatisfiable("err").into(); let res: Response<Body> = ErrorRangeNotSatisfiable("err").into();
assert_eq!(r.status(), StatusCode::RANGE_NOT_SATISFIABLE); assert_eq!(res.status(), StatusCode::RANGE_NOT_SATISFIABLE);
let r: Response = ErrorExpectationFailed("err").into(); let res: Response<Body> = ErrorExpectationFailed("err").into();
assert_eq!(r.status(), StatusCode::EXPECTATION_FAILED); assert_eq!(res.status(), StatusCode::EXPECTATION_FAILED);
let r: Response = ErrorImATeapot("err").into(); let res: Response<Body> = ErrorImATeapot("err").into();
assert_eq!(r.status(), StatusCode::IM_A_TEAPOT); assert_eq!(res.status(), StatusCode::IM_A_TEAPOT);
let r: Response = ErrorMisdirectedRequest("err").into(); let res: Response<Body> = ErrorMisdirectedRequest("err").into();
assert_eq!(r.status(), StatusCode::MISDIRECTED_REQUEST); assert_eq!(res.status(), StatusCode::MISDIRECTED_REQUEST);
let r: Response = ErrorUnprocessableEntity("err").into(); let res: Response<Body> = ErrorUnprocessableEntity("err").into();
assert_eq!(r.status(), StatusCode::UNPROCESSABLE_ENTITY); assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
let r: Response = ErrorLocked("err").into(); let res: Response<Body> = ErrorLocked("err").into();
assert_eq!(r.status(), StatusCode::LOCKED); assert_eq!(res.status(), StatusCode::LOCKED);
let r: Response = ErrorFailedDependency("err").into(); let res: Response<Body> = ErrorFailedDependency("err").into();
assert_eq!(r.status(), StatusCode::FAILED_DEPENDENCY); assert_eq!(res.status(), StatusCode::FAILED_DEPENDENCY);
let r: Response = ErrorUpgradeRequired("err").into(); let res: Response<Body> = ErrorUpgradeRequired("err").into();
assert_eq!(r.status(), StatusCode::UPGRADE_REQUIRED); assert_eq!(res.status(), StatusCode::UPGRADE_REQUIRED);
let r: Response = ErrorPreconditionRequired("err").into(); let res: Response<Body> = ErrorPreconditionRequired("err").into();
assert_eq!(r.status(), StatusCode::PRECONDITION_REQUIRED); assert_eq!(res.status(), StatusCode::PRECONDITION_REQUIRED);
let r: Response = ErrorTooManyRequests("err").into(); let res: Response<Body> = ErrorTooManyRequests("err").into();
assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS); assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
let r: Response = ErrorRequestHeaderFieldsTooLarge("err").into(); let res: Response<Body> = ErrorRequestHeaderFieldsTooLarge("err").into();
assert_eq!(r.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE); assert_eq!(res.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE);
let r: Response = ErrorUnavailableForLegalReasons("err").into(); let res: Response<Body> = ErrorUnavailableForLegalReasons("err").into();
assert_eq!(r.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS); assert_eq!(res.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS);
let r: Response = ErrorInternalServerError("err").into(); let res: Response<Body> = ErrorInternalServerError("err").into();
assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
let r: Response = ErrorNotImplemented("err").into(); let res: Response<Body> = ErrorNotImplemented("err").into();
assert_eq!(r.status(), StatusCode::NOT_IMPLEMENTED); assert_eq!(res.status(), StatusCode::NOT_IMPLEMENTED);
let r: Response = ErrorBadGateway("err").into(); let res: Response<Body> = ErrorBadGateway("err").into();
assert_eq!(r.status(), StatusCode::BAD_GATEWAY); assert_eq!(res.status(), StatusCode::BAD_GATEWAY);
let r: Response = ErrorServiceUnavailable("err").into(); let res: Response<Body> = ErrorServiceUnavailable("err").into();
assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
let r: Response = ErrorGatewayTimeout("err").into(); let res: Response<Body> = ErrorGatewayTimeout("err").into();
assert_eq!(r.status(), StatusCode::GATEWAY_TIMEOUT); assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
let r: Response = ErrorHttpVersionNotSupported("err").into(); let res: Response<Body> = ErrorHttpVersionNotSupported("err").into();
assert_eq!(r.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED); assert_eq!(res.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);
let r: Response = ErrorVariantAlsoNegotiates("err").into(); let res: Response<Body> = ErrorVariantAlsoNegotiates("err").into();
assert_eq!(r.status(), StatusCode::VARIANT_ALSO_NEGOTIATES); assert_eq!(res.status(), StatusCode::VARIANT_ALSO_NEGOTIATES);
let r: Response = ErrorInsufficientStorage("err").into(); let res: Response<Body> = ErrorInsufficientStorage("err").into();
assert_eq!(r.status(), StatusCode::INSUFFICIENT_STORAGE); assert_eq!(res.status(), StatusCode::INSUFFICIENT_STORAGE);
let r: Response = ErrorLoopDetected("err").into(); let res: Response<Body> = ErrorLoopDetected("err").into();
assert_eq!(r.status(), StatusCode::LOOP_DETECTED); assert_eq!(res.status(), StatusCode::LOOP_DETECTED);
let r: Response = ErrorNotExtended("err").into(); let res: Response<Body> = ErrorNotExtended("err").into();
assert_eq!(r.status(), StatusCode::NOT_EXTENDED); assert_eq!(res.status(), StatusCode::NOT_EXTENDED);
let r: Response = ErrorNetworkAuthenticationRequired("err").into(); let res: Response<Body> = ErrorNetworkAuthenticationRequired("err").into();
assert_eq!(r.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED); assert_eq!(res.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED);
} }
} }

View File

@ -1213,8 +1213,9 @@ mod tests {
#[test] #[test]
fn test_parse_chunked_payload_chunk_extension() { fn test_parse_chunked_payload_chunk_extension() {
let mut buf = BytesMut::from( let mut buf = BytesMut::from(
&"GET /test HTTP/1.1\r\n\ "GET /test HTTP/1.1\r\n\
transfer-encoding: chunked\r\n\r\n"[..], transfer-encoding: chunked\r\n\
\r\n",
); );
let mut reader = MessageDecoder::<Request>::default(); let mut reader = MessageDecoder::<Request>::default();
@ -1233,7 +1234,7 @@ mod tests {
#[test] #[test]
fn test_response_http10_read_until_eof() { fn test_response_http10_read_until_eof() {
let mut buf = BytesMut::from(&"HTTP/1.0 200 Ok\r\n\r\ntest data"[..]); let mut buf = BytesMut::from("HTTP/1.0 200 Ok\r\n\r\ntest data");
let mut reader = MessageDecoder::<ResponseHead>::default(); let mut reader = MessageDecoder::<ResponseHead>::default();
let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap(); let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();

View File

@ -21,6 +21,7 @@ use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::config::ServiceConfig; use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error}; use crate::error::{DispatchError, Error};
use crate::error::{ParseError, PayloadError}; use crate::error::{ParseError, PayloadError};
use crate::http::StatusCode;
use crate::request::Request; use crate::request::Request;
use crate::response::Response; use crate::response::Response;
use crate::service::HttpFlow; use crate::service::HttpFlow;
@ -407,7 +408,7 @@ where
} }
// send expect error as response // send expect error as response
Poll::Ready(Err(err)) => { Poll::Ready(Err(err)) => {
let res: Response = err.into().into(); let res = Response::from_error(err.into());
let (res, body) = res.replace_body(()); let (res, body) = res.replace_body(());
self.as_mut().send_response(res, body.into_body())?; self.as_mut().send_response(res, body.into_body())?;
} }
@ -456,8 +457,7 @@ where
// to notify the dispatcher a new state is set and the outer loop // to notify the dispatcher a new state is set and the outer loop
// should be continue. // should be continue.
Poll::Ready(Err(err)) => { Poll::Ready(Err(err)) => {
let err = err.into(); let res = Response::from_error(err.into());
let res: Response = err.into();
let (res, body) = res.replace_body(()); let (res, body) = res.replace_body(());
return self.send_response(res, body.into_body()); return self.send_response(res, body.into_body());
} }
@ -477,7 +477,7 @@ where
Poll::Pending => Ok(()), Poll::Pending => Ok(()),
// see the comment on ExpectCall state branch's Ready(Err(err)). // see the comment on ExpectCall state branch's Ready(Err(err)).
Poll::Ready(Err(err)) => { Poll::Ready(Err(err)) => {
let res: Response = err.into().into(); let res = Response::from_error(err.into());
let (res, body) = res.replace_body(()); let (res, body) = res.replace_body(());
self.send_response(res, body.into_body()) self.send_response(res, body.into_body())
} }
@ -563,7 +563,7 @@ where
); );
this.flags.insert(Flags::READ_DISCONNECT); this.flags.insert(Flags::READ_DISCONNECT);
this.messages.push_back(DispatcherMessage::Error( this.messages.push_back(DispatcherMessage::Error(
Response::InternalServerError().finish().drop_body(), Response::internal_server_error().drop_body(),
)); ));
*this.error = Some(DispatchError::InternalError); *this.error = Some(DispatchError::InternalError);
break; break;
@ -576,7 +576,7 @@ where
error!("Internal server error: unexpected eof"); error!("Internal server error: unexpected eof");
this.flags.insert(Flags::READ_DISCONNECT); this.flags.insert(Flags::READ_DISCONNECT);
this.messages.push_back(DispatcherMessage::Error( this.messages.push_back(DispatcherMessage::Error(
Response::InternalServerError().finish().drop_body(), Response::internal_server_error().drop_body(),
)); ));
*this.error = Some(DispatchError::InternalError); *this.error = Some(DispatchError::InternalError);
break; break;
@ -599,7 +599,8 @@ where
} }
// Requests overflow buffer size should be responded with 431 // Requests overflow buffer size should be responded with 431
this.messages.push_back(DispatcherMessage::Error( this.messages.push_back(DispatcherMessage::Error(
Response::RequestHeaderFieldsTooLarge().finish().drop_body(), Response::new(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE)
.drop_body(),
)); ));
this.flags.insert(Flags::READ_DISCONNECT); this.flags.insert(Flags::READ_DISCONNECT);
*this.error = Some(ParseError::TooLarge.into()); *this.error = Some(ParseError::TooLarge.into());
@ -612,7 +613,7 @@ where
// Malformed requests should be responded with 400 // Malformed requests should be responded with 400
this.messages.push_back(DispatcherMessage::Error( this.messages.push_back(DispatcherMessage::Error(
Response::BadRequest().finish().drop_body(), Response::bad_request().drop_body(),
)); ));
this.flags.insert(Flags::READ_DISCONNECT); this.flags.insert(Flags::READ_DISCONNECT);
*this.error = Some(err.into()); *this.error = Some(err.into());
@ -648,11 +649,6 @@ where
// go into Some<Pin<&mut Sleep>> branch // go into Some<Pin<&mut Sleep>> branch
this.ka_timer.set(Some(sleep_until(deadline))); this.ka_timer.set(Some(sleep_until(deadline)));
return self.poll_keepalive(cx); return self.poll_keepalive(cx);
} else {
this.flags.insert(Flags::READ_DISCONNECT);
if let Some(mut payload) = this.payload.take() {
payload.set_error(PayloadError::Incomplete(None));
}
} }
} }
} }
@ -682,18 +678,14 @@ where
} }
} else { } else {
// timeout on first request (slow request) return 408 // timeout on first request (slow request) return 408
if !this.flags.contains(Flags::STARTED) {
trace!("Slow request timeout"); trace!("Slow request timeout");
let _ = self.as_mut().send_response( let _ = self.as_mut().send_response(
Response::RequestTimeout().finish().drop_body(), Response::new(StatusCode::REQUEST_TIMEOUT)
.drop_body(),
ResponseBody::Other(Body::Empty), ResponseBody::Other(Body::Empty),
); );
this = self.project(); this = self.project();
} else {
trace!("Keep-alive connection timeout");
}
this.flags.insert(Flags::STARTED | Flags::SHUTDOWN); this.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
this.state.set(State::None);
} }
// still have unfinished task. try to reset and register keep-alive. // still have unfinished task. try to reset and register keep-alive.
} else if let Some(deadline) = } else if let Some(deadline) =
@ -954,6 +946,7 @@ mod tests {
use actix_service::fn_service; use actix_service::fn_service;
use actix_utils::future::{ready, Ready}; use actix_utils::future::{ready, Ready};
use bytes::Bytes;
use futures_util::future::lazy; use futures_util::future::lazy;
use super::*; use super::*;
@ -981,19 +974,22 @@ mod tests {
} }
} }
fn ok_service() -> impl Service<Request, Response = Response, Error = Error> { fn ok_service() -> impl Service<Request, Response = Response<Body>, Error = Error> {
fn_service(|_req: Request| ready(Ok::<_, Error>(Response::Ok().finish()))) fn_service(|_req: Request| ready(Ok::<_, Error>(Response::ok())))
} }
fn echo_path_service() -> impl Service<Request, Response = Response, Error = Error> { fn echo_path_service(
) -> impl Service<Request, Response = Response<Body>, Error = Error> {
fn_service(|req: Request| { fn_service(|req: Request| {
let path = req.path().as_bytes(); let path = req.path().as_bytes();
ready(Ok::<_, Error>(Response::Ok().body(Body::from_slice(path)))) ready(Ok::<_, Error>(
Response::ok().set_body(Body::from_slice(path)),
))
}) })
} }
fn echo_payload_service() -> impl Service<Request, Response = Response, Error = Error> fn echo_payload_service(
{ ) -> impl Service<Request, Response = Response<Bytes>, Error = Error> {
fn_service(|mut req: Request| { fn_service(|mut req: Request| {
Box::pin(async move { Box::pin(async move {
use futures_util::stream::StreamExt as _; use futures_util::stream::StreamExt as _;
@ -1004,7 +1000,7 @@ mod tests {
body.extend_from_slice(chunk.unwrap().chunk()) body.extend_from_slice(chunk.unwrap().chunk())
} }
Ok::<_, Error>(Response::Ok().body(body)) Ok::<_, Error>(Response::ok().set_body(body.freeze()))
}) })
}) })
} }

View File

@ -5,7 +5,9 @@ use std::{fmt, net};
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_rt::net::TcpStream; use actix_rt::net::TcpStream;
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory}; use actix_service::{
fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _,
};
use actix_utils::future::ready; use actix_utils::future::ready;
use futures_core::future::LocalBoxFuture; use futures_core::future::LocalBoxFuture;
@ -82,7 +84,7 @@ where
Error = DispatchError, Error = DispatchError,
InitError = (), InitError = (),
> { > {
pipeline_factory(|io: TcpStream| { fn_service(|io: TcpStream| {
let peer_addr = io.peer_addr().ok(); let peer_addr = io.peer_addr().ok();
ready(Ok((io, peer_addr))) ready(Ok((io, peer_addr)))
}) })
@ -132,11 +134,9 @@ mod openssl {
Error = TlsError<SslError, DispatchError>, Error = TlsError<SslError, DispatchError>,
InitError = (), InitError = (),
> { > {
pipeline_factory(
Acceptor::new(acceptor) Acceptor::new(acceptor)
.map_err(TlsError::Tls) .map_err(TlsError::Tls)
.map_init_err(|_| panic!()), .map_init_err(|_| panic!())
)
.and_then(|io: TlsStream<TcpStream>| { .and_then(|io: TlsStream<TcpStream>| {
let peer_addr = io.get_ref().peer_addr().ok(); let peer_addr = io.get_ref().peer_addr().ok();
ready(Ok((io, peer_addr))) ready(Ok((io, peer_addr)))
@ -190,11 +190,9 @@ mod rustls {
Error = TlsError<io::Error, DispatchError>, Error = TlsError<io::Error, DispatchError>,
InitError = (), InitError = (),
> { > {
pipeline_factory(
Acceptor::new(config) Acceptor::new(config)
.map_err(TlsError::Tls) .map_err(TlsError::Tls)
.map_init_err(|_| panic!()), .map_init_err(|_| panic!())
)
.and_then(|io: TlsStream<TcpStream>| { .and_then(|io: TlsStream<TcpStream>| {
let peer_addr = io.get_ref().0.peer_addr().ok(); let peer_addr = io.get_ref().0.peer_addr().ok();
ready(Ok((io, peer_addr))) ready(Ok((io, peer_addr)))

View File

@ -252,8 +252,8 @@ where
} }
} }
Err(e) => { Err(err) => {
let res: Response = e.into().into(); let res = Response::from_error(err.into());
let (res, body) = res.replace_body(()); let (res, body) = res.replace_body(());
let mut send = send.take().unwrap(); let mut send = send.take().unwrap();

View File

@ -7,8 +7,8 @@ use std::{net, rc::Rc};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::net::TcpStream; use actix_rt::net::TcpStream;
use actix_service::{ use actix_service::{
fn_factory, fn_service, pipeline_factory, IntoServiceFactory, Service, fn_factory, fn_service, IntoServiceFactory, Service, ServiceFactory,
ServiceFactory, ServiceFactoryExt as _,
}; };
use actix_utils::future::ready; use actix_utils::future::ready;
use bytes::Bytes; use bytes::Bytes;
@ -81,12 +81,12 @@ where
Error = DispatchError, Error = DispatchError,
InitError = S::InitError, InitError = S::InitError,
> { > {
pipeline_factory(fn_factory(|| { fn_factory(|| {
ready(Ok::<_, S::InitError>(fn_service(|io: TcpStream| { ready(Ok::<_, S::InitError>(fn_service(|io: TcpStream| {
let peer_addr = io.peer_addr().ok(); let peer_addr = io.peer_addr().ok();
ready(Ok::<_, DispatchError>((io, peer_addr))) ready(Ok::<_, DispatchError>((io, peer_addr)))
}))) })))
})) })
.and_then(self) .and_then(self)
} }
} }
@ -119,11 +119,9 @@ mod openssl {
Error = TlsError<SslError, DispatchError>, Error = TlsError<SslError, DispatchError>,
InitError = S::InitError, InitError = S::InitError,
> { > {
pipeline_factory(
Acceptor::new(acceptor) Acceptor::new(acceptor)
.map_err(TlsError::Tls) .map_err(TlsError::Tls)
.map_init_err(|_| panic!()), .map_init_err(|_| panic!())
)
.and_then(fn_factory(|| { .and_then(fn_factory(|| {
ready(Ok::<_, S::InitError>(fn_service( ready(Ok::<_, S::InitError>(fn_service(
|io: TlsStream<TcpStream>| { |io: TlsStream<TcpStream>| {
@ -168,11 +166,9 @@ mod rustls {
let protos = vec!["h2".to_string().into()]; let protos = vec!["h2".to_string().into()];
config.set_protocols(&protos); config.set_protocols(&protos);
pipeline_factory(
Acceptor::new(config) Acceptor::new(config)
.map_err(TlsError::Tls) .map_err(TlsError::Tls)
.map_init_err(|_| panic!()), .map_init_err(|_| panic!())
)
.and_then(fn_factory(|| { .and_then(fn_factory(|| {
ready(Ok::<_, S::InitError>(fn_service( ready(Ok::<_, S::InitError>(fn_service(
|io: TlsStream<TcpStream>| { |io: TlsStream<TcpStream>| {

View File

@ -1,9 +1,33 @@
//! Typed HTTP headers, pre-defined `HeaderName`s, traits for parsing and conversion, and other //! Pre-defined `HeaderName`s, traits for parsing and conversion, and other header utility methods.
//! header utility methods.
use percent_encoding::{AsciiSet, CONTROLS}; use percent_encoding::{AsciiSet, CONTROLS};
pub use http::header::*; // re-export from http except header map related items
pub use http::header::{
HeaderName, HeaderValue, InvalidHeaderName, InvalidHeaderValue, ToStrError,
};
// re-export const header names
pub use http::header::{
ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCEPT_RANGES,
ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS,
ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE,
ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, AGE, ALLOW, ALT_SVC,
AUTHORIZATION, CACHE_CONTROL, CONNECTION, CONTENT_DISPOSITION, CONTENT_ENCODING,
CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_LOCATION, CONTENT_RANGE,
CONTENT_SECURITY_POLICY, CONTENT_SECURITY_POLICY_REPORT_ONLY, CONTENT_TYPE, COOKIE,
DATE, DNT, ETAG, EXPECT, EXPIRES, FORWARDED, FROM, HOST, IF_MATCH,
IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, IF_UNMODIFIED_SINCE, LAST_MODIFIED,
LINK, LOCATION, MAX_FORWARDS, ORIGIN, PRAGMA, PROXY_AUTHENTICATE,
PROXY_AUTHORIZATION, PUBLIC_KEY_PINS, PUBLIC_KEY_PINS_REPORT_ONLY, RANGE, REFERER,
REFERRER_POLICY, REFRESH, RETRY_AFTER, SEC_WEBSOCKET_ACCEPT,
SEC_WEBSOCKET_EXTENSIONS, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_PROTOCOL,
SEC_WEBSOCKET_VERSION, SERVER, SET_COOKIE, STRICT_TRANSPORT_SECURITY, TE, TRAILER,
TRANSFER_ENCODING, UPGRADE, UPGRADE_INSECURE_REQUESTS, USER_AGENT, VARY, VIA,
WARNING, WWW_AUTHENTICATE, X_CONTENT_TYPE_OPTIONS, X_DNS_PREFETCH_CONTROL,
X_FRAME_OPTIONS, X_XSS_PROTECTION,
};
use crate::error::ParseError; use crate::error::ParseError;
use crate::HttpMessage; use crate::HttpMessage;

View File

@ -41,6 +41,7 @@ pub fn write_content_length<B: BufMut>(n: u64, buf: &mut B) {
buf.put_slice(b"\r\n"); buf.put_slice(b"\r\n");
} }
// TODO: bench why this is needed
pub(crate) struct Writer<'a, B>(pub &'a mut B); pub(crate) struct Writer<'a, B>(pub &'a mut B);
impl<'a, B> io::Write for Writer<'a, B> impl<'a, B> io::Write for Writer<'a, B>

View File

@ -1,14 +1,18 @@
use std::cell::{Ref, RefMut}; use std::{
use std::str; cell::{Ref, RefMut},
str,
};
use encoding_rs::{Encoding, UTF_8}; use encoding_rs::{Encoding, UTF_8};
use http::header; use http::header;
use mime::Mime; use mime::Mime;
use crate::error::{ContentTypeError, ParseError}; use crate::{
use crate::extensions::Extensions; error::{ContentTypeError, ParseError},
use crate::header::{Header, HeaderMap}; header::{Header, HeaderMap},
use crate::payload::Payload; payload::Payload,
Extensions,
};
/// Trait that implements general purpose operations on HTTP messages. /// Trait that implements general purpose operations on HTTP messages.
pub trait HttpMessage: Sized { pub trait HttpMessage: Sized {

View File

@ -6,7 +6,6 @@
//! | `openssl` | TLS support via [OpenSSL]. | //! | `openssl` | TLS support via [OpenSSL]. |
//! | `rustls` | TLS support via [rustls]. | //! | `rustls` | TLS support via [rustls]. |
//! | `compress` | Payload compression support. (Deflate, Gzip & Brotli) | //! | `compress` | Payload compression support. (Deflate, Gzip & Brotli) |
//! | `secure-cookies` | Adds for secure cookies. Enables `cookies` feature. |
//! | `trust-dns` | Use [trust-dns] as the client DNS resolver. | //! | `trust-dns` | Use [trust-dns] as the client DNS resolver. |
//! //!
//! [OpenSSL]: https://crates.io/crates/openssl //! [OpenSSL]: https://crates.io/crates/openssl
@ -36,14 +35,14 @@ mod config;
#[cfg(feature = "compress")] #[cfg(feature = "compress")]
pub mod encoding; pub mod encoding;
mod extensions; mod extensions;
mod header; pub mod header;
mod helpers; mod helpers;
mod http_codes;
mod http_message; mod http_message;
mod message; mod message;
mod payload; mod payload;
mod request; mod request;
mod response; mod response;
mod response_builder;
mod service; mod service;
mod time_parser; mod time_parser;
@ -57,13 +56,20 @@ pub use self::builder::HttpServiceBuilder;
pub use self::config::{KeepAlive, ServiceConfig}; pub use self::config::{KeepAlive, ServiceConfig};
pub use self::error::{Error, ResponseError, Result}; pub use self::error::{Error, ResponseError, Result};
pub use self::extensions::Extensions; pub use self::extensions::Extensions;
pub use self::header::ContentEncoding;
pub use self::http_message::HttpMessage; pub use self::http_message::HttpMessage;
pub use self::message::ConnectionType;
pub use self::message::{Message, RequestHead, RequestHeadType, ResponseHead}; pub use self::message::{Message, RequestHead, RequestHeadType, ResponseHead};
pub use self::payload::{Payload, PayloadStream}; pub use self::payload::{Payload, PayloadStream};
pub use self::request::Request; pub use self::request::Request;
pub use self::response::{Response, ResponseBuilder}; pub use self::response::Response;
pub use self::response_builder::ResponseBuilder;
pub use self::service::HttpService; pub use self::service::HttpService;
pub use ::http::{uri, uri::Uri};
pub use ::http::{Method, StatusCode, Version};
// TODO: deprecate this mish-mash of random items
pub mod http { pub mod http {
//! Various HTTP related types. //! Various HTTP related types.

View File

@ -1,4 +1,5 @@
#[macro_export] #[macro_export]
#[doc(hidden)]
macro_rules! downcast_get_type_id { macro_rules! downcast_get_type_id {
() => { () => {
/// A helper method to get the type ID of the type /// A helper method to get the type ID of the type
@ -25,6 +26,7 @@ macro_rules! downcast_get_type_id {
} }
//Generate implementation for dyn $name //Generate implementation for dyn $name
#[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! downcast { macro_rules! downcast {
($name:ident) => { ($name:ident) => {
@ -70,6 +72,7 @@ macro_rules! downcast {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#![allow(clippy::upper_case_acronyms)]
trait MB { trait MB {
downcast_get_type_id!(); downcast_get_type_id!();

View File

@ -1,12 +1,15 @@
use std::cell::{Ref, RefCell, RefMut}; use std::{
use std::net; cell::{Ref, RefCell, RefMut},
use std::rc::Rc; net,
rc::Rc,
};
use bitflags::bitflags; use bitflags::bitflags;
use crate::extensions::Extensions; use crate::{
use crate::header::HeaderMap; header::{self, HeaderMap},
use crate::http::{header, Method, StatusCode, Uri, Version}; Extensions, Method, StatusCode, Uri, Version,
};
/// Represents various types of connection /// Represents various types of connection
#[derive(Copy, Clone, PartialEq, Debug)] #[derive(Copy, Clone, PartialEq, Debug)]

View File

@ -1,4 +1,4 @@
//! HTTP responses. //! HTTP response.
use std::{ use std::{
cell::{Ref, RefMut}, cell::{Ref, RefMut},
@ -10,40 +10,27 @@ use std::{
}; };
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures_core::Stream;
use crate::{ use crate::{
body::{Body, BodyStream, MessageBody, ResponseBody}, body::{Body, MessageBody, ResponseBody},
error::Error, error::Error,
extensions::Extensions, extensions::Extensions,
header::{IntoHeaderPair, IntoHeaderValue}, http::{HeaderMap, StatusCode},
http::{header, Error as HttpError, HeaderMap, StatusCode}, message::{BoxedResponseHead, ResponseHead},
message::{BoxedResponseHead, ConnectionType, ResponseHead}, ResponseBuilder,
}; };
/// An HTTP Response /// An HTTP response.
pub struct Response<B = Body> { pub struct Response<B> {
head: BoxedResponseHead, pub(crate) head: BoxedResponseHead,
body: ResponseBody<B>, pub(crate) body: ResponseBody<B>,
error: Option<Error>, pub(crate) error: Option<Error>,
} }
impl Response<Body> { impl Response<Body> {
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> ResponseBuilder {
ResponseBuilder::new(status)
}
/// Create HTTP response builder
#[inline]
pub fn build_from<T: Into<ResponseBuilder>>(source: T) -> ResponseBuilder {
source.into()
}
/// Constructs a response /// Constructs a response
#[inline] #[inline]
pub fn new(status: StatusCode) -> Response { pub fn new(status: StatusCode) -> Response<Body> {
Response { Response {
head: BoxedResponseHead::new(status), head: BoxedResponseHead::new(status),
body: ResponseBody::Body(Body::Empty), body: ResponseBody::Body(Body::Empty),
@ -51,9 +38,44 @@ impl Response<Body> {
} }
} }
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> ResponseBuilder {
ResponseBuilder::new(status)
}
// just a couple frequently used shortcuts
// this list should not grow larger than a few
/// Creates a new response with status 200 OK.
#[inline]
pub fn ok() -> Response<Body> {
Response::new(StatusCode::OK)
}
/// Creates a new response with status 400 Bad Request.
#[inline]
pub fn bad_request() -> Response<Body> {
Response::new(StatusCode::BAD_REQUEST)
}
/// Creates a new response with status 404 Not Found.
#[inline]
pub fn not_found() -> Response<Body> {
Response::new(StatusCode::NOT_FOUND)
}
/// Creates a new response with status 500 Internal Server Error.
#[inline]
pub fn internal_server_error() -> Response<Body> {
Response::new(StatusCode::INTERNAL_SERVER_ERROR)
}
// end shortcuts
/// Constructs an error response /// Constructs an error response
#[inline] #[inline]
pub fn from_error(error: Error) -> Response { pub fn from_error(error: Error) -> Response<Body> {
let mut resp = error.as_response_error().error_response(); let mut resp = error.as_response_error().error_response();
if resp.head.status == StatusCode::INTERNAL_SERVER_ERROR { if resp.head.status == StatusCode::INTERNAL_SERVER_ERROR {
error!("Internal Server Error: {:?}", error); error!("Internal Server Error: {:?}", error);
@ -238,8 +260,8 @@ impl<B: MessageBody> fmt::Debug for Response<B> {
} }
} }
impl Future for Response { impl<B: Unpin> Future for Response<B> {
type Output = Result<Response, Error>; type Output = Result<Response<B>, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(Ok(Response { Poll::Ready(Ok(Response {
@ -250,297 +272,8 @@ impl Future for Response {
} }
} }
/// An HTTP response builder.
///
/// This type can be used to construct an instance of `Response` through a builder-like pattern.
pub struct ResponseBuilder {
head: Option<BoxedResponseHead>,
err: Option<HttpError>,
}
impl ResponseBuilder {
#[inline]
/// Create response builder
pub fn new(status: StatusCode) -> Self {
ResponseBuilder {
head: Some(BoxedResponseHead::new(status)),
err: None,
}
}
/// Set HTTP status code of this response.
#[inline]
pub fn status(&mut self, status: StatusCode) -> &mut Self {
if let Some(parts) = parts(&mut self.head, &self.err) {
parts.status = status;
}
self
}
/// Insert a header, replacing any that were set with an equivalent field name.
///
/// ```
/// # use actix_http::Response;
/// use actix_http::http::header;
///
/// Response::Ok()
/// .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
/// .insert_header(("X-TEST", "value"))
/// .finish();
/// ```
pub fn insert_header<H>(&mut self, header: H) -> &mut Self
where
H: IntoHeaderPair,
{
if let Some(parts) = parts(&mut self.head, &self.err) {
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.
///
/// ```
/// # use actix_http::Response;
/// use actix_http::http::header;
///
/// Response::Ok()
/// .append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))
/// .append_header(("X-TEST", "value1"))
/// .append_header(("X-TEST", "value2"))
/// .finish();
/// ```
pub fn append_header<H>(&mut self, header: H) -> &mut Self
where
H: IntoHeaderPair,
{
if let Some(parts) = parts(&mut self.head, &self.err) {
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) = parts(&mut self.head, &self.err) {
parts.reason = Some(reason);
}
self
}
/// Set connection type to KeepAlive
#[inline]
pub fn keep_alive(&mut self) -> &mut Self {
if let Some(parts) = parts(&mut self.head, &self.err) {
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) = parts(&mut self.head, &self.err) {
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) = parts(&mut self.head, &self.err) {
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) = parts(&mut self.head, &self.err) {
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) = parts(&mut self.head, &self.err) {
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()
}
/// Set a body and generate `Response`.
///
/// `ResponseBuilder` can not be used after this call.
#[inline]
pub fn body<B: Into<Body>>(&mut self, body: B) -> Response {
self.message_body(body.into())
}
/// Set a body and generate `Response`.
///
/// `ResponseBuilder` can not be used after this call.
pub fn message_body<B>(&mut self, body: B) -> Response<B> {
if let Some(e) = self.err.take() {
return Response::from(Error::from(e)).into_body();
}
let response = self.head.take().expect("cannot reuse response builder");
Response {
head: response,
body: ResponseBody::Body(body),
error: None,
}
}
/// Set a streaming body and generate `Response`.
///
/// `ResponseBuilder` can not be used after this call.
#[inline]
pub fn streaming<S, E>(&mut self, stream: S) -> Response
where
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
E: Into<Error> + 'static,
{
self.body(Body::from_message(BodyStream::new(stream)))
}
/// Set an empty body and generate `Response`
///
/// `ResponseBuilder` can not be used after this call.
#[inline]
pub fn finish(&mut self) -> Response {
self.body(Body::Empty)
}
/// This method construct new `ResponseBuilder`
pub fn take(&mut self) -> ResponseBuilder {
ResponseBuilder {
head: self.head.take(),
err: self.err.take(),
}
}
}
#[inline]
fn parts<'a>(
parts: &'a mut Option<BoxedResponseHead>,
err: &Option<HttpError>,
) -> Option<&'a mut ResponseHead> {
if err.is_some() {
return None;
}
parts.as_mut().map(|r| &mut **r)
}
/// 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, 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
}
}
/// Helper converters /// Helper converters
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response { impl<I: Into<Response<Body>>, E: Into<Error>> From<Result<I, E>> for Response<Body> {
fn from(res: Result<I, E>) -> Self { fn from(res: Result<I, E>) -> Self {
match res { match res {
Ok(val) => val.into(), Ok(val) => val.into(),
@ -549,55 +282,55 @@ impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
} }
} }
impl From<ResponseBuilder> for Response { impl From<ResponseBuilder> for Response<Body> {
fn from(mut builder: ResponseBuilder) -> Self { fn from(mut builder: ResponseBuilder) -> Self {
builder.finish() builder.finish()
} }
} }
impl From<&'static str> for Response { impl From<&'static str> for Response<Body> {
fn from(val: &'static str) -> Self { fn from(val: &'static str) -> Self {
Response::Ok() Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8) .content_type(mime::TEXT_PLAIN_UTF_8)
.body(val) .body(val)
} }
} }
impl From<&'static [u8]> for Response { impl From<&'static [u8]> for Response<Body> {
fn from(val: &'static [u8]) -> Self { fn from(val: &'static [u8]) -> Self {
Response::Ok() Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM) .content_type(mime::APPLICATION_OCTET_STREAM)
.body(val) .body(val)
} }
} }
impl From<String> for Response { impl From<String> for Response<Body> {
fn from(val: String) -> Self { fn from(val: String) -> Self {
Response::Ok() Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8) .content_type(mime::TEXT_PLAIN_UTF_8)
.body(val) .body(val)
} }
} }
impl<'a> From<&'a String> for Response { impl<'a> From<&'a String> for Response<Body> {
fn from(val: &'a String) -> Self { fn from(val: &'a String) -> Self {
Response::Ok() Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8) .content_type(mime::TEXT_PLAIN_UTF_8)
.body(val) .body(val)
} }
} }
impl From<Bytes> for Response { impl From<Bytes> for Response<Body> {
fn from(val: Bytes) -> Self { fn from(val: Bytes) -> Self {
Response::Ok() Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM) .content_type(mime::APPLICATION_OCTET_STREAM)
.body(val) .body(val)
} }
} }
impl From<BytesMut> for Response { impl From<BytesMut> for Response<Body> {
fn from(val: BytesMut) -> Self { fn from(val: BytesMut) -> Self {
Response::Ok() Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM) .content_type(mime::APPLICATION_OCTET_STREAM)
.body(val) .body(val)
} }
@ -607,11 +340,11 @@ impl From<BytesMut> for Response {
mod tests { mod tests {
use super::*; use super::*;
use crate::body::Body; use crate::body::Body;
use crate::http::header::{HeaderName, HeaderValue, CONTENT_TYPE, COOKIE}; use crate::http::header::{HeaderValue, CONTENT_TYPE, COOKIE};
#[test] #[test]
fn test_debug() { fn test_debug() {
let resp = Response::Ok() let resp = Response::build(StatusCode::OK)
.append_header((COOKIE, HeaderValue::from_static("cookie1=value1; "))) .append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
.append_header((COOKIE, HeaderValue::from_static("cookie2=value2; "))) .append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
.finish(); .finish();
@ -619,41 +352,9 @@ mod tests {
assert!(dbg.contains("Response")); assert!(dbg.contains("Response"));
} }
#[test]
fn test_basic_builder() {
let resp = Response::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] #[test]
fn test_into_response() { fn test_into_response() {
let resp: Response = "test".into(); let resp: Response<Body> = "test".into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -662,7 +363,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test"); assert_eq!(resp.body().get_ref(), b"test");
let resp: Response = b"test".as_ref().into(); let resp: Response<Body> = b"test".as_ref().into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -671,7 +372,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test"); assert_eq!(resp.body().get_ref(), b"test");
let resp: Response = "test".to_owned().into(); let resp: Response<Body> = "test".to_owned().into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -680,7 +381,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test"); assert_eq!(resp.body().get_ref(), b"test");
let resp: Response = (&"test".to_owned()).into(); let resp: Response<Body> = (&"test".to_owned()).into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -690,7 +391,7 @@ mod tests {
assert_eq!(resp.body().get_ref(), b"test"); assert_eq!(resp.body().get_ref(), b"test");
let b = Bytes::from_static(b"test"); let b = Bytes::from_static(b"test");
let resp: Response = b.into(); let resp: Response<Body> = b.into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -700,7 +401,7 @@ mod tests {
assert_eq!(resp.body().get_ref(), b"test"); assert_eq!(resp.body().get_ref(), b"test");
let b = Bytes::from_static(b"test"); let b = Bytes::from_static(b"test");
let resp: Response = b.into(); let resp: Response<Body> = b.into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -710,7 +411,7 @@ mod tests {
assert_eq!(resp.body().get_ref(), b"test"); assert_eq!(resp.body().get_ref(), b"test");
let b = BytesMut::from("test"); let b = BytesMut::from("test");
let resp: Response = b.into(); let resp: Response<Body> = b.into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),
@ -720,72 +421,4 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test"); assert_eq!(resp.body().get_ref(), b"test");
} }
#[test]
fn test_into_builder() {
let mut resp: Response = "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::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::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::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::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")));
}
} }

View File

@ -0,0 +1,466 @@
//! 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, ResponseBody},
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_eq!(body::to_bytes(res.take_body()).await.unwrap(), &b"1234"[..]);
///
/// assert!(res.headers().contains_key("server"));
/// assert_eq!(res.headers().get_all("set-cookie").count(), 2);
/// # })
/// ```
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())
}
/// Generate response with a body.
///
/// This `ResponseBuilder` will be left in a useless state.
pub fn message_body<B>(&mut self, body: B) -> Response<B> {
if let Some(e) = self.err.take() {
return Response::from(Error::from(e)).into_body();
}
let response = self.head.take().expect("cannot reuse response builder");
Response {
head: response,
body: ResponseBody::Body(body),
error: None,
}
}
/// 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")));
}
}

View File

@ -10,7 +10,9 @@ use std::{
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_rt::net::TcpStream; use actix_rt::net::TcpStream;
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory}; use actix_service::{
fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _,
};
use bytes::Bytes; use bytes::Bytes;
use futures_core::{future::LocalBoxFuture, ready}; use futures_core::{future::LocalBoxFuture, ready};
use h2::server::{handshake, Handshake}; use h2::server::{handshake, Handshake};
@ -180,7 +182,7 @@ where
Error = DispatchError, Error = DispatchError,
InitError = (), InitError = (),
> { > {
pipeline_factory(|io: TcpStream| async { fn_service(|io: TcpStream| async {
let peer_addr = io.peer_addr().ok(); let peer_addr = io.peer_addr().ok();
Ok((io, Protocol::Http1, peer_addr)) Ok((io, Protocol::Http1, peer_addr))
}) })
@ -232,11 +234,9 @@ mod openssl {
Error = TlsError<SslError, DispatchError>, Error = TlsError<SslError, DispatchError>,
InitError = (), InitError = (),
> { > {
pipeline_factory(
Acceptor::new(acceptor) Acceptor::new(acceptor)
.map_err(TlsError::Tls) .map_err(TlsError::Tls)
.map_init_err(|_| panic!()), .map_init_err(|_| panic!())
)
.and_then(|io: TlsStream<TcpStream>| async { .and_then(|io: TlsStream<TcpStream>| async {
let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() { let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() {
if protos.windows(2).any(|window| window == b"h2") { if protos.windows(2).any(|window| window == b"h2") {
@ -304,13 +304,12 @@ mod rustls {
let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()]; let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()];
config.set_protocols(&protos); config.set_protocols(&protos);
pipeline_factory(
Acceptor::new(config) Acceptor::new(config)
.map_err(TlsError::Tls) .map_err(TlsError::Tls)
.map_init_err(|_| panic!()), .map_init_err(|_| panic!())
)
.and_then(|io: TlsStream<TcpStream>| async { .and_then(|io: TlsStream<TcpStream>| async {
let proto = if let Some(protos) = io.get_ref().1.get_alpn_protocol() { let proto = if let Some(protos) = io.get_ref().1.get_alpn_protocol()
{
if protos.windows(2).any(|window| window == b"h2") { if protos.windows(2).any(|window| window == b"h2") {
Protocol::Http2 Protocol::Http2
} else { } else {

View File

@ -9,8 +9,8 @@ use derive_more::{Display, Error, From};
use http::{header, Method, StatusCode}; use http::{header, Method, StatusCode};
use crate::{ use crate::{
error::ResponseError, header::HeaderValue, message::RequestHead, response::Response, body::Body, error::ResponseError, header::HeaderValue, message::RequestHead,
ResponseBuilder, response::Response, ResponseBuilder,
}; };
mod codec; mod codec;
@ -99,31 +99,39 @@ pub enum HandshakeError {
} }
impl ResponseError for HandshakeError { impl ResponseError for HandshakeError {
fn error_response(&self) -> Response { fn error_response(&self) -> Response<Body> {
match self { match self {
HandshakeError::GetMethodRequired => Response::MethodNotAllowed() HandshakeError::GetMethodRequired => {
Response::build(StatusCode::METHOD_NOT_ALLOWED)
.insert_header((header::ALLOW, "GET")) .insert_header((header::ALLOW, "GET"))
.finish(), .finish()
}
HandshakeError::NoWebsocketUpgrade => Response::BadRequest() HandshakeError::NoWebsocketUpgrade => {
Response::build(StatusCode::BAD_REQUEST)
.reason("No WebSocket Upgrade header found") .reason("No WebSocket Upgrade header found")
.finish(), .finish()
}
HandshakeError::NoConnectionUpgrade => Response::BadRequest() HandshakeError::NoConnectionUpgrade => {
Response::build(StatusCode::BAD_REQUEST)
.reason("No Connection upgrade") .reason("No Connection upgrade")
.finish(), .finish()
}
HandshakeError::NoVersionHeader => Response::BadRequest() HandshakeError::NoVersionHeader => Response::build(StatusCode::BAD_REQUEST)
.reason("WebSocket version header is required") .reason("WebSocket version header is required")
.finish(), .finish(),
HandshakeError::UnsupportedVersion => Response::BadRequest() HandshakeError::UnsupportedVersion => {
Response::build(StatusCode::BAD_REQUEST)
.reason("Unsupported WebSocket version") .reason("Unsupported WebSocket version")
.finish(), .finish()
HandshakeError::BadWebsocketKey => {
Response::BadRequest().reason("Handshake error").finish()
} }
HandshakeError::BadWebsocketKey => Response::build(StatusCode::BAD_REQUEST)
.reason("Handshake error")
.finish(),
} }
} }
} }
@ -320,17 +328,17 @@ mod tests {
#[test] #[test]
fn test_wserror_http_response() { fn test_wserror_http_response() {
let resp: Response = HandshakeError::GetMethodRequired.error_response(); let resp = HandshakeError::GetMethodRequired.error_response();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let resp: Response = HandshakeError::NoWebsocketUpgrade.error_response(); let resp = HandshakeError::NoWebsocketUpgrade.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: Response = HandshakeError::NoConnectionUpgrade.error_response(); let resp = HandshakeError::NoConnectionUpgrade.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: Response = HandshakeError::NoVersionHeader.error_response(); let resp = HandshakeError::NoVersionHeader.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: Response = HandshakeError::UnsupportedVersion.error_response(); let resp = HandshakeError::UnsupportedVersion.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let resp: Response = HandshakeError::BadWebsocketKey.error_response(); let resp = HandshakeError::BadWebsocketKey.error_response();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
} }
} }

View File

@ -33,7 +33,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h1_v2() { async fn test_h1_v2() {
let srv = test_server(move || { let srv = test_server(move || {
HttpService::build() HttpService::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR))) .finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
.tcp() .tcp()
}) })
.await; .await;
@ -61,7 +61,7 @@ async fn test_h1_v2() {
async fn test_connection_close() { async fn test_connection_close() {
let srv = test_server(move || { let srv = test_server(move || {
HttpService::build() HttpService::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().body(STR))) .finish(|_| future::ok::<_, ()>(Response::ok().set_body(STR)))
.tcp() .tcp()
.map(|_| ()) .map(|_| ())
}) })
@ -77,9 +77,9 @@ async fn test_with_query_parameter() {
HttpService::build() HttpService::build()
.finish(|req: Request| { .finish(|req: Request| {
if req.uri().query().unwrap().contains("qp=") { if req.uri().query().unwrap().contains("qp=") {
future::ok::<_, ()>(Response::Ok().finish()) future::ok::<_, ()>(Response::ok())
} else { } else {
future::ok::<_, ()>(Response::BadRequest().finish()) future::ok::<_, ()>(Response::bad_request())
} }
}) })
.tcp() .tcp()
@ -112,7 +112,7 @@ async fn test_h1_expect() {
let str = std::str::from_utf8(&buf).unwrap(); let str = std::str::from_utf8(&buf).unwrap();
assert_eq!(str, "expect body"); assert_eq!(str, "expect body");
Ok::<_, ()>(Response::Ok().finish()) Ok::<_, ()>(Response::ok())
}) })
.tcp() .tcp()
}) })

View File

@ -4,11 +4,15 @@ extern crate tls_openssl as openssl;
use std::io; use std::io;
use actix_http::error::{ErrorBadRequest, PayloadError}; use actix_http::{
use actix_http::http::header::{self, HeaderName, HeaderValue}; body::{Body, SizedStream},
use actix_http::http::{Method, StatusCode, Version}; error::{ErrorBadRequest, PayloadError},
use actix_http::HttpMessage; http::{
use actix_http::{body, Error, HttpService, Request, Response}; header::{self, HeaderName, HeaderValue},
Method, StatusCode, Version,
},
Error, HttpMessage, HttpService, Request, Response,
};
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{fn_service, ServiceFactoryExt}; use actix_service::{fn_service, ServiceFactoryExt};
use actix_utils::future::{err, ok, ready}; use actix_utils::future::{err, ok, ready};
@ -67,7 +71,7 @@ fn tls_config() -> SslAcceptor {
async fn test_h2() -> io::Result<()> { async fn test_h2() -> io::Result<()> {
let srv = test_server(move || { let srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, Error>(Response::Ok().finish())) .h2(|_| ok::<_, Error>(Response::ok()))
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
}) })
@ -85,7 +89,7 @@ async fn test_h2_1() -> io::Result<()> {
.finish(|req: Request| { .finish(|req: Request| {
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_2); assert_eq!(req.version(), Version::HTTP_2);
ok::<_, Error>(Response::Ok().finish()) ok::<_, Error>(Response::ok())
}) })
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
@ -104,7 +108,7 @@ async fn test_h2_body() -> io::Result<()> {
HttpService::build() HttpService::build()
.h2(|mut req: Request<_>| async move { .h2(|mut req: Request<_>| async move {
let body = load_body(req.take_payload()).await?; let body = load_body(req.take_payload()).await?;
Ok::<_, Error>(Response::Ok().body(body)) Ok::<_, Error>(Response::ok().set_body(body))
}) })
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
@ -182,7 +186,7 @@ async fn test_h2_headers() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
let data = data.clone(); let data = data.clone();
HttpService::build().h2(move |_| { HttpService::build().h2(move |_| {
let mut builder = Response::Ok(); let mut builder = Response::build(StatusCode::OK);
for idx in 0..90 { for idx in 0..90 {
builder.insert_header( builder.insert_header(
(format!("X-TEST-{}", idx).as_str(), (format!("X-TEST-{}", idx).as_str(),
@ -241,7 +245,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h2_body2() { async fn test_h2_body2() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
}) })
@ -259,7 +263,7 @@ async fn test_h2_body2() {
async fn test_h2_head_empty() { async fn test_h2_head_empty() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.finish(|_| ok::<_, ()>(Response::Ok().body(STR))) .finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
}) })
@ -283,7 +287,7 @@ async fn test_h2_head_empty() {
async fn test_h2_head_binary() { async fn test_h2_head_binary() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
}) })
@ -306,7 +310,7 @@ async fn test_h2_head_binary() {
async fn test_h2_head_binary2() { async fn test_h2_head_binary2() {
let srv = test_server(move || { let srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
}) })
@ -328,7 +332,7 @@ async fn test_h2_body_length() {
.h2(|_| { .h2(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref()))); let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)), Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
) )
}) })
.openssl(tls_config()) .openssl(tls_config())
@ -351,7 +355,7 @@ async fn test_h2_body_chunked_explicit() {
.h2(|_| { .h2(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::build(StatusCode::OK)
.insert_header((header::TRANSFER_ENCODING, "chunked")) .insert_header((header::TRANSFER_ENCODING, "chunked"))
.streaming(body), .streaming(body),
) )
@ -379,7 +383,7 @@ async fn test_h2_response_http_error_handling() {
.h2(fn_service(|_| { .h2(fn_service(|_| {
let broken_header = Bytes::from_static(b"\0\0\0"); let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::build(StatusCode::OK)
.insert_header((header::CONTENT_TYPE, broken_header)) .insert_header((header::CONTENT_TYPE, broken_header))
.body(STR), .body(STR),
) )
@ -401,7 +405,7 @@ async fn test_h2_response_http_error_handling() {
async fn test_h2_service_error() { async fn test_h2_service_error() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| err::<Response, Error>(ErrorBadRequest("error"))) .h2(|_| err::<Response<Body>, Error>(ErrorBadRequest("error")))
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())
}) })
@ -424,7 +428,7 @@ async fn test_h2_on_connect() {
}) })
.h2(|req: Request| { .h2(|req: Request| {
assert!(req.extensions().contains::<isize>()); assert!(req.extensions().contains::<isize>());
ok::<_, ()>(Response::Ok().finish()) ok::<_, ()>(Response::ok())
}) })
.openssl(tls_config()) .openssl(tls_config())
.map_err(|_| ()) .map_err(|_| ())

View File

@ -2,10 +2,15 @@
extern crate tls_rustls as rustls; extern crate tls_rustls as rustls;
use actix_http::error::PayloadError; use actix_http::{
use actix_http::http::header::{self, HeaderName, HeaderValue}; body::{Body, SizedStream},
use actix_http::http::{Method, StatusCode, Version}; error::{self, PayloadError},
use actix_http::{body, error, Error, HttpService, Request, Response}; http::{
header::{self, HeaderName, HeaderValue},
Method, StatusCode, Version,
},
Error, HttpService, Request, Response,
};
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{fn_factory_with_config, fn_service}; use actix_service::{fn_factory_with_config, fn_service};
use actix_utils::future::{err, ok}; use actix_utils::future::{err, ok};
@ -51,7 +56,7 @@ fn tls_config() -> RustlsServerConfig {
async fn test_h1() -> io::Result<()> { async fn test_h1() -> io::Result<()> {
let srv = test_server(move || { let srv = test_server(move || {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, Error>(Response::Ok().finish())) .h1(|_| ok::<_, Error>(Response::ok()))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;
@ -65,7 +70,7 @@ async fn test_h1() -> io::Result<()> {
async fn test_h2() -> io::Result<()> { async fn test_h2() -> io::Result<()> {
let srv = test_server(move || { let srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, Error>(Response::Ok().finish())) .h2(|_| ok::<_, Error>(Response::ok()))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;
@ -82,7 +87,7 @@ async fn test_h1_1() -> io::Result<()> {
.h1(|req: Request| { .h1(|req: Request| {
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_11); assert_eq!(req.version(), Version::HTTP_11);
ok::<_, Error>(Response::Ok().finish()) ok::<_, Error>(Response::ok())
}) })
.rustls(tls_config()) .rustls(tls_config())
}) })
@ -100,7 +105,7 @@ async fn test_h2_1() -> io::Result<()> {
.finish(|req: Request| { .finish(|req: Request| {
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
assert_eq!(req.version(), Version::HTTP_2); assert_eq!(req.version(), Version::HTTP_2);
ok::<_, Error>(Response::Ok().finish()) ok::<_, Error>(Response::ok())
}) })
.rustls(tls_config()) .rustls(tls_config())
}) })
@ -118,7 +123,7 @@ async fn test_h2_body1() -> io::Result<()> {
HttpService::build() HttpService::build()
.h2(|mut req: Request<_>| async move { .h2(|mut req: Request<_>| async move {
let body = load_body(req.take_payload()).await?; let body = load_body(req.take_payload()).await?;
Ok::<_, Error>(Response::Ok().body(body)) Ok::<_, Error>(Response::ok().set_body(body))
}) })
.rustls(tls_config()) .rustls(tls_config())
}) })
@ -194,7 +199,7 @@ async fn test_h2_headers() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
let data = data.clone(); let data = data.clone();
HttpService::build().h2(move |_| { HttpService::build().h2(move |_| {
let mut config = Response::Ok(); let mut config = Response::build(StatusCode::OK);
for idx in 0..90 { for idx in 0..90 {
config.insert_header(( config.insert_header((
format!("X-TEST-{}", idx).as_str(), format!("X-TEST-{}", idx).as_str(),
@ -252,7 +257,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h2_body2() { async fn test_h2_body2() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;
@ -269,7 +274,7 @@ async fn test_h2_body2() {
async fn test_h2_head_empty() { async fn test_h2_head_empty() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.finish(|_| ok::<_, ()>(Response::Ok().body(STR))) .finish(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;
@ -295,7 +300,7 @@ async fn test_h2_head_empty() {
async fn test_h2_head_binary() { async fn test_h2_head_binary() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;
@ -320,7 +325,7 @@ async fn test_h2_head_binary() {
async fn test_h2_head_binary2() { async fn test_h2_head_binary2() {
let srv = test_server(move || { let srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| ok::<_, ()>(Response::Ok().body(STR))) .h2(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;
@ -344,7 +349,7 @@ async fn test_h2_body_length() {
.h2(|_| { .h2(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref()))); let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)), Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
) )
}) })
.rustls(tls_config()) .rustls(tls_config())
@ -366,7 +371,7 @@ async fn test_h2_body_chunked_explicit() {
.h2(|_| { .h2(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::build(StatusCode::OK)
.insert_header((header::TRANSFER_ENCODING, "chunked")) .insert_header((header::TRANSFER_ENCODING, "chunked"))
.streaming(body), .streaming(body),
) )
@ -394,7 +399,7 @@ async fn test_h2_response_http_error_handling() {
ok::<_, ()>(fn_service(|_| { ok::<_, ()>(fn_service(|_| {
let broken_header = Bytes::from_static(b"\0\0\0"); let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::build(StatusCode::OK)
.insert_header((http::header::CONTENT_TYPE, broken_header)) .insert_header((http::header::CONTENT_TYPE, broken_header))
.body(STR), .body(STR),
) )
@ -416,7 +421,7 @@ async fn test_h2_response_http_error_handling() {
async fn test_h2_service_error() { async fn test_h2_service_error() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.h2(|_| err::<Response, Error>(error::ErrorBadRequest("error"))) .h2(|_| err::<Response<Body>, Error>(error::ErrorBadRequest("error")))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;
@ -433,7 +438,7 @@ async fn test_h2_service_error() {
async fn test_h1_service_error() { async fn test_h1_service_error() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
HttpService::build() HttpService::build()
.h1(|_| err::<Response, Error>(error::ErrorBadRequest("error"))) .h1(|_| err::<Response<Body>, Error>(error::ErrorBadRequest("error")))
.rustls(tls_config()) .rustls(tls_config())
}) })
.await; .await;

View File

@ -13,7 +13,10 @@ use regex::Regex;
use actix_http::HttpMessage; use actix_http::HttpMessage;
use actix_http::{ use actix_http::{
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response, body::{Body, SizedStream},
error,
http::{self, header, StatusCode},
Error, HttpService, KeepAlive, Request, Response,
}; };
#[actix_rt::test] #[actix_rt::test]
@ -25,7 +28,7 @@ async fn test_h1() {
.client_disconnect(1000) .client_disconnect(1000)
.h1(|req: Request| { .h1(|req: Request| {
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
ok::<_, ()>(Response::Ok().finish()) ok::<_, ()>(Response::ok())
}) })
.tcp() .tcp()
}) })
@ -45,7 +48,7 @@ async fn test_h1_2() {
.finish(|req: Request| { .finish(|req: Request| {
assert!(req.peer_addr().is_some()); assert!(req.peer_addr().is_some());
assert_eq!(req.version(), http::Version::HTTP_11); assert_eq!(req.version(), http::Version::HTTP_11);
ok::<_, ()>(Response::Ok().finish()) ok::<_, ()>(Response::ok())
}) })
.tcp() .tcp()
}) })
@ -66,7 +69,7 @@ async fn test_expect_continue() {
err(error::ErrorPreconditionFailed("error")) err(error::ErrorPreconditionFailed("error"))
} }
})) }))
.finish(|_| ok::<_, ()>(Response::Ok().finish())) .finish(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -97,7 +100,7 @@ async fn test_expect_continue_h1() {
} }
}) })
})) }))
.h1(fn_service(|_| ok::<_, ()>(Response::Ok().finish()))) .h1(fn_service(|_| ok::<_, ()>(Response::ok())))
.tcp() .tcp()
}) })
.await; .await;
@ -131,7 +134,9 @@ async fn test_chunked_payload() {
}) })
.fold(0usize, |acc, chunk| ready(acc + chunk.len())) .fold(0usize, |acc, chunk| ready(acc + chunk.len()))
.map(|req_size| { .map(|req_size| {
Ok::<_, Error>(Response::Ok().body(format!("size={}", req_size))) Ok::<_, Error>(
Response::ok().set_body(format!("size={}", req_size)),
)
}) })
})) }))
.tcp() .tcp()
@ -176,7 +181,7 @@ async fn test_slow_request() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.client_timeout(100) .client_timeout(100)
.finish(|_| ok::<_, ()>(Response::Ok().finish())) .finish(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -192,7 +197,7 @@ async fn test_slow_request() {
async fn test_http1_malformed_request() { async fn test_http1_malformed_request() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish())) .h1(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -208,7 +213,7 @@ async fn test_http1_malformed_request() {
async fn test_http1_keepalive() { async fn test_http1_keepalive() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish())) .h1(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -230,7 +235,7 @@ async fn test_http1_keepalive_timeout() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.keep_alive(1) .keep_alive(1)
.h1(|_| ok::<_, ()>(Response::Ok().finish())) .h1(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -251,7 +256,7 @@ async fn test_http1_keepalive_timeout() {
async fn test_http1_keepalive_close() { async fn test_http1_keepalive_close() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish())) .h1(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -272,7 +277,7 @@ async fn test_http1_keepalive_close() {
async fn test_http10_keepalive_default_close() { async fn test_http10_keepalive_default_close() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish())) .h1(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -292,7 +297,7 @@ async fn test_http10_keepalive_default_close() {
async fn test_http10_keepalive() { async fn test_http10_keepalive() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().finish())) .h1(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -320,7 +325,7 @@ async fn test_http1_keepalive_disabled() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.keep_alive(KeepAlive::Disabled) .keep_alive(KeepAlive::Disabled)
.h1(|_| ok::<_, ()>(Response::Ok().finish())) .h1(|_| ok::<_, ()>(Response::ok()))
.tcp() .tcp()
}) })
.await; .await;
@ -391,7 +396,7 @@ async fn test_h1_headers() {
let mut srv = test_server(move || { let mut srv = test_server(move || {
let data = data.clone(); let data = data.clone();
HttpService::build().h1(move |_| { HttpService::build().h1(move |_| {
let mut builder = Response::Ok(); let mut builder = Response::build(StatusCode::OK);
for idx in 0..90 { for idx in 0..90 {
builder.insert_header(( builder.insert_header((
format!("X-TEST-{}", idx).as_str(), format!("X-TEST-{}", idx).as_str(),
@ -448,7 +453,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
async fn test_h1_body() { async fn test_h1_body() {
let mut srv = test_server(|| { let mut srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR))) .h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp() .tcp()
}) })
.await; .await;
@ -465,7 +470,7 @@ async fn test_h1_body() {
async fn test_h1_head_empty() { async fn test_h1_head_empty() {
let mut srv = test_server(|| { let mut srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR))) .h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp() .tcp()
}) })
.await; .await;
@ -490,7 +495,7 @@ async fn test_h1_head_empty() {
async fn test_h1_head_binary() { async fn test_h1_head_binary() {
let mut srv = test_server(|| { let mut srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR))) .h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp() .tcp()
}) })
.await; .await;
@ -515,7 +520,7 @@ async fn test_h1_head_binary() {
async fn test_h1_head_binary2() { async fn test_h1_head_binary2() {
let srv = test_server(|| { let srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| ok::<_, ()>(Response::Ok().body(STR))) .h1(|_| ok::<_, ()>(Response::ok().set_body(STR)))
.tcp() .tcp()
}) })
.await; .await;
@ -539,7 +544,7 @@ async fn test_h1_body_length() {
.h1(|_| { .h1(|_| {
let body = once(ok(Bytes::from_static(STR.as_ref()))); let body = once(ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)), Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
) )
}) })
.tcp() .tcp()
@ -561,7 +566,7 @@ async fn test_h1_body_chunked_explicit() {
.h1(|_| { .h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::build(StatusCode::OK)
.insert_header((header::TRANSFER_ENCODING, "chunked")) .insert_header((header::TRANSFER_ENCODING, "chunked"))
.streaming(body), .streaming(body),
) )
@ -595,7 +600,7 @@ async fn test_h1_body_chunked_implicit() {
HttpService::build() HttpService::build()
.h1(|_| { .h1(|_| {
let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().streaming(body)) ok::<_, ()>(Response::build(StatusCode::OK).streaming(body))
}) })
.tcp() .tcp()
}) })
@ -625,7 +630,7 @@ async fn test_h1_response_http_error_handling() {
.h1(fn_service(|_| { .h1(fn_service(|_| {
let broken_header = Bytes::from_static(b"\0\0\0"); let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::build(StatusCode::OK)
.insert_header((http::header::CONTENT_TYPE, broken_header)) .insert_header((http::header::CONTENT_TYPE, broken_header))
.body(STR), .body(STR),
) )
@ -646,7 +651,7 @@ async fn test_h1_response_http_error_handling() {
async fn test_h1_service_error() { async fn test_h1_service_error() {
let mut srv = test_server(|| { let mut srv = test_server(|| {
HttpService::build() HttpService::build()
.h1(|_| err::<Response, _>(error::ErrorBadRequest("error"))) .h1(|_| err::<Response<Body>, _>(error::ErrorBadRequest("error")))
.tcp() .tcp()
}) })
.await; .await;
@ -668,7 +673,7 @@ async fn test_h1_on_connect() {
}) })
.h1(|req: Request| { .h1(|req: Request| {
assert!(req.extensions().contains::<isize>()); assert!(req.extensions().contains::<isize>());
ok::<_, ()>(Response::Ok().finish()) ok::<_, ()>(Response::ok())
}) })
.tcp() .tcp()
}) })

View File

@ -91,7 +91,7 @@ async fn test_simple() {
let ws_service = ws_service.clone(); let ws_service = ws_service.clone();
HttpService::build() HttpService::build()
.upgrade(fn_factory(move || future::ok::<_, ()>(ws_service.clone()))) .upgrade(fn_factory(move || future::ok::<_, ()>(ws_service.clone())))
.finish(|_| future::ok::<_, ()>(Response::NotFound())) .finish(|_| future::ok::<_, ()>(Response::not_found()))
.tcp() .tcp()
} }
}) })

View File

@ -16,8 +16,8 @@ name = "actix_multipart"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "4.0.0-beta.5", default-features = false } actix-web = { version = "4.0.0-beta.6", default-features = false }
actix-utils = "3.0.0-beta.4" actix-utils = "3.0.0"
bytes = "1" bytes = "1"
derive_more = "0.99.5" derive_more = "0.99.5"
@ -31,6 +31,6 @@ twoway = "0.2"
[dev-dependencies] [dev-dependencies]
actix-rt = "2.2" actix-rt = "2.2"
actix-http = "3.0.0-beta.5" actix-http = "3.0.0-beta.6"
tokio = { version = "1", features = ["sync"] } tokio = { version = "1", features = ["sync"] }
tokio-stream = "0.1" tokio-stream = "0.1"

View File

@ -3,6 +3,10 @@
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
## 0.1.0-beta.2 - 2021-04-17
* No significant changes from `0.1.0-beta.1`.
## 0.1.0-beta.1 - 2021-04-02 ## 0.1.0-beta.1 - 2021-04-02
* Move integration testing structs from `actix-web`. [#2112] * Move integration testing structs from `actix-web`. [#2112]

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-test" name = "actix-test"
version = "0.1.0-beta.1" version = "0.1.0-beta.2"
authors = [ authors = [
"Nikolay Kim <fafhrd91@gmail.com>", "Nikolay Kim <fafhrd91@gmail.com>",
"Rob Ede <robjtede@icloud.com>", "Rob Ede <robjtede@icloud.com>",
@ -19,14 +19,14 @@ rustls = ["tls-rustls", "actix-http/rustls"]
openssl = ["tls-openssl", "actix-http/openssl"] openssl = ["tls-openssl", "actix-http/openssl"]
[dependencies] [dependencies]
actix-codec = "0.4.0-beta.1" actix-codec = "0.4.0"
actix-http = "3.0.0-beta.5" actix-http = "3.0.0-beta.6"
actix-http-test = { version = "3.0.0-beta.4", features = [] } actix-http-test = { version = "3.0.0-beta.4", features = [] }
actix-service = "2.0.0-beta.4" actix-service = "2.0.0"
actix-utils = "3.0.0-beta.2" actix-utils = "3.0.0"
actix-web = { version = "4.0.0-beta.5", default-features = false, features = ["cookies"] } actix-web = { version = "4.0.0-beta.6", default-features = false, features = ["cookies"] }
actix-rt = "2.1" actix-rt = "2.1"
awc = { version = "3.0.0-beta.4", default-features = false, features = ["cookies"] } awc = { version = "3.0.0-beta.5", default-features = false, features = ["cookies"] }
futures-core = { version = "0.3.7", default-features = false, features = ["std"] } futures-core = { version = "0.3.7", default-features = false, features = ["std"] }
futures-util = { version = "0.3.7", default-features = false, features = [] } futures-util = { version = "0.3.7", default-features = false, features = [] }

View File

@ -17,9 +17,9 @@ path = "src/lib.rs"
[dependencies] [dependencies]
actix = { version = "0.11.0-beta.3", default-features = false } actix = { version = "0.11.0-beta.3", default-features = false }
actix-codec = "0.4.0-beta.1" actix-codec = "0.4.0"
actix-http = "3.0.0-beta.5" actix-http = "3.0.0-beta.6"
actix-web = { version = "4.0.0-beta.5", default-features = false } actix-web = { version = "4.0.0-beta.6", default-features = false }
bytes = "1" bytes = "1"
bytestring = "1" bytestring = "1"
@ -29,8 +29,8 @@ tokio = { version = "1", features = ["sync"] }
[dev-dependencies] [dev-dependencies]
actix-rt = "2.2" actix-rt = "2.2"
actix-test = "0.1.0-beta.1" actix-test = "0.1.0-beta.2"
awc = { version = "3.0.0-beta.4", default-features = false } awc = { version = "3.0.0-beta.5", default-features = false }
env_logger = "0.8" env_logger = "0.8"
futures-util = { version = "0.3.7", default-features = false } futures-util = { version = "0.3.7", default-features = false }

View File

@ -20,9 +20,9 @@ proc-macro2 = "1"
[dev-dependencies] [dev-dependencies]
actix-rt = "2.2" actix-rt = "2.2"
actix-test = "0.1.0-beta.1" actix-test = "0.1.0-beta.2"
actix-utils = "3.0.0-beta.4" actix-utils = "3.0.0"
actix-web = "4.0.0-beta.5" actix-web = "4.0.0-beta.6"
futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] } futures-core = { version = "0.3.7", default-features = false, features = ["alloc"] }
trybuild = "1" trybuild = "1"

View File

@ -1,11 +1,15 @@
use std::future::Future; use std::future::Future;
use std::task::{Context, Poll};
use actix_utils::future::{ok, Ready}; use actix_utils::future::{ok, Ready};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform}; use actix_web::{
use actix_web::http::header::{HeaderName, HeaderValue}; dev::{Service, ServiceRequest, ServiceResponse, Transform},
use actix_web::http::StatusCode; http::{
use actix_web::{http, web::Path, App, Error, HttpResponse, Responder}; self,
header::{HeaderName, HeaderValue},
StatusCode,
},
web, App, Error, HttpResponse, Responder,
};
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, route, trace}; use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, route, trace};
use futures_core::future::LocalBoxFuture; use futures_core::future::LocalBoxFuture;
@ -66,17 +70,17 @@ fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
} }
#[put("/test/{param}")] #[put("/test/{param}")]
async fn put_param_test(_: Path<String>) -> impl Responder { async fn put_param_test(_: web::Path<String>) -> impl Responder {
HttpResponse::Created() HttpResponse::Created()
} }
#[delete("/test/{param}")] #[delete("/test/{param}")]
async fn delete_param_test(_: Path<String>) -> impl Responder { async fn delete_param_test(_: web::Path<String>) -> impl Responder {
HttpResponse::NoContent() HttpResponse::NoContent()
} }
#[get("/test/{param}")] #[get("/test/{param}")]
async fn get_param_test(_: Path<String>) -> impl Responder { async fn get_param_test(_: web::Path<String>) -> impl Responder {
HttpResponse::Ok() HttpResponse::Ok()
} }
@ -125,9 +129,7 @@ where
type Error = Error; type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { actix_web::dev::forward_ready!(service);
self.service.poll_ready(cx)
}
fn call(&self, req: ServiceRequest) -> Self::Future { fn call(&self, req: ServiceRequest) -> Self::Future {
let fut = self.service.call(req); let fut = self.service.call(req);
@ -144,7 +146,7 @@ where
} }
#[get("/test/wrap", wrap = "ChangeStatusCode")] #[get("/test/wrap", wrap = "ChangeStatusCode")]
async fn get_wrap(_: Path<String>) -> impl Responder { async fn get_wrap(_: web::Path<String>) -> impl Responder {
// panic!("actually never gets called because path failed to extract"); // panic!("actually never gets called because path failed to extract");
HttpResponse::Ok() HttpResponse::Ok()
} }

View File

@ -1,6 +1,9 @@
# Changes # Changes
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
## 3.0.0-beta.5 - 2021-04-17
### Removed ### Removed
* Deprecated methods on `ClientRequest`: `if_true`, `if_some`. [#2148] * Deprecated methods on `ClientRequest`: `if_true`, `if_some`. [#2148]

View File

@ -1,22 +1,20 @@
[package] [package]
name = "awc" name = "awc"
version = "3.0.0-beta.4" version = "3.0.0-beta.5"
authors = [ authors = [
"Nikolay Kim <fafhrd91@gmail.com>", "Nikolay Kim <fafhrd91@gmail.com>",
"fakeshadow <24548779@qq.com>", "fakeshadow <24548779@qq.com>",
] ]
description = "Async HTTP and WebSocket client library built on the Actix ecosystem" description = "Async HTTP and WebSocket client library built on the Actix ecosystem"
readme = "README.md"
keywords = ["actix", "http", "framework", "async", "web"] keywords = ["actix", "http", "framework", "async", "web"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/awc/"
categories = [ categories = [
"network-programming", "network-programming",
"asynchronous", "asynchronous",
"web-programming::http-client", "web-programming::http-client",
"web-programming::websocket", "web-programming::websocket",
] ]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
edition = "2018" edition = "2018"
@ -47,9 +45,9 @@ cookies = ["cookie"]
trust-dns = ["actix-http/trust-dns"] trust-dns = ["actix-http/trust-dns"]
[dependencies] [dependencies]
actix-codec = "0.4.0-beta.1" actix-codec = "0.4.0"
actix-service = "2.0.0-beta.4" actix-service = "2.0.0"
actix-http = "3.0.0-beta.5" actix-http = "3.0.0-beta.6"
actix-rt = { version = "2.1", default-features = false } actix-rt = { version = "2.1", default-features = false }
base64 = "0.13" base64 = "0.13"
@ -70,13 +68,13 @@ tls-openssl = { version = "0.10.9", package = "openssl", optional = true }
tls-rustls = { version = "0.19.0", package = "rustls", optional = true, features = ["dangerous_configuration"] } tls-rustls = { version = "0.19.0", package = "rustls", optional = true, features = ["dangerous_configuration"] }
[dev-dependencies] [dev-dependencies]
actix-web = { version = "4.0.0-beta.5", features = ["openssl"] } actix-web = { version = "4.0.0-beta.6", features = ["openssl"] }
actix-http = { version = "3.0.0-beta.5", features = ["openssl"] } actix-http = { version = "3.0.0-beta.6", features = ["openssl"] }
actix-http-test = { version = "3.0.0-beta.4", features = ["openssl"] } actix-http-test = { version = "3.0.0-beta.4", features = ["openssl"] }
actix-utils = "3.0.0-beta.4" actix-utils = "3.0.0"
actix-server = "2.0.0-beta.3" actix-server = "2.0.0-beta.3"
actix-tls = { version = "3.0.0-beta.5", features = ["openssl", "rustls"] } actix-tls = { version = "3.0.0-beta.5", features = ["openssl", "rustls"] }
actix-test = { version = "0.1.0-beta.1", features = ["openssl", "rustls"] } actix-test = { version = "0.1.0-beta.2", features = ["openssl", "rustls"] }
brotli2 = "0.3.2" brotli2 = "0.3.2"
env_logger = "0.8" env_logger = "0.8"

View File

@ -20,7 +20,7 @@ use actix_http::{
HttpService, HttpService,
}; };
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory}; use actix_service::{fn_service, map_config, ServiceFactoryExt as _};
use actix_web::{ use actix_web::{
dev::{AppConfig, BodyEncoding}, dev::{AppConfig, BodyEncoding},
http::header, http::header,
@ -239,7 +239,7 @@ async fn test_connection_reuse() {
let srv = test_server(move || { let srv = test_server(move || {
let num2 = num2.clone(); let num2 = num2.clone();
pipeline_factory(move |io| { fn_service(move |io| {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
@ -276,7 +276,7 @@ async fn test_connection_force_close() {
let srv = test_server(move || { let srv = test_server(move || {
let num2 = num2.clone(); let num2 = num2.clone();
pipeline_factory(move |io| { fn_service(move |io| {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
@ -313,7 +313,7 @@ async fn test_connection_server_close() {
let srv = test_server(move || { let srv = test_server(move || {
let num2 = num2.clone(); let num2 = num2.clone();
pipeline_factory(move |io| { fn_service(move |io| {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
@ -353,7 +353,7 @@ async fn test_connection_wait_queue() {
let srv = test_server(move || { let srv = test_server(move || {
let num2 = num2.clone(); let num2 = num2.clone();
pipeline_factory(move |io| { fn_service(move |io| {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })
@ -401,7 +401,7 @@ async fn test_connection_wait_queue_force_close() {
let srv = test_server(move || { let srv = test_server(move || {
let num2 = num2.clone(); let num2 = num2.clone();
pipeline_factory(move |io| { fn_service(move |io| {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })

View File

@ -12,7 +12,7 @@ use std::{
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory, ServiceFactoryExt}; use actix_service::{fn_service, map_config, ServiceFactoryExt};
use actix_utils::future::ok; use actix_utils::future::ok;
use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse}; use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse};
use rustls::internal::pemfile::{certs, pkcs8_private_keys}; use rustls::internal::pemfile::{certs, pkcs8_private_keys};
@ -57,7 +57,7 @@ async fn test_connection_reuse_h2() {
let srv = test_server(move || { let srv = test_server(move || {
let num2 = num2.clone(); let num2 = num2.clone();
pipeline_factory(move |io| { fn_service(move |io| {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })

View File

@ -7,7 +7,7 @@ use std::sync::Arc;
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory, ServiceFactoryExt}; use actix_service::{fn_service, map_config, ServiceFactoryExt};
use actix_utils::future::ok; use actix_utils::future::ok;
use actix_web::http::Version; use actix_web::http::Version;
use actix_web::{dev::AppConfig, web, App, HttpResponse}; use actix_web::{dev::AppConfig, web, App, HttpResponse};
@ -48,7 +48,7 @@ async fn test_connection_reuse_h2() {
let srv = test_server(move || { let srv = test_server(move || {
let num2 = num2.clone(); let num2 = num2.clone();
pipeline_factory(move |io| { fn_service(move |io| {
num2.fetch_add(1, Ordering::Relaxed); num2.fetch_add(1, Ordering::Relaxed);
ok(io) ok(io)
}) })

View File

@ -36,7 +36,7 @@ async fn test_simple() {
ws::Dispatcher::with(framed, ws_service).await ws::Dispatcher::with(framed, ws_service).await
} }
}) })
.finish(|_| ok::<_, Error>(Response::NotFound())) .finish(|_| ok::<_, Error>(Response::not_found()))
.tcp() .tcp()
}) })
.await; .await;

View File

@ -1,20 +1,23 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use actix_http::{Extensions, Request, Response}; use actix_http::{Extensions, Request};
use actix_router::{Path, ResourceDef, Router, Url}; use actix_router::{Path, ResourceDef, Router, Url};
use actix_service::boxed::{self, BoxService, BoxServiceFactory}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{fn_service, Service, ServiceFactory}; use actix_service::{fn_service, Service, ServiceFactory};
use futures_core::future::LocalBoxFuture; use futures_core::future::LocalBoxFuture;
use futures_util::future::join_all; use futures_util::future::join_all;
use crate::config::{AppConfig, AppService};
use crate::data::FnDataFactory; use crate::data::FnDataFactory;
use crate::error::Error; use crate::error::Error;
use crate::guard::Guard; use crate::guard::Guard;
use crate::request::{HttpRequest, HttpRequestPool}; use crate::request::{HttpRequest, HttpRequestPool};
use crate::rmap::ResourceMap; use crate::rmap::ResourceMap;
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse}; use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
use crate::{
config::{AppConfig, AppService},
HttpResponse,
};
type Guards = Vec<Box<dyn Guard>>; type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
@ -64,7 +67,7 @@ where
// if no user defined default service exists. // if no user defined default service exists.
let default = self.default.clone().unwrap_or_else(|| { let default = self.default.clone().unwrap_or_else(|| {
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async { Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async {
Ok(req.into_response(Response::NotFound().finish())) Ok(req.into_response(HttpResponse::NotFound()))
}))) })))
}); });

View File

@ -5,7 +5,7 @@ use mime::Mime;
use super::{qitem, QualityItem}; use super::{qitem, QualityItem};
use crate::http::header; use crate::http::header;
crate::header! { crate::__define_common_header! {
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2) /// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
/// ///
/// The `Accept` header field can be used by user agents to specify /// The `Accept` header field can be used by user agents to specify
@ -81,14 +81,14 @@ crate::header! {
test_accept { test_accept {
// Tests from the RFC // Tests from the RFC
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"audio/*; q=0.2, audio/basic"], vec![b"audio/*; q=0.2, audio/basic"],
Some(Accept(vec![ Some(Accept(vec![
QualityItem::new("audio/*".parse().unwrap(), q(200)), QualityItem::new("audio/*".parse().unwrap(), q(200)),
qitem("audio/basic".parse().unwrap()), qitem("audio/basic".parse().unwrap()),
]))); ])));
test_header!( crate::__common_header_test!(
test2, test2,
vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"], vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"],
Some(Accept(vec![ Some(Accept(vec![
@ -100,13 +100,13 @@ crate::header! {
qitem("text/x-c".parse().unwrap()), qitem("text/x-c".parse().unwrap()),
]))); ])));
// Custom tests // Custom tests
test_header!( crate::__common_header_test!(
test3, test3,
vec![b"text/plain; charset=utf-8"], vec![b"text/plain; charset=utf-8"],
Some(Accept(vec![ Some(Accept(vec![
qitem(mime::TEXT_PLAIN_UTF_8), qitem(mime::TEXT_PLAIN_UTF_8),
]))); ])));
test_header!( crate::__common_header_test!(
test4, test4,
vec![b"text/plain; charset=utf-8; q=0.5"], vec![b"text/plain; charset=utf-8; q=0.5"],
Some(Accept(vec![ Some(Accept(vec![

View File

@ -1,6 +1,6 @@
use super::{Charset, QualityItem, ACCEPT_CHARSET}; use super::{Charset, QualityItem, ACCEPT_CHARSET};
crate::header! { crate::__define_common_header! {
/// `Accept-Charset` header, defined in /// `Accept-Charset` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3) /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3)
/// ///
@ -57,6 +57,6 @@ crate::header! {
test_accept_charset { test_accept_charset {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"iso-8859-5, unicode-1-1;q=0.8"]); crate::__common_header_test!(test1, vec![b"iso-8859-5, unicode-1-1;q=0.8"]);
} }
} }

View File

@ -64,12 +64,12 @@ header! {
test_accept_encoding { test_accept_encoding {
// From the RFC // From the RFC
test_header!(test1, vec![b"compress, gzip"]); crate::__common_header_test!(test1, vec![b"compress, gzip"]);
test_header!(test2, vec![b""], Some(AcceptEncoding(vec![]))); crate::__common_header_test!(test2, vec![b""], Some(AcceptEncoding(vec![])));
test_header!(test3, vec![b"*"]); crate::__common_header_test!(test3, vec![b"*"]);
// Note: Removed quality 1 from gzip // Note: Removed quality 1 from gzip
test_header!(test4, vec![b"compress;q=0.5, gzip"]); crate::__common_header_test!(test4, vec![b"compress;q=0.5, gzip"]);
// Note: Removed quality 1 from gzip // Note: Removed quality 1 from gzip
test_header!(test5, vec![b"gzip, identity; q=0.5, *;q=0"]); crate::__common_header_test!(test5, vec![b"gzip, identity; q=0.5, *;q=0"]);
} }
} }

View File

@ -1,7 +1,8 @@
use super::{QualityItem, ACCEPT_LANGUAGE};
use language_tags::LanguageTag; use language_tags::LanguageTag;
crate::header! { use super::{QualityItem, ACCEPT_LANGUAGE};
crate::__define_common_header! {
/// `Accept-Language` header, defined in /// `Accept-Language` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5) /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
/// ///
@ -56,9 +57,9 @@ crate::header! {
test_accept_language { test_accept_language {
// From the RFC // From the RFC
test_header!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]); crate::__common_header_test!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]);
// Own test // Own test
test_header!( crate::__common_header_test!(
test2, vec![b"en-US, en; q=0.5, fr"], test2, vec![b"en-US, en; q=0.5, fr"],
Some(AcceptLanguage(vec![ Some(AcceptLanguage(vec![
qitem("en-US".parse().unwrap()), qitem("en-US".parse().unwrap()),

View File

@ -1,7 +1,7 @@
use actix_http::http::Method;
use crate::http::header; use crate::http::header;
use actix_http::http::Method;
crate::header! { crate::__define_common_header! {
/// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1) /// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)
/// ///
/// The `Allow` header field lists the set of methods advertised as /// The `Allow` header field lists the set of methods advertised as
@ -49,12 +49,12 @@ crate::header! {
test_allow { test_allow {
// From the RFC // From the RFC
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"GET, HEAD, PUT"], vec![b"GET, HEAD, PUT"],
Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT]))); Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT])));
// Own tests // Own tests
test_header!( crate::__common_header_test!(
test2, test2,
vec![b"OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH"], vec![b"OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH"],
Some(HeaderField(vec![ Some(HeaderField(vec![
@ -67,7 +67,7 @@ crate::header! {
Method::TRACE, Method::TRACE,
Method::CONNECT, Method::CONNECT,
Method::PATCH]))); Method::PATCH])));
test_header!( crate::__common_header_test!(
test3, test3,
vec![b""], vec![b""],
Some(HeaderField(Vec::<Method>::new()))); Some(HeaderField(Vec::<Method>::new())));

View File

@ -1,9 +1,7 @@
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::str::FromStr; use std::str::FromStr;
use super::{ use super::{fmt_comma_delimited, from_comma_delimited, Header, IntoHeaderValue, Writer};
fmt_comma_delimited, from_comma_delimited, Header, IntoHeaderValue, Writer,
};
use crate::http::header; use crate::http::header;
@ -51,9 +49,9 @@ use crate::http::header;
#[derive(PartialEq, Clone, Debug)] #[derive(PartialEq, Clone, Debug)]
pub struct CacheControl(pub Vec<CacheDirective>); pub struct CacheControl(pub Vec<CacheDirective>);
__hyper__deref!(CacheControl => Vec<CacheDirective>); crate::__common_header_deref!(CacheControl => Vec<CacheDirective>);
//TODO: this could just be the header! macro // TODO: this could just be the __define_common_header! macro
impl Header for CacheControl { impl Header for CacheControl {
fn name() -> header::HeaderName { fn name() -> header::HeaderName {
header::CACHE_CONTROL header::CACHE_CONTROL
@ -75,7 +73,7 @@ impl Header for CacheControl {
impl fmt::Display for CacheControl { impl fmt::Display for CacheControl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_comma_delimited(f, &self[..]) fmt_comma_delimited(f, &self.0[..])
} }
} }
@ -176,9 +174,7 @@ impl FromStr for CacheDirective {
("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some), ("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some), ("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some), ("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
(left, right) => { (left, right) => Ok(Extension(left.to_owned(), Some(right.to_owned()))),
Ok(Extension(left.to_owned(), Some(right.to_owned())))
}
} }
} }
Some(_) => Err(None), Some(_) => Err(None),

View File

@ -10,8 +10,8 @@ use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use crate::http::header;
use super::{ExtendedValue, Header, IntoHeaderValue, Writer}; use super::{ExtendedValue, Header, IntoHeaderValue, Writer};
use crate::http::header;
/// Split at the index of the first `needle` if it exists or at the end. /// Split at the index of the first `needle` if it exists or at the end.
fn split_once(haystack: &str, needle: char) -> (&str, &str) { fn split_once(haystack: &str, needle: char) -> (&str, &str) {
@ -401,15 +401,11 @@ impl ContentDisposition {
} }
/// Returns `true` if it is [`Ext`](DispositionType::Ext) and the `disp_type` matches. /// Returns `true` if it is [`Ext`](DispositionType::Ext) and the `disp_type` matches.
pub fn is_ext<T: AsRef<str>>(&self, disp_type: T) -> bool { pub fn is_ext(&self, disp_type: impl AsRef<str>) -> bool {
match self.disposition { matches!(
DispositionType::Ext(ref t) self.disposition,
if t.eq_ignore_ascii_case(disp_type.as_ref()) => DispositionType::Ext(ref t) if t.eq_ignore_ascii_case(disp_type.as_ref())
{ )
true
}
_ => false,
}
} }
/// Return the value of *name* if exists. /// Return the value of *name* if exists.
@ -434,7 +430,7 @@ impl ContentDisposition {
} }
/// Return the value of the parameter which the `name` matches. /// Return the value of the parameter which the `name` matches.
pub fn get_unknown<T: AsRef<str>>(&self, name: T) -> Option<&str> { pub fn get_unknown(&self, name: impl AsRef<str>) -> Option<&str> {
let name = name.as_ref(); let name = name.as_ref();
self.parameters self.parameters
.iter() .iter()
@ -443,7 +439,7 @@ impl ContentDisposition {
} }
/// Return the value of the extended parameter which the `name` matches. /// Return the value of the extended parameter which the `name` matches.
pub fn get_unknown_ext<T: AsRef<str>>(&self, name: T) -> Option<&ExtendedValue> { pub fn get_unknown_ext(&self, name: impl AsRef<str>) -> Option<&ExtendedValue> {
let name = name.as_ref(); let name = name.as_ref();
self.parameters self.parameters
.iter() .iter()
@ -521,7 +517,8 @@ impl fmt::Display for DispositionParam {
// //
// //
// See also comments in test_from_raw_unnecessary_percent_decode. // See also comments in test_from_raw_unnecessary_percent_decode.
static RE: Lazy<Regex> = Lazy::new(|| Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").unwrap()); static RE: Lazy<Regex> =
Lazy::new(|| Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").unwrap());
match self { match self {
DispositionParam::Name(ref value) => write!(f, "name={}", value), DispositionParam::Name(ref value) => write!(f, "name={}", value),
DispositionParam::Filename(ref value) => { DispositionParam::Filename(ref value) => {
@ -555,8 +552,7 @@ impl fmt::Display for ContentDisposition {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{ContentDisposition, DispositionParam, DispositionType}; use super::{ContentDisposition, DispositionParam, DispositionType};
use crate::http::header::Charset; use crate::http::header::{Charset, ExtendedValue, HeaderValue};
use crate::http::header::{ExtendedValue, HeaderValue};
#[test] #[test]
fn test_from_raw_basic() { fn test_from_raw_basic() {
@ -618,8 +614,8 @@ mod tests {
charset: Charset::Ext(String::from("UTF-8")), charset: Charset::Ext(String::from("UTF-8")),
language_tag: None, language_tag: None,
value: vec![ value: vec![
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, 0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r',
b'r', b'a', b't', b'e', b's', b'a', b't', b'e', b's',
], ],
})], })],
}; };
@ -635,8 +631,8 @@ mod tests {
charset: Charset::Ext(String::from("UTF-8")), charset: Charset::Ext(String::from("UTF-8")),
language_tag: None, language_tag: None,
value: vec![ value: vec![
0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, 0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r',
b'r', b'a', b't', b'e', b's', b'a', b't', b'e', b's',
], ],
})], })],
}; };
@ -698,25 +694,21 @@ mod tests {
#[test] #[test]
fn test_from_raw_only_disp() { fn test_from_raw_only_disp() {
let a = ContentDisposition::from_raw(&HeaderValue::from_static("attachment")) let a = ContentDisposition::from_raw(&HeaderValue::from_static("attachment")).unwrap();
.unwrap();
let b = ContentDisposition { let b = ContentDisposition {
disposition: DispositionType::Attachment, disposition: DispositionType::Attachment,
parameters: vec![], parameters: vec![],
}; };
assert_eq!(a, b); assert_eq!(a, b);
let a = let a = ContentDisposition::from_raw(&HeaderValue::from_static("inline ;")).unwrap();
ContentDisposition::from_raw(&HeaderValue::from_static("inline ;")).unwrap();
let b = ContentDisposition { let b = ContentDisposition {
disposition: DispositionType::Inline, disposition: DispositionType::Inline,
parameters: vec![], parameters: vec![],
}; };
assert_eq!(a, b); assert_eq!(a, b);
let a = ContentDisposition::from_raw(&HeaderValue::from_static( let a = ContentDisposition::from_raw(&HeaderValue::from_static("unknown-disp-param"))
"unknown-disp-param",
))
.unwrap(); .unwrap();
let b = ContentDisposition { let b = ContentDisposition {
disposition: DispositionType::Ext(String::from("unknown-disp-param")), disposition: DispositionType::Ext(String::from("unknown-disp-param")),
@ -756,8 +748,8 @@ mod tests {
Mainstream browsers like Firefox (gecko) and Chrome use UTF-8 directly as above. Mainstream browsers like Firefox (gecko) and Chrome use UTF-8 directly as above.
(And now, only UTF-8 is handled by this implementation.) (And now, only UTF-8 is handled by this implementation.)
*/ */
let a = HeaderValue::from_str("form-data; name=upload; filename=\"文件.webp\"") let a =
.unwrap(); HeaderValue::from_str("form-data; name=upload; filename=\"文件.webp\"").unwrap();
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap(); let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
let b = ContentDisposition { let b = ContentDisposition {
disposition: DispositionType::FormData, disposition: DispositionType::FormData,
@ -808,8 +800,7 @@ mod tests {
#[test] #[test]
fn test_from_raw_semicolon() { fn test_from_raw_semicolon() {
let a = let a = HeaderValue::from_static("form-data; filename=\"A semicolon here;.pdf\"");
HeaderValue::from_static("form-data; filename=\"A semicolon here;.pdf\"");
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap(); let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
let b = ContentDisposition { let b = ContentDisposition {
disposition: DispositionType::FormData, disposition: DispositionType::FormData,
@ -845,9 +836,8 @@ mod tests {
}; };
assert_eq!(a, b); assert_eq!(a, b);
let a = HeaderValue::from_static( let a =
"form-data; name=photo; filename=\"%74%65%73%74.png\"", HeaderValue::from_static("form-data; name=photo; filename=\"%74%65%73%74.png\"");
);
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap(); let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
let b = ContentDisposition { let b = ContentDisposition {
disposition: DispositionType::FormData, disposition: DispositionType::FormData,
@ -892,8 +882,7 @@ mod tests {
#[test] #[test]
fn test_display_extended() { fn test_display_extended() {
let as_string = let as_string = "attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
"attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
let a = HeaderValue::from_static(as_string); let a = HeaderValue::from_static(as_string);
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap(); let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
let display_rendered = format!("{}", a); let display_rendered = format!("{}", a);

View File

@ -1,7 +1,7 @@
use super::{QualityItem, CONTENT_LANGUAGE}; use super::{QualityItem, CONTENT_LANGUAGE};
use language_tags::LanguageTag; use language_tags::LanguageTag;
crate::header! { crate::__define_common_header! {
/// `Content-Language` header, defined in /// `Content-Language` header, defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2) /// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
/// ///
@ -52,7 +52,7 @@ crate::header! {
(ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+ (ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+
test_content_language { test_content_language {
test_header!(test1, vec![b"da"]); crate::__common_header_test!(test1, vec![b"da"]);
test_header!(test2, vec![b"mi, en"]); crate::__common_header_test!(test2, vec![b"mi, en"]);
} }
} }

View File

@ -1,70 +1,68 @@
use std::fmt::{self, Display, Write}; use std::fmt::{self, Display, Write};
use std::str::FromStr; use std::str::FromStr;
use super::{HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE};
use crate::error::ParseError; use crate::error::ParseError;
use super::{
HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE,
};
crate::header! { crate::__define_common_header! {
/// `Content-Range` header, defined in /// `Content-Range` header, defined in
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2) /// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2)
(ContentRange, CONTENT_RANGE) => [ContentRangeSpec] (ContentRange, CONTENT_RANGE) => [ContentRangeSpec]
test_content_range { test_content_range {
test_header!(test_bytes, crate::__common_header_test!(test_bytes,
vec![b"bytes 0-499/500"], vec![b"bytes 0-499/500"],
Some(ContentRange(ContentRangeSpec::Bytes { Some(ContentRange(ContentRangeSpec::Bytes {
range: Some((0, 499)), range: Some((0, 499)),
instance_length: Some(500) instance_length: Some(500)
}))); })));
test_header!(test_bytes_unknown_len, crate::__common_header_test!(test_bytes_unknown_len,
vec![b"bytes 0-499/*"], vec![b"bytes 0-499/*"],
Some(ContentRange(ContentRangeSpec::Bytes { Some(ContentRange(ContentRangeSpec::Bytes {
range: Some((0, 499)), range: Some((0, 499)),
instance_length: None instance_length: None
}))); })));
test_header!(test_bytes_unknown_range, crate::__common_header_test!(test_bytes_unknown_range,
vec![b"bytes */500"], vec![b"bytes */500"],
Some(ContentRange(ContentRangeSpec::Bytes { Some(ContentRange(ContentRangeSpec::Bytes {
range: None, range: None,
instance_length: Some(500) instance_length: Some(500)
}))); })));
test_header!(test_unregistered, crate::__common_header_test!(test_unregistered,
vec![b"seconds 1-2"], vec![b"seconds 1-2"],
Some(ContentRange(ContentRangeSpec::Unregistered { Some(ContentRange(ContentRangeSpec::Unregistered {
unit: "seconds".to_owned(), unit: "seconds".to_owned(),
resp: "1-2".to_owned() resp: "1-2".to_owned()
}))); })));
test_header!(test_no_len, crate::__common_header_test!(test_no_len,
vec![b"bytes 0-499"], vec![b"bytes 0-499"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_only_unit, crate::__common_header_test!(test_only_unit,
vec![b"bytes"], vec![b"bytes"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_end_less_than_start, crate::__common_header_test!(test_end_less_than_start,
vec![b"bytes 499-0/500"], vec![b"bytes 499-0/500"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_blank, crate::__common_header_test!(test_blank,
vec![b""], vec![b""],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_bytes_many_spaces, crate::__common_header_test!(test_bytes_many_spaces,
vec![b"bytes 1-2/500 3"], vec![b"bytes 1-2/500 3"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_bytes_many_slashes, crate::__common_header_test!(test_bytes_many_slashes,
vec![b"bytes 1-2/500/600"], vec![b"bytes 1-2/500/600"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_bytes_many_dashes, crate::__common_header_test!(test_bytes_many_dashes,
vec![b"bytes 1-2-3/500"], vec![b"bytes 1-2-3/500"],
None::<ContentRange>); None::<ContentRange>);
@ -141,8 +139,7 @@ impl FromStr for ContentRangeSpec {
} else { } else {
let (first_byte, last_byte) = let (first_byte, last_byte) =
split_in_two(range, '-').ok_or(ParseError::Header)?; split_in_two(range, '-').ok_or(ParseError::Header)?;
let first_byte = let first_byte = first_byte.parse().map_err(|_| ParseError::Header)?;
first_byte.parse().map_err(|_| ParseError::Header)?;
let last_byte = last_byte.parse().map_err(|_| ParseError::Header)?; let last_byte = last_byte.parse().map_err(|_| ParseError::Header)?;
if last_byte < first_byte { if last_byte < first_byte {
return Err(ParseError::Header); return Err(ParseError::Header);

View File

@ -1,7 +1,7 @@
use super::CONTENT_TYPE; use super::CONTENT_TYPE;
use mime::Mime; use mime::Mime;
crate::header! { crate::__define_common_header! {
/// `Content-Type` header, defined in /// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5) /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
/// ///
@ -52,7 +52,7 @@ crate::header! {
(ContentType, CONTENT_TYPE) => [Mime] (ContentType, CONTENT_TYPE) => [Mime]
test_content_type { test_content_type {
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"text/html"], vec![b"text/html"],
Some(HeaderField(mime::TEXT_HTML))); Some(HeaderField(mime::TEXT_HTML)));

View File

@ -1,7 +1,7 @@
use super::{HttpDate, DATE}; use super::{HttpDate, DATE};
use std::time::SystemTime; use std::time::SystemTime;
crate::header! { crate::__define_common_header! {
/// `Date` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.1.2) /// `Date` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.1.2)
/// ///
/// The `Date` header field represents the date and time at which the /// The `Date` header field represents the date and time at which the
@ -32,7 +32,7 @@ crate::header! {
(Date, DATE) => [HttpDate] (Date, DATE) => [HttpDate]
test_date { test_date {
test_header!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]); crate::__common_header_test!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]);
} }
} }

View File

@ -1,6 +1,6 @@
use super::{EntityTag, ETAG}; use super::{EntityTag, ETAG};
crate::header! { crate::__define_common_header! {
/// `ETag` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.3) /// `ETag` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.3)
/// ///
/// The `ETag` header field in a response provides the current entity-tag /// The `ETag` header field in a response provides the current entity-tag
@ -50,50 +50,50 @@ crate::header! {
test_etag { test_etag {
// From the RFC // From the RFC
test_header!(test1, crate::__common_header_test!(test1,
vec![b"\"xyzzy\""], vec![b"\"xyzzy\""],
Some(ETag(EntityTag::new(false, "xyzzy".to_owned())))); Some(ETag(EntityTag::new(false, "xyzzy".to_owned()))));
test_header!(test2, crate::__common_header_test!(test2,
vec![b"W/\"xyzzy\""], vec![b"W/\"xyzzy\""],
Some(ETag(EntityTag::new(true, "xyzzy".to_owned())))); Some(ETag(EntityTag::new(true, "xyzzy".to_owned()))));
test_header!(test3, crate::__common_header_test!(test3,
vec![b"\"\""], vec![b"\"\""],
Some(ETag(EntityTag::new(false, "".to_owned())))); Some(ETag(EntityTag::new(false, "".to_owned()))));
// Own tests // Own tests
test_header!(test4, crate::__common_header_test!(test4,
vec![b"\"foobar\""], vec![b"\"foobar\""],
Some(ETag(EntityTag::new(false, "foobar".to_owned())))); Some(ETag(EntityTag::new(false, "foobar".to_owned()))));
test_header!(test5, crate::__common_header_test!(test5,
vec![b"\"\""], vec![b"\"\""],
Some(ETag(EntityTag::new(false, "".to_owned())))); Some(ETag(EntityTag::new(false, "".to_owned()))));
test_header!(test6, crate::__common_header_test!(test6,
vec![b"W/\"weak-etag\""], vec![b"W/\"weak-etag\""],
Some(ETag(EntityTag::new(true, "weak-etag".to_owned())))); Some(ETag(EntityTag::new(true, "weak-etag".to_owned()))));
test_header!(test7, crate::__common_header_test!(test7,
vec![b"W/\"\x65\x62\""], vec![b"W/\"\x65\x62\""],
Some(ETag(EntityTag::new(true, "\u{0065}\u{0062}".to_owned())))); Some(ETag(EntityTag::new(true, "\u{0065}\u{0062}".to_owned()))));
test_header!(test8, crate::__common_header_test!(test8,
vec![b"W/\"\""], vec![b"W/\"\""],
Some(ETag(EntityTag::new(true, "".to_owned())))); Some(ETag(EntityTag::new(true, "".to_owned()))));
test_header!(test9, crate::__common_header_test!(test9,
vec![b"no-dquotes"], vec![b"no-dquotes"],
None::<ETag>); None::<ETag>);
test_header!(test10, crate::__common_header_test!(test10,
vec![b"w/\"the-first-w-is-case-sensitive\""], vec![b"w/\"the-first-w-is-case-sensitive\""],
None::<ETag>); None::<ETag>);
test_header!(test11, crate::__common_header_test!(test11,
vec![b""], vec![b""],
None::<ETag>); None::<ETag>);
test_header!(test12, crate::__common_header_test!(test12,
vec![b"\"unmatched-dquotes1"], vec![b"\"unmatched-dquotes1"],
None::<ETag>); None::<ETag>);
test_header!(test13, crate::__common_header_test!(test13,
vec![b"unmatched-dquotes2\""], vec![b"unmatched-dquotes2\""],
None::<ETag>); None::<ETag>);
test_header!(test14, crate::__common_header_test!(test14,
vec![b"matched-\"dquotes\""], vec![b"matched-\"dquotes\""],
None::<ETag>); None::<ETag>);
test_header!(test15, crate::__common_header_test!(test15,
vec![b"\""], vec![b"\""],
None::<ETag>); None::<ETag>);
} }

View File

@ -1,6 +1,6 @@
use super::{HttpDate, EXPIRES}; use super::{HttpDate, EXPIRES};
crate::header! { crate::__define_common_header! {
/// `Expires` header, defined in [RFC7234](http://tools.ietf.org/html/rfc7234#section-5.3) /// `Expires` header, defined in [RFC7234](http://tools.ietf.org/html/rfc7234#section-5.3)
/// ///
/// The `Expires` header field gives the date/time after which the /// The `Expires` header field gives the date/time after which the
@ -36,6 +36,6 @@ crate::header! {
test_expires { test_expires {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Thu, 01 Dec 1994 16:00:00 GMT"]); crate::__common_header_test!(test1, vec![b"Thu, 01 Dec 1994 16:00:00 GMT"]);
} }
} }

View File

@ -1,6 +1,6 @@
use super::{EntityTag, IF_MATCH}; use super::{EntityTag, IF_MATCH};
crate::header! { crate::__define_common_header! {
/// `If-Match` header, defined in /// `If-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1) /// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1)
/// ///
@ -53,18 +53,18 @@ crate::header! {
(IfMatch, IF_MATCH) => {Any / (EntityTag)+} (IfMatch, IF_MATCH) => {Any / (EntityTag)+}
test_if_match { test_if_match {
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"\"xyzzy\""], vec![b"\"xyzzy\""],
Some(HeaderField::Items( Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned())]))); vec![EntityTag::new(false, "xyzzy".to_owned())])));
test_header!( crate::__common_header_test!(
test2, test2,
vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""], vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""],
Some(HeaderField::Items( Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned()), vec![EntityTag::new(false, "xyzzy".to_owned()),
EntityTag::new(false, "r2d2xxxx".to_owned()), EntityTag::new(false, "r2d2xxxx".to_owned()),
EntityTag::new(false, "c3piozzzz".to_owned())]))); EntityTag::new(false, "c3piozzzz".to_owned())])));
test_header!(test3, vec![b"*"], Some(IfMatch::Any)); crate::__common_header_test!(test3, vec![b"*"], Some(IfMatch::Any));
} }
} }

View File

@ -1,6 +1,6 @@
use super::{HttpDate, IF_MODIFIED_SINCE}; use super::{HttpDate, IF_MODIFIED_SINCE};
crate::header! { crate::__define_common_header! {
/// `If-Modified-Since` header, defined in /// `If-Modified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.3) /// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.3)
/// ///
@ -36,6 +36,6 @@ crate::header! {
test_if_modified_since { test_if_modified_since {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]); crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
} }
} }

View File

@ -1,6 +1,6 @@
use super::{EntityTag, IF_NONE_MATCH}; use super::{EntityTag, IF_NONE_MATCH};
crate::header! { crate::__define_common_header! {
/// `If-None-Match` header, defined in /// `If-None-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.2) /// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.2)
/// ///
@ -55,11 +55,11 @@ crate::header! {
(IfNoneMatch, IF_NONE_MATCH) => {Any / (EntityTag)+} (IfNoneMatch, IF_NONE_MATCH) => {Any / (EntityTag)+}
test_if_none_match { test_if_none_match {
test_header!(test1, vec![b"\"xyzzy\""]); crate::__common_header_test!(test1, vec![b"\"xyzzy\""]);
test_header!(test2, vec![b"W/\"xyzzy\""]); crate::__common_header_test!(test2, vec![b"W/\"xyzzy\""]);
test_header!(test3, vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]); crate::__common_header_test!(test3, vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]);
test_header!(test4, vec![b"W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\""]); crate::__common_header_test!(test4, vec![b"W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\""]);
test_header!(test5, vec![b"*"]); crate::__common_header_test!(test5, vec![b"*"]);
} }
} }

View File

@ -1,11 +1,11 @@
use std::fmt::{self, Display, Write}; use std::fmt::{self, Display, Write};
use crate::http::header;
use crate::error::ParseError;
use super::{ use super::{
from_one_raw_str, EntityTag, Header, HeaderName, HeaderValue, HttpDate, from_one_raw_str, EntityTag, Header, HeaderName, HeaderValue, HttpDate, IntoHeaderValue,
IntoHeaderValue, InvalidHeaderValue, Writer, InvalidHeaderValue, Writer,
}; };
use crate::error::ParseError;
use crate::http::header;
use crate::HttpMessage; use crate::HttpMessage;
/// `If-Range` header, defined in [RFC7233](http://tools.ietf.org/html/rfc7233#section-3.2) /// `If-Range` header, defined in [RFC7233](http://tools.ietf.org/html/rfc7233#section-3.2)
@ -76,13 +76,11 @@ impl Header for IfRange {
where where
T: HttpMessage, T: HttpMessage,
{ {
let etag: Result<EntityTag, _> = let etag: Result<EntityTag, _> = from_one_raw_str(msg.headers().get(&header::IF_RANGE));
from_one_raw_str(msg.headers().get(&header::IF_RANGE));
if let Ok(etag) = etag { if let Ok(etag) = etag {
return Ok(IfRange::EntityTag(etag)); return Ok(IfRange::EntityTag(etag));
} }
let date: Result<HttpDate, _> = let date: Result<HttpDate, _> = from_one_raw_str(msg.headers().get(&header::IF_RANGE));
from_one_raw_str(msg.headers().get(&header::IF_RANGE));
if let Ok(date) = date { if let Ok(date) = date {
return Ok(IfRange::Date(date)); return Ok(IfRange::Date(date));
} }
@ -115,7 +113,7 @@ mod test_if_range {
use crate::http::header::*; use crate::http::header::*;
use std::str; use std::str;
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]); crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
test_header!(test2, vec![b"\"abc\""]); crate::__common_header_test!(test2, vec![b"\"abc\""]);
test_header!(test3, vec![b"this-is-invalid"], None::<IfRange>); crate::__common_header_test!(test3, vec![b"this-is-invalid"], None::<IfRange>);
} }

View File

@ -1,6 +1,6 @@
use super::{HttpDate, IF_UNMODIFIED_SINCE}; use super::{HttpDate, IF_UNMODIFIED_SINCE};
crate::header! { crate::__define_common_header! {
/// `If-Unmodified-Since` header, defined in /// `If-Unmodified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4) /// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4)
/// ///
@ -37,6 +37,6 @@ crate::header! {
test_if_unmodified_since { test_if_unmodified_since {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]); crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
} }
} }

View File

@ -1,6 +1,6 @@
use super::{HttpDate, LAST_MODIFIED}; use super::{HttpDate, LAST_MODIFIED};
crate::header! { crate::__define_common_header! {
/// `Last-Modified` header, defined in /// `Last-Modified` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.2) /// [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.2)
/// ///
@ -36,5 +36,6 @@ crate::header! {
test_last_modified { test_last_modified {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);} crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
}
} }

300
src/http/header/macros.rs Normal file
View File

@ -0,0 +1,300 @@
#[doc(hidden)]
#[macro_export]
macro_rules! __common_header_deref {
($from:ty => $to:ty) => {
impl ::std::ops::Deref for $from {
type Target = $to;
#[inline]
fn deref(&self) -> &$to {
&self.0
}
}
impl ::std::ops::DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut $to {
&mut self.0
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __common_header_test_module {
($id:ident, $tm:ident{$($tf:item)*}) => {
#[allow(unused_imports)]
#[cfg(test)]
mod $tm {
use std::str;
use actix_http::http::Method;
use mime::*;
use $crate::http::header::*;
use super::$id as HeaderField;
$($tf)*
}
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! __common_header_test {
($id:ident, $raw:expr) => {
#[test]
fn $id() {
use actix_http::test;
let raw = $raw;
let a: Vec<Vec<u8>> = raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req = req.insert_header((HeaderField::name(), item)).take();
}
let req = req.finish();
let value = HeaderField::parse(&req);
let result = format!("{}", value.unwrap());
let expected = String::from_utf8(raw[0].to_vec()).unwrap();
let result_cmp: Vec<String> = result
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
let expected_cmp: Vec<String> = expected
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
assert_eq!(result_cmp.concat(), expected_cmp.concat());
}
};
($id:ident, $raw:expr, $typed:expr) => {
#[test]
fn $id() {
use actix_http::test;
let a: Vec<Vec<u8>> = $raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req.insert_header((HeaderField::name(), item));
}
let req = req.finish();
let val = HeaderField::parse(&req);
let typed: Option<HeaderField> = $typed;
// Test parsing
assert_eq!(val.ok(), typed);
// Test formatting
if typed.is_some() {
let raw = &($raw)[..];
let mut iter = raw.iter().map(|b| str::from_utf8(&b[..]).unwrap());
let mut joined = String::new();
joined.push_str(iter.next().unwrap());
for s in iter {
joined.push_str(", ");
joined.push_str(s);
}
assert_eq!(format!("{}", typed.unwrap()), joined);
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __define_common_header {
// $a:meta: Attributes associated with the header item (usually docs)
// $id:ident: Identifier of the header
// $n:expr: Lowercase name of the header
// $nn:expr: Nice name of the header
// List header, zero or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)*) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
crate::__common_header_deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> ::std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// List header, one or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)+) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
crate::__common_header_deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// Single value header
($(#[$a:meta])*($id:ident, $name:expr) => [$value:ty]) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub $value);
crate::__common_header_deref!($id => $value);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_one_raw_str(
msg.headers().get(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
self.0.try_into_value()
}
}
};
// List header, one or more items with "*" option
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+}) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub enum $id {
/// Any value is a match
Any,
/// Only the listed items are a match
Items(Vec<$item>),
}
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
let any = msg.headers().get(Self::name()).and_then(|hdr| {
hdr.to_str().ok().and_then(|hdr| Some(hdr.trim() == "*"))});
if let Some(true) = any {
Ok($id::Any)
} else {
Ok($id::Items(
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name()))?))
}
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
$id::Any => f.write_str("*"),
$id::Items(ref fields) => $crate::http::header::fmt_comma_delimited(
f, &fields[..])
}
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// optional test module
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])*
($id, $name) => ($item)*
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])*
($id, $n) => ($item)+
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => [$item:ty] $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])* ($id, $name) => [$item]
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])*
($id, $name) => {Any / ($item)+}
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
}

View File

@ -2,28 +2,26 @@
//! //!
//! ## Mime //! ## Mime
//! //!
//! Several header fields use MIME values for their contents. Keeping with the //! Several header fields use MIME values for their contents. Keeping with the strongly-typed theme,
//! strongly-typed theme, the [mime] crate //! the [mime] crate is used in such headers as [`ContentType`] and [`Accept`].
//! is used, such as `ContentType(pub Mime)`.
#![cfg_attr(rustfmt, rustfmt_skip)]
use bytes::{Bytes, BytesMut};
use std::fmt; use std::fmt;
use bytes::{BytesMut, Bytes};
pub use actix_http::http::header::*;
pub use self::accept_charset::AcceptCharset; pub use self::accept_charset::AcceptCharset;
pub use actix_http::http::header::*;
//pub use self::accept_encoding::AcceptEncoding; //pub use self::accept_encoding::AcceptEncoding;
pub use self::accept::Accept; pub use self::accept::Accept;
pub use self::accept_language::AcceptLanguage; pub use self::accept_language::AcceptLanguage;
pub use self::allow::Allow; pub use self::allow::Allow;
pub use self::cache_control::{CacheControl, CacheDirective}; pub use self::cache_control::{CacheControl, CacheDirective};
pub use self::content_disposition::{ pub use self::content_disposition::{ContentDisposition, DispositionParam, DispositionType};
ContentDisposition, DispositionParam, DispositionType,
};
pub use self::content_language::ContentLanguage; pub use self::content_language::ContentLanguage;
pub use self::content_range::{ContentRange, ContentRangeSpec}; pub use self::content_range::{ContentRange, ContentRangeSpec};
pub use self::content_type::ContentType; pub use self::content_type::ContentType;
pub use self::date::Date; pub use self::date::Date;
pub use self::encoding::Encoding;
pub use self::entity::EntityTag;
pub use self::etag::ETag; pub use self::etag::ETag;
pub use self::expires::Expires; pub use self::expires::Expires;
pub use self::if_match::IfMatch; pub use self::if_match::IfMatch;
@ -32,10 +30,10 @@ pub use self::if_none_match::IfNoneMatch;
pub use self::if_range::IfRange; pub use self::if_range::IfRange;
pub use self::if_unmodified_since::IfUnmodifiedSince; pub use self::if_unmodified_since::IfUnmodifiedSince;
pub use self::last_modified::LastModified; pub use self::last_modified::LastModified;
pub use self::encoding::Encoding;
pub use self::entity::EntityTag;
//pub use self::range::{Range, ByteRangeSpec}; //pub use self::range::{Range, ByteRangeSpec};
pub(crate) use actix_http::http::header::{fmt_comma_delimited, from_comma_delimited, from_one_raw_str}; pub(crate) use actix_http::http::header::{
fmt_comma_delimited, from_comma_delimited, from_one_raw_str,
};
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct Writer { struct Writer {
@ -65,309 +63,6 @@ impl fmt::Write for Writer {
} }
} }
#[doc(hidden)]
#[macro_export]
macro_rules! __hyper__deref {
($from:ty => $to:ty) => {
impl ::std::ops::Deref for $from {
type Target = $to;
#[inline]
fn deref(&self) -> &$to {
&self.0
}
}
impl ::std::ops::DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut $to {
&mut self.0
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __hyper__tm {
($id:ident, $tm:ident{$($tf:item)*}) => {
#[allow(unused_imports)]
#[cfg(test)]
mod $tm{
use std::str;
use actix_http::http::Method;
use mime::*;
use $crate::http::header::*;
use super::$id as HeaderField;
$($tf)*
}
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! test_header {
($id:ident, $raw:expr) => {
#[test]
fn $id() {
use actix_http::test;
let raw = $raw;
let a: Vec<Vec<u8>> = raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req = req.insert_header((HeaderField::name(), item)).take();
}
let req = req.finish();
let value = HeaderField::parse(&req);
let result = format!("{}", value.unwrap());
let expected = String::from_utf8(raw[0].to_vec()).unwrap();
let result_cmp: Vec<String> = result
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
let expected_cmp: Vec<String> = expected
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
assert_eq!(result_cmp.concat(), expected_cmp.concat());
}
};
($id:ident, $raw:expr, $typed:expr) => {
#[test]
fn $id() {
use actix_http::test;
let a: Vec<Vec<u8>> = $raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req.insert_header((HeaderField::name(), item));
}
let req = req.finish();
let val = HeaderField::parse(&req);
let typed: Option<HeaderField> = $typed;
// Test parsing
assert_eq!(val.ok(), typed);
// Test formatting
if typed.is_some() {
let raw = &($raw)[..];
let mut iter = raw.iter().map(|b| str::from_utf8(&b[..]).unwrap());
let mut joined = String::new();
joined.push_str(iter.next().unwrap());
for s in iter {
joined.push_str(", ");
joined.push_str(s);
}
assert_eq!(format!("{}", typed.unwrap()), joined);
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! header {
// $a:meta: Attributes associated with the header item (usually docs)
// $id:ident: Identifier of the header
// $n:expr: Lowercase name of the header
// $nn:expr: Nice name of the header
// List header, zero or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)*) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
__hyper__deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> ::std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// List header, one or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)+) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
__hyper__deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// Single value header
($(#[$a:meta])*($id:ident, $name:expr) => [$value:ty]) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub $value);
__hyper__deref!($id => $value);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_one_raw_str(
msg.headers().get(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
self.0.try_into_value()
}
}
};
// List header, one or more items with "*" option
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+}) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub enum $id {
/// Any value is a match
Any,
/// Only the listed items are a match
Items(Vec<$item>),
}
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
let any = msg.headers().get(Self::name()).and_then(|hdr| {
hdr.to_str().ok().and_then(|hdr| Some(hdr.trim() == "*"))});
if let Some(true) = any {
Ok($id::Any)
} else {
Ok($id::Items(
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name()))?))
}
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
$id::Any => f.write_str("*"),
$id::Items(ref fields) => $crate::http::header::fmt_comma_delimited(
f, &fields[..])
}
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// optional test module
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])*
($id, $name) => ($item)*
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])*
($id, $n) => ($item)+
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => [$item:ty] $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])* ($id, $name) => [$item]
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])*
($id, $name) => {Any / ($item)+}
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
}
mod accept_charset; mod accept_charset;
// mod accept_encoding; // mod accept_encoding;
mod accept; mod accept;
@ -379,6 +74,8 @@ mod content_language;
mod content_range; mod content_range;
mod content_type; mod content_type;
mod date; mod date;
mod encoding;
mod entity;
mod etag; mod etag;
mod expires; mod expires;
mod if_match; mod if_match;
@ -387,5 +84,4 @@ mod if_none_match;
mod if_range; mod if_range;
mod if_unmodified_since; mod if_unmodified_since;
mod last_modified; mod last_modified;
mod encoding; mod macros;
mod entity;

View File

@ -30,16 +30,16 @@
//! //!
//! To get started navigating the API docs, you may consider looking at the following pages first: //! To get started navigating the API docs, you may consider looking at the following pages first:
//! //!
//! * [App]: This struct represents an Actix Web application and is used to //! * [`App`]: This struct represents an Actix Web application and is used to
//! configure routes and other common application settings. //! configure routes and other common application settings.
//! //!
//! * [HttpServer]: This struct represents an HTTP server instance and is //! * [`HttpServer`]: This struct represents an HTTP server instance and is
//! used to instantiate and configure servers. //! used to instantiate and configure servers.
//! //!
//! * [web]: This module provides essential types for route registration as well as //! * [`web`]: This module provides essential types for route registration as well as
//! common utilities for request handlers. //! common utilities for request handlers.
//! //!
//! * [HttpRequest] and [HttpResponse]: These //! * [`HttpRequest`] and [`HttpResponse`]: These
//! structs represent HTTP requests and responses and expose methods for creating, inspecting, //! structs represent HTTP requests and responses and expose methods for creating, inspecting,
//! and otherwise utilizing them. //! and otherwise utilizing them.
//! //!
@ -55,7 +55,7 @@
//! * Static assets //! * Static assets
//! * SSL support using OpenSSL or Rustls //! * SSL support using OpenSSL or Rustls
//! * Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/)) //! * Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
//! * Includes an async [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html) //! * Includes an async [HTTP client](https://docs.rs/awc/)
//! * Runs on stable Rust 1.46+ //! * Runs on stable Rust 1.46+
//! //!
//! ## Crate Features //! ## Crate Features
@ -145,7 +145,7 @@ pub mod dev {
pub use actix_http::{Extensions, Payload, PayloadStream, RequestHead, ResponseHead}; pub use actix_http::{Extensions, Payload, PayloadStream, RequestHead, ResponseHead};
pub use actix_router::{Path, ResourceDef, ResourcePath, Url}; pub use actix_router::{Path, ResourceDef, ResourcePath, Url};
pub use actix_server::Server; pub use actix_server::Server;
pub use actix_service::{Service, Transform}; pub use actix_service::{always_ready, forward_ready, Service, Transform};
pub(crate) fn insert_slash(mut patterns: Vec<String>) -> Vec<String> { pub(crate) fn insert_slash(mut patterns: Vec<String>) -> Vec<String> {
for path in &mut patterns { for path in &mut patterns {

View File

@ -80,9 +80,7 @@ where
type Error = Error; type Error = Error;
type Future = CompatMiddlewareFuture<S::Future>; type Future = CompatMiddlewareFuture<S::Future>;
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { actix_service::forward_ready!(service);
self.service.poll_ready(cx).map_err(From::from)
}
fn call(&self, req: Req) -> Self::Future { fn call(&self, req: Req) -> Self::Future {
let fut = self.service.call(req); let fut = self.service.call(req);

View File

@ -380,7 +380,7 @@ impl Format {
results.push(match cap.get(3).unwrap().as_str() { results.push(match cap.get(3).unwrap().as_str() {
"a" => { "a" => {
if key.as_str() == "r" { if key.as_str() == "r" {
FormatText::RealIPRemoteAddr FormatText::RealIpRemoteAddr
} else { } else {
unreachable!() unreachable!()
} }
@ -434,7 +434,7 @@ enum FormatText {
Time, Time,
TimeMillis, TimeMillis,
RemoteAddr, RemoteAddr,
RealIPRemoteAddr, RealIpRemoteAddr,
UrlPath, UrlPath,
RequestHeader(HeaderName), RequestHeader(HeaderName),
ResponseHeader(HeaderName), ResponseHeader(HeaderName),
@ -554,7 +554,7 @@ impl FormatText {
}; };
*self = s; *self = s;
} }
FormatText::RealIPRemoteAddr => { FormatText::RealIpRemoteAddr => {
let s = if let Some(remote) = req.connection_info().realip_remote_addr() { let s = if let Some(remote) = req.connection_info().realip_remote_addr() {
FormatText::Str(remote.to_string()) FormatText::Str(remote.to_string())
} else { } else {

View File

@ -3,7 +3,7 @@ use std::fmt;
use std::future::Future; use std::future::Future;
use std::rc::Rc; use std::rc::Rc;
use actix_http::{Error, Extensions, Response}; use actix_http::{Error, Extensions};
use actix_router::IntoPattern; use actix_router::IntoPattern;
use actix_service::boxed::{self, BoxService, BoxServiceFactory}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{ use actix_service::{
@ -13,7 +13,6 @@ use actix_service::{
use futures_core::future::LocalBoxFuture; use futures_core::future::LocalBoxFuture;
use futures_util::future::join_all; use futures_util::future::join_all;
use crate::data::Data;
use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef}; use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef};
use crate::extract::FromRequest; use crate::extract::FromRequest;
use crate::guard::Guard; use crate::guard::Guard;
@ -21,6 +20,7 @@ use crate::handler::Handler;
use crate::responder::Responder; use crate::responder::Responder;
use crate::route::{Route, RouteService}; use crate::route::{Route, RouteService};
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::{ServiceRequest, ServiceResponse};
use crate::{data::Data, HttpResponse};
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
@ -71,7 +71,7 @@ impl Resource {
guards: Vec::new(), guards: Vec::new(),
app_data: None, app_data: None,
default: boxed::factory(fn_service(|req: ServiceRequest| async { default: boxed::factory(fn_service(|req: ServiceRequest| async {
Ok(req.into_response(Response::MethodNotAllowed().finish())) Ok(req.into_response(HttpResponse::MethodNotAllowed()))
})), })),
} }
} }

View File

@ -1,6 +1,7 @@
use std::fmt; use std::{borrow::Cow, fmt};
use actix_http::{ use actix_http::{
body::Body,
error::InternalError, error::InternalError,
http::{header::IntoHeaderPair, Error as HttpError, HeaderMap, StatusCode}, http::{header::IntoHeaderPair, Error as HttpError, HeaderMap, StatusCode},
}; };
@ -65,7 +66,7 @@ impl Responder for HttpResponse {
} }
} }
impl Responder for actix_http::Response { impl Responder for actix_http::Response<Body> {
#[inline] #[inline]
fn respond_to(self, _: &HttpRequest) -> HttpResponse { fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::from(self) HttpResponse::from(self)
@ -116,53 +117,29 @@ impl<T: Responder> Responder for (T, StatusCode) {
} }
} }
impl Responder for &'static str { macro_rules! impl_responder {
($res: ty, $ct: path) => {
impl Responder for $res {
fn respond_to(self, _: &HttpRequest) -> HttpResponse { fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok().content_type($ct).body(self)
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(self)
} }
} }
};
}
impl Responder for &'static [u8] { impl_responder!(&'static str, mime::TEXT_PLAIN_UTF_8);
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(self)
}
}
impl Responder for String { impl_responder!(String, mime::TEXT_PLAIN_UTF_8);
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(self)
}
}
impl<'a> Responder for &'a String { impl_responder!(&'_ String, mime::TEXT_PLAIN_UTF_8);
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(self)
}
}
impl Responder for Bytes { impl_responder!(Cow<'_, str>, mime::TEXT_PLAIN_UTF_8);
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(self)
}
}
impl Responder for BytesMut { impl_responder!(&'static [u8], mime::APPLICATION_OCTET_STREAM);
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok() impl_responder!(Bytes, mime::APPLICATION_OCTET_STREAM);
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(self) impl_responder!(BytesMut, mime::APPLICATION_OCTET_STREAM);
}
}
/// Allows overriding status code and headers for a responder. /// Allows overriding status code and headers for a responder.
pub struct CustomResponder<T> { pub struct CustomResponder<T> {
@ -357,6 +334,31 @@ pub(crate) mod tests {
HeaderValue::from_static("text/plain; charset=utf-8") HeaderValue::from_static("text/plain; charset=utf-8")
); );
let s = String::from("test");
let resp = Cow::Borrowed(s.as_str()).respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
let resp = Cow::<'_, str>::Owned(s).respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
let resp = Cow::Borrowed("test").respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
let resp = Bytes::from_static(b"test").respond_to(&req); let resp = Bytes::from_static(b"test").respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test"); assert_eq!(resp.body().bin_ref(), b"test");

View File

@ -1,16 +1,15 @@
use std::{ use std::{
cell::{Ref, RefMut}, cell::{Ref, RefMut},
convert::TryInto, convert::TryInto,
fmt,
future::Future, future::Future,
pin::Pin, pin::Pin,
task::{Context, Poll}, task::{Context, Poll},
}; };
use actix_http::{ use actix_http::{
body::{Body, BodyStream, MessageBody, ResponseBody}, body::{Body, BodyStream},
http::{ http::{
header::{self, HeaderMap, HeaderName, IntoHeaderPair, IntoHeaderValue}, header::{self, HeaderName, IntoHeaderPair, IntoHeaderValue},
ConnectionType, Error as HttpError, StatusCode, ConnectionType, Error as HttpError, StatusCode,
}, },
Extensions, Response, ResponseHead, Extensions, Response, ResponseHead,
@ -24,289 +23,16 @@ use actix_http::http::header::HeaderValue;
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
use cookie::{Cookie, CookieJar}; use cookie::{Cookie, CookieJar};
use crate::error::{Error, JsonPayloadError}; use crate::{
error::{Error, JsonPayloadError},
/// An HTTP Response HttpResponse,
pub struct HttpResponse<B = Body> { };
res: Response<B>,
error: Option<Error>,
}
impl HttpResponse<Body> {
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> HttpResponseBuilder {
HttpResponseBuilder::new(status)
}
/// Create HTTP response builder
#[inline]
pub fn build_from<T: Into<HttpResponseBuilder>>(source: T) -> HttpResponseBuilder {
source.into()
}
/// Create a response.
#[inline]
pub fn new(status: StatusCode) -> Self {
Self {
res: Response::new(status),
error: None,
}
}
/// Create an error response.
#[inline]
pub fn from_error(error: Error) -> Self {
let res = error.as_response_error().error_response();
Self {
res,
error: Some(error),
}
}
/// Convert response to response with body
pub fn into_body<B>(self) -> HttpResponse<B> {
HttpResponse {
res: self.res.into_body(),
error: self.error,
}
}
}
impl<B> HttpResponse<B> {
/// Constructs a response with body
#[inline]
pub fn with_body(status: StatusCode, body: B) -> Self {
Self {
res: Response::with_body(status, body),
error: None,
}
}
/// Returns a reference to response head.
#[inline]
pub fn head(&self) -> &ResponseHead {
self.res.head()
}
/// Returns a mutable reference to response head.
#[inline]
pub fn head_mut(&mut self) -> &mut ResponseHead {
self.res.head_mut()
}
/// The source `error` for this response
#[inline]
pub fn error(&self) -> Option<&Error> {
self.error.as_ref()
}
/// Get the response status code
#[inline]
pub fn status(&self) -> StatusCode {
self.res.status()
}
/// Set the `StatusCode` for this response
#[inline]
pub fn status_mut(&mut self) -> &mut StatusCode {
self.res.status_mut()
}
/// Get the headers from the response
#[inline]
pub fn headers(&self) -> &HeaderMap {
self.res.headers()
}
/// Get a mutable reference to the headers
#[inline]
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.res.headers_mut()
}
/// Get an iterator for the cookies set by this response.
#[cfg(feature = "cookies")]
pub fn cookies(&self) -> CookieIter<'_> {
CookieIter {
iter: self.headers().get_all(header::SET_COOKIE),
}
}
/// Add a cookie to this response
#[cfg(feature = "cookies")]
pub fn add_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
HeaderValue::from_str(&cookie.to_string())
.map(|c| {
self.headers_mut().append(header::SET_COOKIE, c);
})
.map_err(|e| e.into())
}
/// Remove all cookies with the given name from this response. Returns
/// the number of cookies removed.
#[cfg(feature = "cookies")]
pub fn del_cookie(&mut self, name: &str) -> usize {
let headers = self.headers_mut();
let vals: Vec<HeaderValue> = headers
.get_all(header::SET_COOKIE)
.map(|v| v.to_owned())
.collect();
headers.remove(header::SET_COOKIE);
let mut count: usize = 0;
for v in vals {
if let Ok(s) = v.to_str() {
if let Ok(c) = Cookie::parse_encoded(s) {
if c.name() == name {
count += 1;
continue;
}
}
}
// put set-cookie header head back if it does not validate
headers.append(header::SET_COOKIE, v);
}
count
}
/// Connection upgrade status
#[inline]
pub fn upgrade(&self) -> bool {
self.res.upgrade()
}
/// Keep-alive status for this connection
pub fn keep_alive(&self) -> bool {
self.res.keep_alive()
}
/// Responses extensions
#[inline]
pub fn extensions(&self) -> Ref<'_, Extensions> {
self.res.extensions()
}
/// Mutable reference to a the response's extensions
#[inline]
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
self.res.extensions_mut()
}
/// Get body of this response
#[inline]
pub fn body(&self) -> &ResponseBody<B> {
self.res.body()
}
/// Set a body
pub fn set_body<B2>(self, body: B2) -> HttpResponse<B2> {
HttpResponse {
res: self.res.set_body(body),
error: None,
// error: self.error, ??
}
}
/// Split response and body
pub fn into_parts(self) -> (HttpResponse<()>, ResponseBody<B>) {
let (head, body) = self.res.into_parts();
(
HttpResponse {
res: head,
error: None,
},
body,
)
}
/// Drop request's body
pub fn drop_body(self) -> HttpResponse<()> {
HttpResponse {
res: self.res.drop_body(),
error: None,
}
}
/// Set a body and return previous body value
pub fn map_body<F, B2>(self, f: F) -> HttpResponse<B2>
where
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
{
HttpResponse {
res: self.res.map_body(f),
error: self.error,
}
}
/// Extract response body
pub fn take_body(&mut self) -> ResponseBody<B> {
self.res.take_body()
}
}
impl<B: MessageBody> fmt::Debug for HttpResponse<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpResponse")
.field("error", &self.error)
.field("res", &self.res)
.finish()
}
}
impl<B> From<Response<B>> for HttpResponse<B> {
fn from(res: Response<B>) -> Self {
HttpResponse { res, error: None }
}
}
impl From<Error> for HttpResponse {
fn from(err: Error) -> Self {
HttpResponse::from_error(err)
}
}
impl<B> From<HttpResponse<B>> for Response<B> {
fn from(res: HttpResponse<B>) -> Self {
// this impl will always be called as part of dispatcher
// TODO: expose cause somewhere?
// if let Some(err) = res.error {
// eprintln!("impl<B> From<HttpResponse<B>> for Response<B> let Some(err)");
// return Response::from_error(err).into_body();
// }
res.res
}
}
impl Future for HttpResponse {
type Output = Result<Response, Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.error.take() {
eprintln!("httpresponse future error");
return Poll::Ready(Ok(Response::from_error(err).into_body()));
}
let res = &mut self.res;
actix_rt::pin!(res);
res.poll(cx)
}
}
/// An HTTP response builder. /// An HTTP response builder.
/// ///
/// This type can be used to construct an instance of `Response` through a builder-like pattern. /// This type can be used to construct an instance of `Response` through a builder-like pattern.
pub struct HttpResponseBuilder { pub struct HttpResponseBuilder {
head: Option<ResponseHead>, res: Option<Response<Body>>,
err: Option<HttpError>, err: Option<HttpError>,
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
cookies: Option<CookieJar>, cookies: Option<CookieJar>,
@ -317,7 +43,7 @@ impl HttpResponseBuilder {
/// Create response builder /// Create response builder
pub fn new(status: StatusCode) -> Self { pub fn new(status: StatusCode) -> Self {
Self { Self {
head: Some(ResponseHead::new(status)), res: Some(Response::new(status)),
err: None, err: None,
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
cookies: None, cookies: None,
@ -565,15 +291,19 @@ impl HttpResponseBuilder {
/// Responses extensions /// Responses extensions
#[inline] #[inline]
pub fn extensions(&self) -> Ref<'_, Extensions> { pub fn extensions(&self) -> Ref<'_, Extensions> {
let head = self.head.as_ref().expect("cannot reuse response builder"); self.res
head.extensions() .as_ref()
.expect("cannot reuse response builder")
.extensions()
} }
/// Mutable reference to a the response's extensions /// Mutable reference to a the response's extensions
#[inline] #[inline]
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> { pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
let head = self.head.as_ref().expect("cannot reuse response builder"); self.res
head.extensions_mut() .as_mut()
.expect("cannot reuse response builder")
.extensions_mut()
} }
/// Set a body and generate `Response`. /// Set a body and generate `Response`.
@ -592,12 +322,14 @@ impl HttpResponseBuilder {
return HttpResponse::from_error(Error::from(err)).into_body(); return HttpResponse::from_error(Error::from(err)).into_body();
} }
// allow unused mut when cookies feature is disabled let res = self
#[allow(unused_mut)] .res
let mut head = self.head.take().expect("cannot reuse response builder"); .take()
.expect("cannot reuse response builder")
.set_body(body);
let mut res = HttpResponse::with_body(StatusCode::OK, body); #[allow(unused_mut)]
*res.head_mut() = head; let mut res = HttpResponse::from(res);
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
if let Some(ref jar) = self.cookies { if let Some(ref jar) = self.cookies {
@ -657,7 +389,7 @@ impl HttpResponseBuilder {
/// This method construct new `HttpResponseBuilder` /// This method construct new `HttpResponseBuilder`
pub fn take(&mut self) -> Self { pub fn take(&mut self) -> Self {
Self { Self {
head: self.head.take(), res: self.res.take(),
err: self.err.take(), err: self.err.take(),
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
cookies: self.cookies.take(), cookies: self.cookies.take(),
@ -670,7 +402,7 @@ impl HttpResponseBuilder {
return None; return None;
} }
self.head.as_mut() self.res.as_mut().map(|res| res.head_mut())
} }
} }
@ -680,7 +412,7 @@ impl From<HttpResponseBuilder> for HttpResponse {
} }
} }
impl From<HttpResponseBuilder> for Response { impl From<HttpResponseBuilder> for Response<Body> {
fn from(mut builder: HttpResponseBuilder) -> Self { fn from(mut builder: HttpResponseBuilder) -> Self {
builder.finish().into() builder.finish().into()
} }
@ -695,146 +427,18 @@ impl Future for HttpResponseBuilder {
} }
} }
#[cfg(feature = "cookies")] #[cfg(test)]
pub struct CookieIter<'a> { mod tests {
iter: header::GetAll<'a>, use actix_http::body;
}
#[cfg(feature = "cookies")] use super::*;
impl<'a> Iterator for CookieIter<'a> { use crate::{
type Item = Cookie<'a>; dev::Body,
http::{
#[inline] header::{self, HeaderValue, CONTENT_TYPE},
fn next(&mut self) -> Option<Cookie<'a>> { StatusCode,
for v in self.iter.by_ref() { },
if let Ok(c) = Cookie::parse_encoded(v.to_str().ok()?) {
return Some(c);
}
}
None
}
}
mod http_codes {
//! Status code based HTTP response builders.
use actix_http::http::StatusCode;
use super::{HttpResponse, HttpResponseBuilder};
macro_rules! static_resp {
($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)]
pub fn $name() -> HttpResponseBuilder {
HttpResponseBuilder::new($status)
}
}; };
}
impl HttpResponse {
static_resp!(Continue, StatusCode::CONTINUE);
static_resp!(SwitchingProtocols, StatusCode::SWITCHING_PROTOCOLS);
static_resp!(Processing, StatusCode::PROCESSING);
static_resp!(Ok, StatusCode::OK);
static_resp!(Created, StatusCode::CREATED);
static_resp!(Accepted, StatusCode::ACCEPTED);
static_resp!(
NonAuthoritativeInformation,
StatusCode::NON_AUTHORITATIVE_INFORMATION
);
static_resp!(NoContent, StatusCode::NO_CONTENT);
static_resp!(ResetContent, StatusCode::RESET_CONTENT);
static_resp!(PartialContent, StatusCode::PARTIAL_CONTENT);
static_resp!(MultiStatus, StatusCode::MULTI_STATUS);
static_resp!(AlreadyReported, StatusCode::ALREADY_REPORTED);
static_resp!(MultipleChoices, StatusCode::MULTIPLE_CHOICES);
static_resp!(MovedPermanently, StatusCode::MOVED_PERMANENTLY);
static_resp!(Found, StatusCode::FOUND);
static_resp!(SeeOther, StatusCode::SEE_OTHER);
static_resp!(NotModified, StatusCode::NOT_MODIFIED);
static_resp!(UseProxy, StatusCode::USE_PROXY);
static_resp!(TemporaryRedirect, StatusCode::TEMPORARY_REDIRECT);
static_resp!(PermanentRedirect, StatusCode::PERMANENT_REDIRECT);
static_resp!(BadRequest, StatusCode::BAD_REQUEST);
static_resp!(NotFound, StatusCode::NOT_FOUND);
static_resp!(Unauthorized, StatusCode::UNAUTHORIZED);
static_resp!(PaymentRequired, StatusCode::PAYMENT_REQUIRED);
static_resp!(Forbidden, StatusCode::FORBIDDEN);
static_resp!(MethodNotAllowed, StatusCode::METHOD_NOT_ALLOWED);
static_resp!(NotAcceptable, StatusCode::NOT_ACCEPTABLE);
static_resp!(
ProxyAuthenticationRequired,
StatusCode::PROXY_AUTHENTICATION_REQUIRED
);
static_resp!(RequestTimeout, StatusCode::REQUEST_TIMEOUT);
static_resp!(Conflict, StatusCode::CONFLICT);
static_resp!(Gone, StatusCode::GONE);
static_resp!(LengthRequired, StatusCode::LENGTH_REQUIRED);
static_resp!(PreconditionFailed, StatusCode::PRECONDITION_FAILED);
static_resp!(PreconditionRequired, StatusCode::PRECONDITION_REQUIRED);
static_resp!(PayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE);
static_resp!(UriTooLong, StatusCode::URI_TOO_LONG);
static_resp!(UnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE);
static_resp!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
static_resp!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
static_resp!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
static_resp!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
static_resp!(
RequestHeaderFieldsTooLarge,
StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE
);
static_resp!(
UnavailableForLegalReasons,
StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS
);
static_resp!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
static_resp!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
static_resp!(BadGateway, StatusCode::BAD_GATEWAY);
static_resp!(ServiceUnavailable, StatusCode::SERVICE_UNAVAILABLE);
static_resp!(GatewayTimeout, StatusCode::GATEWAY_TIMEOUT);
static_resp!(VersionNotSupported, StatusCode::HTTP_VERSION_NOT_SUPPORTED);
static_resp!(VariantAlsoNegotiates, StatusCode::VARIANT_ALSO_NEGOTIATES);
static_resp!(InsufficientStorage, StatusCode::INSUFFICIENT_STORAGE);
static_resp!(LoopDetected, StatusCode::LOOP_DETECTED);
}
#[cfg(test)]
mod tests {
use crate::dev::Body;
use crate::http::StatusCode;
use crate::HttpResponse;
#[test]
fn test_build() {
let resp = HttpResponse::Ok().body(Body::Empty);
assert_eq!(resp.status(), StatusCode::OK);
}
}
}
#[cfg(test)]
mod tests {
use bytes::{Bytes, BytesMut};
use super::{HttpResponse, HttpResponseBuilder};
use crate::dev::{Body, MessageBody, ResponseBody};
use crate::http::header::{self, HeaderValue, CONTENT_TYPE, COOKIE};
use crate::http::StatusCode;
#[test]
fn test_debug() {
let resp = HttpResponse::Ok()
.append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
.append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
.finish();
let dbg = format!("{:?}", resp);
assert!(dbg.contains("HttpResponse"));
}
#[test] #[test]
fn test_basic_builder() { fn test_basic_builder() {
@ -872,26 +476,13 @@ mod tests {
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain") assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
} }
pub async fn read_body<B>(mut body: ResponseBody<B>) -> Bytes
where
B: MessageBody + Unpin,
{
use futures_util::StreamExt as _;
let mut bytes = BytesMut::new();
while let Some(item) = body.next().await {
bytes.extend_from_slice(&item.unwrap());
}
bytes.freeze()
}
#[actix_rt::test] #[actix_rt::test]
async fn test_json() { async fn test_json() {
let mut resp = HttpResponse::Ok().json(vec!["v1", "v2", "v3"]); let mut resp = HttpResponse::Ok().json(vec!["v1", "v2", "v3"]);
let ct = resp.headers().get(CONTENT_TYPE).unwrap(); let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_eq!( assert_eq!(
read_body(resp.take_body()).await.as_ref(), body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"["v1","v2","v3"]"# br#"["v1","v2","v3"]"#
); );
@ -899,7 +490,7 @@ mod tests {
let ct = resp.headers().get(CONTENT_TYPE).unwrap(); let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json")); assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_eq!( assert_eq!(
read_body(resp.take_body()).await.as_ref(), body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"["v1","v2","v3"]"# br#"["v1","v2","v3"]"#
); );
@ -910,7 +501,7 @@ mod tests {
let ct = resp.headers().get(CONTENT_TYPE).unwrap(); let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("text/json")); assert_eq!(ct, HeaderValue::from_static("text/json"));
assert_eq!( assert_eq!(
read_body(resp.take_body()).await.as_ref(), body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"["v1","v2","v3"]"# br#"["v1","v2","v3"]"#
); );
} }
@ -922,7 +513,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
read_body(resp.take_body()).await.as_ref(), body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"{"test-key":"test-value"}"# br#"{"test-key":"test-value"}"#
); );
} }

View File

@ -1,21 +1,19 @@
//! Status code based HTTP response builders. //! Status code based HTTP response builders.
#![allow(non_upper_case_globals)] use actix_http::http::StatusCode;
use http::StatusCode; use crate::{HttpResponse, HttpResponseBuilder};
use crate::response::{Response, ResponseBuilder};
macro_rules! static_resp { macro_rules! static_resp {
($name:ident, $status:expr) => { ($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)] #[allow(non_snake_case, missing_docs)]
pub fn $name() -> ResponseBuilder { pub fn $name() -> HttpResponseBuilder {
ResponseBuilder::new($status) HttpResponseBuilder::new($status)
} }
}; };
} }
impl Response { impl HttpResponse {
static_resp!(Continue, StatusCode::CONTINUE); static_resp!(Continue, StatusCode::CONTINUE);
static_resp!(SwitchingProtocols, StatusCode::SWITCHING_PROTOCOLS); static_resp!(SwitchingProtocols, StatusCode::SWITCHING_PROTOCOLS);
static_resp!(Processing, StatusCode::PROCESSING); static_resp!(Processing, StatusCode::PROCESSING);
@ -89,13 +87,13 @@ impl Response {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::body::Body; use crate::dev::Body;
use crate::response::Response; use crate::http::StatusCode;
use http::StatusCode; use crate::HttpResponse;
#[test] #[test]
fn test_build() { fn test_build() {
let resp = Response::Ok().body(Body::Empty); let resp = HttpResponse::Ok().body(Body::Empty);
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
} }

10
src/response/mod.rs Normal file
View File

@ -0,0 +1,10 @@
mod builder;
mod http_codes;
#[allow(clippy::module_inception)]
mod response;
pub use self::builder::HttpResponseBuilder;
pub use self::response::HttpResponse;
#[cfg(feature = "cookies")]
pub use self::response::CookieIter;

330
src/response/response.rs Normal file
View File

@ -0,0 +1,330 @@
use std::{
cell::{Ref, RefMut},
fmt,
future::Future,
mem,
pin::Pin,
task::{Context, Poll},
};
use actix_http::{
body::{Body, MessageBody, ResponseBody},
http::{header::HeaderMap, StatusCode},
Extensions, Response, ResponseHead,
};
#[cfg(feature = "cookies")]
use {
actix_http::http::{
header::{self, HeaderValue},
Error as HttpError,
},
cookie::Cookie,
};
use crate::{error::Error, HttpResponseBuilder};
/// An HTTP Response
pub struct HttpResponse<B = Body> {
res: Response<B>,
error: Option<Error>,
}
impl HttpResponse<Body> {
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> HttpResponseBuilder {
HttpResponseBuilder::new(status)
}
/// Create a response.
#[inline]
pub fn new(status: StatusCode) -> Self {
Self {
res: Response::new(status),
error: None,
}
}
/// Create an error response.
#[inline]
pub fn from_error(error: Error) -> Self {
let res = error.as_response_error().error_response();
Self {
res,
error: Some(error),
}
}
/// Convert response to response with body
pub fn into_body<B>(self) -> HttpResponse<B> {
HttpResponse {
res: self.res.into_body(),
error: self.error,
}
}
}
impl<B> HttpResponse<B> {
/// Constructs a response with body
#[inline]
pub fn with_body(status: StatusCode, body: B) -> Self {
Self {
res: Response::with_body(status, body),
error: None,
}
}
/// Returns a reference to response head.
#[inline]
pub fn head(&self) -> &ResponseHead {
self.res.head()
}
/// Returns a mutable reference to response head.
#[inline]
pub fn head_mut(&mut self) -> &mut ResponseHead {
self.res.head_mut()
}
/// The source `error` for this response
#[inline]
pub fn error(&self) -> Option<&Error> {
self.error.as_ref()
}
/// Get the response status code
#[inline]
pub fn status(&self) -> StatusCode {
self.res.status()
}
/// Set the `StatusCode` for this response
#[inline]
pub fn status_mut(&mut self) -> &mut StatusCode {
self.res.status_mut()
}
/// Get the headers from the response
#[inline]
pub fn headers(&self) -> &HeaderMap {
self.res.headers()
}
/// Get a mutable reference to the headers
#[inline]
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.res.headers_mut()
}
/// Get an iterator for the cookies set by this response.
#[cfg(feature = "cookies")]
pub fn cookies(&self) -> CookieIter<'_> {
CookieIter {
iter: self.headers().get_all(header::SET_COOKIE),
}
}
/// Add a cookie to this response
#[cfg(feature = "cookies")]
pub fn add_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
HeaderValue::from_str(&cookie.to_string())
.map(|c| {
self.headers_mut().append(header::SET_COOKIE, c);
})
.map_err(|e| e.into())
}
/// Remove all cookies with the given name from this response. Returns
/// the number of cookies removed.
#[cfg(feature = "cookies")]
pub fn del_cookie(&mut self, name: &str) -> usize {
let headers = self.headers_mut();
let vals: Vec<HeaderValue> = headers
.get_all(header::SET_COOKIE)
.map(|v| v.to_owned())
.collect();
headers.remove(header::SET_COOKIE);
let mut count: usize = 0;
for v in vals {
if let Ok(s) = v.to_str() {
if let Ok(c) = Cookie::parse_encoded(s) {
if c.name() == name {
count += 1;
continue;
}
}
}
// put set-cookie header head back if it does not validate
headers.append(header::SET_COOKIE, v);
}
count
}
/// Connection upgrade status
#[inline]
pub fn upgrade(&self) -> bool {
self.res.upgrade()
}
/// Keep-alive status for this connection
pub fn keep_alive(&self) -> bool {
self.res.keep_alive()
}
/// Responses extensions
#[inline]
pub fn extensions(&self) -> Ref<'_, Extensions> {
self.res.extensions()
}
/// Mutable reference to a the response's extensions
#[inline]
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
self.res.extensions_mut()
}
/// Get body of this response
#[inline]
pub fn body(&self) -> &ResponseBody<B> {
self.res.body()
}
/// Set a body
pub fn set_body<B2>(self, body: B2) -> HttpResponse<B2> {
HttpResponse {
res: self.res.set_body(body),
error: None,
// error: self.error, ??
}
}
/// Split response and body
pub fn into_parts(self) -> (HttpResponse<()>, ResponseBody<B>) {
let (head, body) = self.res.into_parts();
(
HttpResponse {
res: head,
error: None,
},
body,
)
}
/// Drop request's body
pub fn drop_body(self) -> HttpResponse<()> {
HttpResponse {
res: self.res.drop_body(),
error: None,
}
}
/// Set a body and return previous body value
pub fn map_body<F, B2>(self, f: F) -> HttpResponse<B2>
where
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
{
HttpResponse {
res: self.res.map_body(f),
error: self.error,
}
}
/// Extract response body
pub fn take_body(&mut self) -> ResponseBody<B> {
self.res.take_body()
}
}
impl<B: MessageBody> fmt::Debug for HttpResponse<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpResponse")
.field("error", &self.error)
.field("res", &self.res)
.finish()
}
}
impl<B> From<Response<B>> for HttpResponse<B> {
fn from(res: Response<B>) -> Self {
HttpResponse { res, error: None }
}
}
impl From<Error> for HttpResponse {
fn from(err: Error) -> Self {
HttpResponse::from_error(err)
}
}
impl<B> From<HttpResponse<B>> for Response<B> {
fn from(res: HttpResponse<B>) -> Self {
// this impl will always be called as part of dispatcher
// TODO: expose cause somewhere?
// if let Some(err) = res.error {
// eprintln!("impl<B> From<HttpResponse<B>> for Response<B> let Some(err)");
// return Response::from_error(err).into_body();
// }
res.res
}
}
impl Future for HttpResponse {
type Output = Result<Response<Body>, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.error.take() {
return Poll::Ready(Ok(Response::from_error(err).into_body()));
}
Poll::Ready(Ok(mem::replace(
&mut self.res,
Response::new(StatusCode::default()),
)))
}
}
#[cfg(feature = "cookies")]
pub struct CookieIter<'a> {
iter: header::GetAll<'a>,
}
#[cfg(feature = "cookies")]
impl<'a> Iterator for CookieIter<'a> {
type Item = Cookie<'a>;
#[inline]
fn next(&mut self) -> Option<Cookie<'a>> {
for v in self.iter.by_ref() {
if let Ok(c) = Cookie::parse_encoded(v.to_str().ok()?) {
return Some(c);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::header::{HeaderValue, COOKIE};
#[test]
fn test_debug() {
let resp = HttpResponse::Ok()
.append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
.append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
.finish();
let dbg = format!("{:?}", resp);
assert!(dbg.contains("HttpResponse"));
}
}

View File

@ -489,7 +489,7 @@ where
pub fn listen_uds(mut self, lst: std::os::unix::net::UnixListener) -> io::Result<Self> { pub fn listen_uds(mut self, lst: std::os::unix::net::UnixListener) -> io::Result<Self> {
use actix_http::Protocol; use actix_http::Protocol;
use actix_rt::net::UnixStream; use actix_rt::net::UnixStream;
use actix_service::pipeline_factory; use actix_service::{fn_service, ServiceFactoryExt as _};
let cfg = self.config.clone(); let cfg = self.config.clone();
let factory = self.factory.clone(); let factory = self.factory.clone();
@ -511,16 +511,13 @@ where
socket_addr, socket_addr,
); );
pipeline_factory(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }) fn_service(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }).and_then({
.and_then({
let svc = HttpService::build() let svc = HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout); .client_timeout(c.client_timeout);
let svc = if let Some(handler) = on_connect_fn.clone() { let svc = if let Some(handler) = on_connect_fn.clone() {
svc.on_connect_ext(move |io: &_, ext: _| { svc.on_connect_ext(move |io: &_, ext: _| (&*handler)(io as &dyn Any, ext))
(&*handler)(io as &dyn Any, ext)
})
} else { } else {
svc svc
}; };
@ -539,7 +536,7 @@ where
{ {
use actix_http::Protocol; use actix_http::Protocol;
use actix_rt::net::UnixStream; use actix_rt::net::UnixStream;
use actix_service::pipeline_factory; use actix_service::{fn_service, ServiceFactoryExt as _};
let cfg = self.config.clone(); let cfg = self.config.clone();
let factory = self.factory.clone(); let factory = self.factory.clone();
@ -560,8 +557,7 @@ where
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)), c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
socket_addr, socket_addr,
); );
pipeline_factory(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }) fn_service(|io: UnixStream| async { Ok((io, Protocol::Http1, None)) }).and_then(
.and_then(
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)

View File

@ -9,6 +9,8 @@ use actix_http::{
}; };
use actix_router::{IntoPattern, Path, Resource, ResourceDef, Url}; use actix_router::{IntoPattern, Path, Resource, ResourceDef, Url};
use actix_service::{IntoServiceFactory, ServiceFactory}; use actix_service::{IntoServiceFactory, ServiceFactory};
#[cfg(feature = "cookies")]
use cookie::{Cookie, ParseError as CookieParseError};
use crate::dev::insert_slash; use crate::dev::insert_slash;
use crate::guard::Guard; use crate::guard::Guard;
@ -244,6 +246,17 @@ impl ServiceRequest {
None None
} }
#[cfg(feature = "cookies")]
pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
self.req.cookies()
}
/// Return request cookie.
#[cfg(feature = "cookies")]
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
self.req.cookie(name)
}
/// Set request payload. /// Set request payload.
pub fn set_payload(&mut self, payload: Payload) { pub fn set_payload(&mut self, payload: Payload) {
self.payload = payload; self.payload = payload;