Merge branch 'master' into bump_json_limits

This commit is contained in:
Rob Ede 2021-04-22 11:22:37 +01:00 committed by GitHub
commit ae53fbf6b9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
62 changed files with 988 additions and 760 deletions

View File

@ -1,11 +1,15 @@
# Changes
## Unreleased - 2021-xx-xx
## 4.0.0-beta.6 - 2021-04-17
### Added
* `HttpResponse` and `HttpResponseBuilder` structs. [#2065]
### Changed
* Most error types are now marked `#[non_exhaustive]`. [#2148]
* Methods on `ContentDisposition` that took `T: AsRef<str>` now take `impl AsRef<str>`.
[#2065]: https://github.com/actix/actix-web/pull/2065
[#2148]: https://github.com/actix/actix-web/pull/2148

View File

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

View File

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

View File

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

View File

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

View File

@ -199,6 +199,18 @@ impl Files {
}
/// 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
where
F: IntoServiceFactory<U, ServiceRequest>,

View File

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

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

View File

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

View File

@ -2,6 +2,22 @@
## 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]

View File

@ -1,6 +1,6 @@
[package]
name = "actix-http"
version = "3.0.0-beta.5"
version = "3.0.0-beta.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "HTTP primitives for the Actix ecosystem"
readme = "README.md"
@ -38,9 +38,9 @@ compress = ["flate2", "brotli2"]
trust-dns = ["trust-dns-resolver"]
[dependencies]
actix-service = "2.0.0-beta.4"
actix-codec = "0.4.0-beta.1"
actix-utils = "3.0.0-beta.4"
actix-service = "2.0.0"
actix-codec = "0.4.0"
actix-utils = "3.0.0"
actix-rt = "2.2"
actix-tls = { version = "3.0.0-beta.5", features = ["accept", "connect"] }

View File

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

View File

@ -1,4 +1,5 @@
use std::{
borrow::Cow,
fmt, mem,
pin::Pin,
task::{Context, Poll},
@ -118,12 +119,23 @@ impl From<String> for Body {
}
}
impl<'a> From<&'a String> for Body {
fn from(s: &'a String) -> Body {
impl From<&'_ String> for Body {
fn from(s: &String) -> Body {
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 {
fn from(s: Bytes) -> Body {
Body::Bytes(s)

View File

@ -10,18 +10,17 @@ use std::{
use bytes::BytesMut;
use derive_more::{Display, Error, From};
use http::uri::InvalidUri;
use http::{header, Error as HttpError, StatusCode};
use http::{header, uri::InvalidUri, StatusCode};
use serde::de::value::Error as DeError;
use crate::{body::Body, helpers::Writer, Response, ResponseBuilder};
/// A specialized [`std::result::Result`]
/// for actix web operations
pub use http::Error as HttpError;
/// A specialized [`std::result::Result`] for Actix Web operations.
///
/// This typedef is generally used to avoid writing out
/// `actix_http::error::Error` directly and is otherwise a direct mapping to
/// `Result`.
/// This typedef is generally used to avoid writing out `actix_http::error::Error` directly and is
/// otherwise a direct mapping to `Result`.
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// General purpose actix web error.
@ -50,18 +49,20 @@ impl Error {
}
}
/// Error that can be converted to `Response`
/// Errors that can generate responses.
pub trait ResponseError: fmt::Debug + fmt::Display {
/// Response's status code
/// Returns appropriate status code for error.
///
/// Internal server error is generated by default.
/// A 500 Internal Server Error is used by default. If [error_response](Self::error_response) is
/// also implemented and does not call `self.status_code()`, then this will not be used.
fn status_code(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
/// Create response for error
/// Creates full response for error.
///
/// Internal server error is generated by default.
/// By default, the generated response uses a 500 Internal Server Error status code, a
/// `Content-Type` of `text/plain`, and the body is set to `Self`'s `Display` impl.
fn error_response(&self) -> Response<Body> {
let mut resp = Response::new(self.status_code());
let mut buf = BytesMut::new();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,7 +35,7 @@ mod config;
#[cfg(feature = "compress")]
pub mod encoding;
mod extensions;
mod header;
pub mod header;
mod helpers;
mod http_message;
mod message;
@ -56,7 +56,9 @@ pub use self::builder::HttpServiceBuilder;
pub use self::config::{KeepAlive, ServiceConfig};
pub use self::error::{Error, ResponseError, Result};
pub use self::extensions::Extensions;
pub use self::header::ContentEncoding;
pub use self::http_message::HttpMessage;
pub use self::message::ConnectionType;
pub use self::message::{Message, RequestHead, RequestHeadType, ResponseHead};
pub use self::payload::{Payload, PayloadStream};
pub use self::request::Request;
@ -64,6 +66,10 @@ pub use self::response::Response;
pub use self::response_builder::ResponseBuilder;
pub use self::service::HttpService;
pub use ::http::{uri, uri::Uri};
pub use ::http::{Method, StatusCode, Version};
// TODO: deprecate this mish-mash of random items
pub mod http {
//! Various HTTP related types.

View File

@ -1,4 +1,5 @@
#[macro_export]
#[doc(hidden)]
macro_rules! downcast_get_type_id {
() => {
/// A helper method to get the type ID of the type
@ -25,6 +26,7 @@ macro_rules! downcast_get_type_id {
}
//Generate implementation for dyn $name
#[doc(hidden)]
#[macro_export]
macro_rules! downcast {
($name:ident) => {

View File

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

View File

@ -14,12 +14,10 @@ use futures_core::Stream;
use crate::{
body::{Body, BodyStream, ResponseBody},
error::Error,
extensions::Extensions,
header::{IntoHeaderPair, IntoHeaderValue},
http::{header, Error as HttpError, StatusCode},
error::{Error, HttpError},
header::{self, IntoHeaderPair, IntoHeaderValue},
message::{BoxedResponseHead, ConnectionType, ResponseHead},
Response,
Extensions, Response, StatusCode,
};
/// An HTTP response builder.
@ -291,7 +289,7 @@ impl ResponseBuilder {
return None;
}
self.head.as_mut().map(|r| &mut **r)
self.head.as_deref_mut()
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
use super::{HttpDate, DATE};
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)
///
/// The `Date` header field represents the date and time at which the
@ -32,7 +32,7 @@ crate::header! {
(Date, DATE) => [HttpDate]
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};
crate::header! {
crate::__define_common_header! {
/// `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
@ -50,50 +50,50 @@ crate::header! {
test_etag {
// From the RFC
test_header!(test1,
crate::__common_header_test!(test1,
vec![b"\"xyzzy\""],
Some(ETag(EntityTag::new(false, "xyzzy".to_owned()))));
test_header!(test2,
crate::__common_header_test!(test2,
vec![b"W/\"xyzzy\""],
Some(ETag(EntityTag::new(true, "xyzzy".to_owned()))));
test_header!(test3,
crate::__common_header_test!(test3,
vec![b"\"\""],
Some(ETag(EntityTag::new(false, "".to_owned()))));
// Own tests
test_header!(test4,
crate::__common_header_test!(test4,
vec![b"\"foobar\""],
Some(ETag(EntityTag::new(false, "foobar".to_owned()))));
test_header!(test5,
crate::__common_header_test!(test5,
vec![b"\"\""],
Some(ETag(EntityTag::new(false, "".to_owned()))));
test_header!(test6,
crate::__common_header_test!(test6,
vec![b"W/\"weak-etag\""],
Some(ETag(EntityTag::new(true, "weak-etag".to_owned()))));
test_header!(test7,
crate::__common_header_test!(test7,
vec![b"W/\"\x65\x62\""],
Some(ETag(EntityTag::new(true, "\u{0065}\u{0062}".to_owned()))));
test_header!(test8,
crate::__common_header_test!(test8,
vec![b"W/\"\""],
Some(ETag(EntityTag::new(true, "".to_owned()))));
test_header!(test9,
crate::__common_header_test!(test9,
vec![b"no-dquotes"],
None::<ETag>);
test_header!(test10,
crate::__common_header_test!(test10,
vec![b"w/\"the-first-w-is-case-sensitive\""],
None::<ETag>);
test_header!(test11,
crate::__common_header_test!(test11,
vec![b""],
None::<ETag>);
test_header!(test12,
crate::__common_header_test!(test12,
vec![b"\"unmatched-dquotes1"],
None::<ETag>);
test_header!(test13,
crate::__common_header_test!(test13,
vec![b"unmatched-dquotes2\""],
None::<ETag>);
test_header!(test14,
crate::__common_header_test!(test14,
vec![b"matched-\"dquotes\""],
None::<ETag>);
test_header!(test15,
crate::__common_header_test!(test15,
vec![b"\""],
None::<ETag>);
}

View File

@ -1,6 +1,6 @@
use super::{HttpDate, EXPIRES};
crate::header! {
crate::__define_common_header! {
/// `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
@ -36,6 +36,6 @@ crate::header! {
test_expires {
// 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};
crate::header! {
crate::__define_common_header! {
/// `If-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1)
///
@ -53,18 +53,18 @@ crate::header! {
(IfMatch, IF_MATCH) => {Any / (EntityTag)+}
test_if_match {
test_header!(
crate::__common_header_test!(
test1,
vec![b"\"xyzzy\""],
Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned())])));
test_header!(
crate::__common_header_test!(
test2,
vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""],
Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned()),
EntityTag::new(false, "r2d2xxxx".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};
crate::header! {
crate::__define_common_header! {
/// `If-Modified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.3)
///
@ -36,6 +36,6 @@ crate::header! {
test_if_modified_since {
// 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};
crate::header! {
crate::__define_common_header! {
/// `If-None-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.2)
///
@ -55,11 +55,11 @@ crate::header! {
(IfNoneMatch, IF_NONE_MATCH) => {Any / (EntityTag)+}
test_if_none_match {
test_header!(test1, vec![b"\"xyzzy\""]);
test_header!(test2, vec![b"W/\"xyzzy\""]);
test_header!(test3, vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]);
test_header!(test4, vec![b"W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\""]);
test_header!(test5, vec![b"*"]);
crate::__common_header_test!(test1, vec![b"\"xyzzy\""]);
crate::__common_header_test!(test2, vec![b"W/\"xyzzy\""]);
crate::__common_header_test!(test3, vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]);
crate::__common_header_test!(test4, vec![b"W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\""]);
crate::__common_header_test!(test5, vec![b"*"]);
}
}

View File

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

View File

@ -1,6 +1,6 @@
use super::{HttpDate, IF_UNMODIFIED_SINCE};
crate::header! {
crate::__define_common_header! {
/// `If-Unmodified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4)
///
@ -37,6 +37,6 @@ crate::header! {
test_if_unmodified_since {
// 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};
crate::header! {
crate::__define_common_header! {
/// `Last-Modified` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.2)
///
@ -36,5 +36,6 @@ crate::header! {
test_last_modified {
// 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
//!
//! Several header fields use MIME values for their contents. Keeping with the
//! strongly-typed theme, the [mime] crate
//! is used, such as `ContentType(pub Mime)`.
#![cfg_attr(rustfmt, rustfmt_skip)]
//! Several header fields use MIME values for their contents. Keeping with the strongly-typed theme,
//! the [mime] crate is used in such headers as [`ContentType`] and [`Accept`].
use bytes::{Bytes, BytesMut};
use std::fmt;
use bytes::{BytesMut, Bytes};
pub use actix_http::http::header::*;
pub use self::accept_charset::AcceptCharset;
pub use actix_http::http::header::*;
//pub use self::accept_encoding::AcceptEncoding;
pub use self::accept::Accept;
pub use self::accept_language::AcceptLanguage;
pub use self::allow::Allow;
pub use self::cache_control::{CacheControl, CacheDirective};
pub use self::content_disposition::{
ContentDisposition, DispositionParam, DispositionType,
};
pub use self::content_disposition::{ContentDisposition, DispositionParam, DispositionType};
pub use self::content_language::ContentLanguage;
pub use self::content_range::{ContentRange, ContentRangeSpec};
pub use self::content_type::ContentType;
pub use self::date::Date;
pub use self::encoding::Encoding;
pub use self::entity::EntityTag;
pub use self::etag::ETag;
pub use self::expires::Expires;
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_unmodified_since::IfUnmodifiedSince;
pub use self::last_modified::LastModified;
pub use self::encoding::Encoding;
pub use self::entity::EntityTag;
//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)]
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_encoding;
mod accept;
@ -379,6 +74,8 @@ mod content_language;
mod content_range;
mod content_type;
mod date;
mod encoding;
mod entity;
mod etag;
mod expires;
mod if_match;
@ -387,5 +84,4 @@ mod if_none_match;
mod if_range;
mod if_unmodified_since;
mod last_modified;
mod encoding;
mod entity;
mod macros;

View File

@ -30,16 +30,16 @@
//!
//! 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.
//!
//! * [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.
//!
//! * [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.
//!
//! * [HttpRequest] and [HttpResponse]: These
//! * [`HttpRequest`] and [`HttpResponse`]: These
//! structs represent HTTP requests and responses and expose methods for creating, inspecting,
//! and otherwise utilizing them.
//!
@ -55,7 +55,7 @@
//! * Static assets
//! * SSL support using OpenSSL or Rustls
//! * Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
//! * Includes an async [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
//! * Includes an async [HTTP client](https://docs.rs/awc/)
//! * Runs on stable Rust 1.46+
//!
//! ## Crate Features
@ -145,7 +145,7 @@ pub mod dev {
pub use actix_http::{Extensions, Payload, PayloadStream, RequestHead, ResponseHead};
pub use actix_router::{Path, ResourceDef, ResourcePath, Url};
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> {
for path in &mut patterns {

View File

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

View File

@ -1,4 +1,4 @@
use std::fmt;
use std::{borrow::Cow, fmt};
use actix_http::{
body::Body,
@ -117,53 +117,29 @@ impl<T: Responder> Responder for (T, StatusCode) {
}
}
impl Responder for &'static str {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(self)
}
macro_rules! impl_responder {
($res: ty, $ct: path) => {
impl Responder for $res {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok().content_type($ct).body(self)
}
}
};
}
impl Responder for &'static [u8] {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(self)
}
}
impl_responder!(&'static str, mime::TEXT_PLAIN_UTF_8);
impl Responder for String {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(self)
}
}
impl_responder!(String, mime::TEXT_PLAIN_UTF_8);
impl<'a> Responder for &'a String {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(self)
}
}
impl_responder!(&'_ String, mime::TEXT_PLAIN_UTF_8);
impl Responder for Bytes {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(self)
}
}
impl_responder!(Cow<'_, str>, mime::TEXT_PLAIN_UTF_8);
impl Responder for BytesMut {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_OCTET_STREAM)
.body(self)
}
}
impl_responder!(&'static [u8], mime::APPLICATION_OCTET_STREAM);
impl_responder!(Bytes, mime::APPLICATION_OCTET_STREAM);
impl_responder!(BytesMut, mime::APPLICATION_OCTET_STREAM);
/// Allows overriding status code and headers for a responder.
pub struct CustomResponder<T> {
@ -358,6 +334,31 @@ pub(crate) mod tests {
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);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");

View File

@ -32,7 +32,7 @@ use crate::{
///
/// This type can be used to construct an instance of `Response` through a builder-like pattern.
pub struct HttpResponseBuilder {
head: Option<ResponseHead>,
res: Option<Response<Body>>,
err: Option<HttpError>,
#[cfg(feature = "cookies")]
cookies: Option<CookieJar>,
@ -43,7 +43,7 @@ impl HttpResponseBuilder {
/// Create response builder
pub fn new(status: StatusCode) -> Self {
Self {
head: Some(ResponseHead::new(status)),
res: Some(Response::new(status)),
err: None,
#[cfg(feature = "cookies")]
cookies: None,
@ -291,15 +291,19 @@ impl HttpResponseBuilder {
/// Responses extensions
#[inline]
pub fn extensions(&self) -> Ref<'_, Extensions> {
let head = self.head.as_ref().expect("cannot reuse response builder");
head.extensions()
self.res
.as_ref()
.expect("cannot reuse response builder")
.extensions()
}
/// 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_mut()
self.res
.as_mut()
.expect("cannot reuse response builder")
.extensions_mut()
}
/// Set a body and generate `Response`.
@ -318,12 +322,14 @@ impl HttpResponseBuilder {
return HttpResponse::from_error(Error::from(err)).into_body();
}
// allow unused mut when cookies feature is disabled
#[allow(unused_mut)]
let mut head = self.head.take().expect("cannot reuse response builder");
let res = self
.res
.take()
.expect("cannot reuse response builder")
.set_body(body);
let mut res = HttpResponse::with_body(StatusCode::OK, body);
*res.head_mut() = head;
#[allow(unused_mut)]
let mut res = HttpResponse::from(res);
#[cfg(feature = "cookies")]
if let Some(ref jar) = self.cookies {
@ -383,7 +389,7 @@ impl HttpResponseBuilder {
/// This method construct new `HttpResponseBuilder`
pub fn take(&mut self) -> Self {
Self {
head: self.head.take(),
res: self.res.take(),
err: self.err.take(),
#[cfg(feature = "cookies")]
cookies: self.cookies.take(),
@ -396,7 +402,7 @@ impl HttpResponseBuilder {
return None;
}
self.head.as_mut()
self.res.as_mut().map(|res| res.head_mut())
}
}

View File

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

View File

@ -9,6 +9,8 @@ use actix_http::{
};
use actix_router::{IntoPattern, Path, Resource, ResourceDef, Url};
use actix_service::{IntoServiceFactory, ServiceFactory};
#[cfg(feature = "cookies")]
use cookie::{Cookie, ParseError as CookieParseError};
use crate::dev::insert_slash;
use crate::guard::Guard;
@ -244,6 +246,17 @@ impl ServiceRequest {
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.
pub fn set_payload(&mut self, payload: Payload) {
self.payload = payload;