mirror of https://github.com/fafhrd91/actix-web
fix tests
This commit is contained in:
parent
0e2f9a9106
commit
698737950a
|
@ -15,10 +15,12 @@
|
||||||
### Removed
|
### Removed
|
||||||
* Public field of `web::Path` has been made private. [#1894]
|
* Public field of `web::Path` has been made private. [#1894]
|
||||||
* Public field of `web::Query` has been made private. [#1894]
|
* Public field of `web::Query` has been made private. [#1894]
|
||||||
|
* `TestRequest::with_header`; use `TestRequest::default().insert_header()`. [#1869]
|
||||||
|
|
||||||
[#1891]: https://github.com/actix/actix-web/pull/1891
|
[#1891]: https://github.com/actix/actix-web/pull/1891
|
||||||
[#1893]: https://github.com/actix/actix-web/pull/1893
|
[#1893]: https://github.com/actix/actix-web/pull/1893
|
||||||
[#1894]: https://github.com/actix/actix-web/pull/1894
|
[#1894]: https://github.com/actix/actix-web/pull/1894
|
||||||
|
[#1869]: https://github.com/actix/actix-web/pull/1869
|
||||||
|
|
||||||
|
|
||||||
## 4.0.0-beta.1 - 2021-01-07
|
## 4.0.0-beta.1 - 2021-01-07
|
||||||
|
|
|
@ -1,11 +1,26 @@
|
||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
### Changed
|
### Added
|
||||||
* `Response::content_type` now takes an `impl IntoHeaderValue` to support `mime` types. [#1894]
|
* `IntoHeaderPair` trait that allows using types and non-typed headers in the same methods. [#1869]
|
||||||
* `Response::set` and `Response::header` methods; use the respective `Response::set_header` and
|
* `ResponseBuilder::insert_header` method which allows using typed headers. [#1869]
|
||||||
`Response::append_header` methods. [#1869]
|
* `ResponseBuilder::append_header` method which allows using typed headers. [#1869]
|
||||||
|
* `TestRequest::insert_header` method which allows using typed headers. [#1869]
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
* `ResponseBuilder::content_type` now takes an `impl IntoHeaderValue` to support using typed
|
||||||
|
`mime` types. [#1894]
|
||||||
|
* Renamed `IntoHeaderValue::{try_into => try_into_value}` to avoid ambiguity with std
|
||||||
|
`TryInto` trait. [#1894]
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
* `ResponseBuilder::set`; use `ResponseBuilder::insert_header`. [#1869]
|
||||||
|
* `ResponseBuilder::set_header`; use `ResponseBuilder::insert_header`. [#1869]
|
||||||
|
* `ResponseBuilder::header`; use `ResponseBuilder::append_header`. [#1869]
|
||||||
|
* `TestRequest::with_hdr`; use `TestRequest::default().insert_header()`. [#1869]
|
||||||
|
* `TestRequest::with_header`; use `TestRequest::default().insert_header()`. [#1869]
|
||||||
|
|
||||||
|
[#1869]: https://github.com/actix/actix-web/pull/1869
|
||||||
[#1894]: https://github.com/actix/actix-web/pull/1894
|
[#1894]: https://github.com/actix/actix-web/pull/1894
|
||||||
|
|
||||||
|
|
||||||
|
@ -35,12 +50,8 @@
|
||||||
[#1813]: https://github.com/actix/actix-web/pull/1813
|
[#1813]: https://github.com/actix/actix-web/pull/1813
|
||||||
[#1857]: https://github.com/actix/actix-web/pull/1857
|
[#1857]: https://github.com/actix/actix-web/pull/1857
|
||||||
[#1864]: https://github.com/actix/actix-web/pull/1864
|
[#1864]: https://github.com/actix/actix-web/pull/1864
|
||||||
<<<<<<< HEAD
|
|
||||||
[#1878]: https://github.com/actix/actix-web/pull/1878
|
[#1878]: https://github.com/actix/actix-web/pull/1878
|
||||||
=======
|
|
||||||
[#1869]: https://github.com/actix/actix-web/pull/1869
|
|
||||||
|
|
||||||
>>>>>>> 587000a2... add IntoHeaderPair trait
|
|
||||||
|
|
||||||
## 2.2.0 - 2020-11-25
|
## 2.2.0 - 2020-11-25
|
||||||
### Added
|
### Added
|
||||||
|
|
|
@ -132,7 +132,7 @@ header! {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_fuzzing1() {
|
fn test_fuzzing1() {
|
||||||
use crate::test::TestRequest;
|
use crate::test::TestRequest;
|
||||||
let req = TestRequest::with_header(crate::header::ACCEPT, "chunk#;e").finish();
|
let req = TestRequest::default().insert_header(crate::header::ACCEPT, "chunk#;e").finish();
|
||||||
let header = Accept::parse(&req);
|
let header = Accept::parse(&req);
|
||||||
assert!(header.is_ok());
|
assert!(header.is_ok());
|
||||||
}
|
}
|
||||||
|
|
|
@ -196,7 +196,7 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_multiple_headers() {
|
fn test_parse_multiple_headers() {
|
||||||
let req = TestRequest::with_header(header::CACHE_CONTROL, "no-cache, private")
|
let req = TestRequest::default().insert_header(header::CACHE_CONTROL, "no-cache, private")
|
||||||
.finish();
|
.finish();
|
||||||
let cache = Header::parse(&req);
|
let cache = Header::parse(&req);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
@ -211,7 +211,7 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_argument() {
|
fn test_parse_argument() {
|
||||||
let req =
|
let req =
|
||||||
TestRequest::with_header(header::CACHE_CONTROL, "max-age=100, private")
|
TestRequest::default().insert_header(header::CACHE_CONTROL, "max-age=100, private")
|
||||||
.finish();
|
.finish();
|
||||||
let cache = Header::parse(&req);
|
let cache = Header::parse(&req);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
@ -226,7 +226,7 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_quote_form() {
|
fn test_parse_quote_form() {
|
||||||
let req =
|
let req =
|
||||||
TestRequest::with_header(header::CACHE_CONTROL, "max-age=\"200\"").finish();
|
TestRequest::default().insert_header(header::CACHE_CONTROL, "max-age=\"200\"").finish();
|
||||||
let cache = Header::parse(&req);
|
let cache = Header::parse(&req);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.ok(),
|
cache.ok(),
|
||||||
|
@ -237,7 +237,7 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_extension() {
|
fn test_parse_extension() {
|
||||||
let req =
|
let req =
|
||||||
TestRequest::with_header(header::CACHE_CONTROL, "foo, bar=baz").finish();
|
TestRequest::default().insert_header(header::CACHE_CONTROL, "foo, bar=baz").finish();
|
||||||
let cache = Header::parse(&req);
|
let cache = Header::parse(&req);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
cache.ok(),
|
cache.ok(),
|
||||||
|
@ -250,7 +250,7 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_bad_syntax() {
|
fn test_parse_bad_syntax() {
|
||||||
let req = TestRequest::with_header(header::CACHE_CONTROL, "foo=").finish();
|
let req = TestRequest::default().insert_header(header::CACHE_CONTROL, "foo=").finish();
|
||||||
let cache: Result<CacheControl, _> = Header::parse(&req);
|
let cache: Result<CacheControl, _> = Header::parse(&req);
|
||||||
assert_eq!(cache.ok(), None)
|
assert_eq!(cache.ok(), None)
|
||||||
}
|
}
|
||||||
|
|
|
@ -73,12 +73,12 @@ mod tests {
|
||||||
fn test_if_none_match() {
|
fn test_if_none_match() {
|
||||||
let mut if_none_match: Result<IfNoneMatch, _>;
|
let mut if_none_match: Result<IfNoneMatch, _>;
|
||||||
|
|
||||||
let req = TestRequest::with_header(IF_NONE_MATCH, "*").finish();
|
let req = TestRequest::default().insert_header(IF_NONE_MATCH, "*").finish();
|
||||||
if_none_match = Header::parse(&req);
|
if_none_match = Header::parse(&req);
|
||||||
assert_eq!(if_none_match.ok(), Some(IfNoneMatch::Any));
|
assert_eq!(if_none_match.ok(), Some(IfNoneMatch::Any));
|
||||||
|
|
||||||
let req =
|
let req =
|
||||||
TestRequest::with_header(IF_NONE_MATCH, &b"\"foobar\", W/\"weak-etag\""[..])
|
TestRequest::default().insert_header(IF_NONE_MATCH, &b"\"foobar\", W/\"weak-etag\""[..])
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
if_none_match = Header::parse(&req);
|
if_none_match = Header::parse(&req);
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
use std::convert::{Infallible, TryFrom};
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
use either::Either;
|
|
||||||
use http::{
|
use http::{
|
||||||
header::{HeaderName, InvalidHeaderName, InvalidHeaderValue},
|
header::{HeaderName, InvalidHeaderName, InvalidHeaderValue},
|
||||||
Error as HttpError, HeaderValue,
|
Error as HttpError, HeaderValue,
|
||||||
|
@ -10,39 +9,11 @@ use super::{Header, IntoHeaderValue};
|
||||||
|
|
||||||
/// Transforms structures into header K/V pairs for inserting into `HeaderMap`s.
|
/// Transforms structures into header K/V pairs for inserting into `HeaderMap`s.
|
||||||
pub trait IntoHeaderPair: Sized {
|
pub trait IntoHeaderPair: Sized {
|
||||||
type Error;
|
type Error: Into<HttpError>;
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error>;
|
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoHeaderPair for (HeaderName, HeaderValue) {
|
|
||||||
type Error = Infallible;
|
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntoHeaderPair for (HeaderName, &str) {
|
|
||||||
type Error = InvalidHeaderValue;
|
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
|
||||||
let (name, value) = self;
|
|
||||||
let value = HeaderValue::try_from(value)?;
|
|
||||||
Ok((name, value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntoHeaderPair for (&str, HeaderValue) {
|
|
||||||
type Error = InvalidHeaderName;
|
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
|
||||||
let (name, value) = self;
|
|
||||||
let name = HeaderName::try_from(name)?;
|
|
||||||
Ok((name, value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum InvalidHeaderPart {
|
pub enum InvalidHeaderPart {
|
||||||
Name(InvalidHeaderName),
|
Name(InvalidHeaderName),
|
||||||
|
@ -58,52 +29,86 @@ impl From<InvalidHeaderPart> for HttpError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoHeaderPair for (&str, &str) {
|
impl<V> IntoHeaderPair for (HeaderName, V)
|
||||||
|
where
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
V::Error: Into<InvalidHeaderValue>,
|
||||||
|
{
|
||||||
|
type Error = InvalidHeaderPart;
|
||||||
|
|
||||||
|
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
||||||
|
let (name, value) = self;
|
||||||
|
let value = value
|
||||||
|
.try_into_value()
|
||||||
|
.map_err(|err| InvalidHeaderPart::Value(err.into()))?;
|
||||||
|
Ok((name, value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<V> IntoHeaderPair for (&HeaderName, V)
|
||||||
|
where
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
V::Error: Into<InvalidHeaderValue>,
|
||||||
|
{
|
||||||
|
type Error = InvalidHeaderPart;
|
||||||
|
|
||||||
|
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
||||||
|
let (name, value) = self;
|
||||||
|
let value = value
|
||||||
|
.try_into_value()
|
||||||
|
.map_err(|err| InvalidHeaderPart::Value(err.into()))?;
|
||||||
|
Ok((name.clone(), value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<V> IntoHeaderPair for (&[u8], V)
|
||||||
|
where
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
V::Error: Into<InvalidHeaderValue>,
|
||||||
|
{
|
||||||
type Error = InvalidHeaderPart;
|
type Error = InvalidHeaderPart;
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
||||||
let (name, value) = self;
|
let (name, value) = self;
|
||||||
let name = HeaderName::try_from(name).map_err(InvalidHeaderPart::Name)?;
|
let name = HeaderName::try_from(name).map_err(InvalidHeaderPart::Name)?;
|
||||||
let value = HeaderValue::try_from(value).map_err(InvalidHeaderPart::Value)?;
|
let value = value
|
||||||
|
.try_into_value()
|
||||||
|
.map_err(|err| InvalidHeaderPart::Value(err.into()))?;
|
||||||
Ok((name, value))
|
Ok((name, value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoHeaderPair for (HeaderName, String) {
|
impl<V> IntoHeaderPair for (&str, V)
|
||||||
type Error = InvalidHeaderValue;
|
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
|
||||||
let (name, value) = self;
|
|
||||||
let value = HeaderValue::try_from(&value)?;
|
|
||||||
Ok((name, value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntoHeaderPair for (String, HeaderValue) {
|
|
||||||
type Error = InvalidHeaderName;
|
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
|
||||||
let (name, value) = self;
|
|
||||||
let name = HeaderName::try_from(&name)?;
|
|
||||||
Ok((name, value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntoHeaderPair for (String, String) {
|
|
||||||
type Error = Either<InvalidHeaderName, InvalidHeaderValue>;
|
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
|
||||||
let (name, value) = self;
|
|
||||||
let name = HeaderName::try_from(&name).map_err(Either::Left)?;
|
|
||||||
let value = HeaderValue::try_from(&value).map_err(Either::Right)?;
|
|
||||||
Ok((name, value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> IntoHeaderPair for T
|
|
||||||
where
|
where
|
||||||
T: Header,
|
V: IntoHeaderValue,
|
||||||
|
V::Error: Into<InvalidHeaderValue>,
|
||||||
{
|
{
|
||||||
|
type Error = InvalidHeaderPart;
|
||||||
|
|
||||||
|
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
||||||
|
let (name, value) = self;
|
||||||
|
let name = HeaderName::try_from(name).map_err(InvalidHeaderPart::Name)?;
|
||||||
|
let value = value
|
||||||
|
.try_into_value()
|
||||||
|
.map_err(|err| InvalidHeaderPart::Value(err.into()))?;
|
||||||
|
Ok((name, value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<V> IntoHeaderPair for (String, V)
|
||||||
|
where
|
||||||
|
V: IntoHeaderValue,
|
||||||
|
V::Error: Into<InvalidHeaderValue>,
|
||||||
|
{
|
||||||
|
type Error = InvalidHeaderPart;
|
||||||
|
|
||||||
|
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
||||||
|
let (name, value) = self;
|
||||||
|
(name.as_str(), value).try_into_header_pair()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Header> IntoHeaderPair for T {
|
||||||
type Error = <T as IntoHeaderValue>::Error;
|
type Error = <T as IntoHeaderValue>::Error;
|
||||||
|
|
||||||
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
fn try_into_header_pair(self) -> Result<(HeaderName, HeaderValue), Self::Error> {
|
||||||
|
|
|
@ -9,7 +9,7 @@ pub trait IntoHeaderValue: Sized {
|
||||||
/// The type returned in the event of a conversion error.
|
/// The type returned in the event of a conversion error.
|
||||||
type Error: Into<HttpError>;
|
type Error: Into<HttpError>;
|
||||||
|
|
||||||
/// Try to convert value to a Header pair value.
|
/// Try to convert value to a HeaderValue.
|
||||||
fn try_into_value(self) -> Result<HeaderValue, Self::Error>;
|
fn try_into_value(self) -> Result<HeaderValue, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -22,7 +22,16 @@ impl IntoHeaderValue for HeaderValue {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> IntoHeaderValue for &'a str {
|
impl IntoHeaderValue for &HeaderValue {
|
||||||
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
||||||
|
Ok(self.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoHeaderValue for &str {
|
||||||
type Error = InvalidHeaderValue;
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
|
@ -31,7 +40,7 @@ impl<'a> IntoHeaderValue for &'a str {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> IntoHeaderValue for &'a [u8] {
|
impl IntoHeaderValue for &[u8] {
|
||||||
type Error = InvalidHeaderValue;
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
|
@ -72,8 +81,16 @@ impl IntoHeaderValue for usize {
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
||||||
let s = format!("{}", self);
|
HeaderValue::try_from(self.to_string())
|
||||||
HeaderValue::try_from(s)
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoHeaderValue for i64 {
|
||||||
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
||||||
|
HeaderValue::try_from(self.to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -82,8 +99,25 @@ impl IntoHeaderValue for u64 {
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
||||||
let s = format!("{}", self);
|
HeaderValue::try_from(self.to_string())
|
||||||
HeaderValue::try_from(s)
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoHeaderValue for i32 {
|
||||||
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
||||||
|
HeaderValue::try_from(self.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoHeaderValue for u32 {
|
||||||
|
type Error = InvalidHeaderValue;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
|
||||||
|
HeaderValue::try_from(self.to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -285,6 +285,7 @@ impl<'a> AsName for &'a String {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Iterator for all values in a `HeaderMap` with the same name.
|
||||||
pub struct GetAll<'a> {
|
pub struct GetAll<'a> {
|
||||||
idx: usize,
|
idx: usize,
|
||||||
item: Option<&'a Value>,
|
item: Option<&'a Value>,
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
//! Various HTTP headers.
|
//! Typed HTTP headers, pre-defined `HeaderName`s, traits for parsing/conversion and other
|
||||||
|
//! header utility methods.
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
@ -68,7 +69,7 @@ impl fmt::Write for Writer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert http::HeaderMap to a HeaderMap
|
/// Convert `http::HeaderMap` to our `HeaderMap`.
|
||||||
impl From<http::HeaderMap> for HeaderMap {
|
impl From<http::HeaderMap> for HeaderMap {
|
||||||
fn from(map: http::HeaderMap) -> HeaderMap {
|
fn from(map: http::HeaderMap) -> HeaderMap {
|
||||||
let mut new_map = HeaderMap::with_capacity(map.capacity());
|
let mut new_map = HeaderMap::with_capacity(map.capacity());
|
||||||
|
@ -80,7 +81,7 @@ impl From<http::HeaderMap> for HeaderMap {
|
||||||
}
|
}
|
||||||
|
|
||||||
// This encode set is used for HTTP header values and is defined at
|
// This encode set is used for HTTP header values and is defined at
|
||||||
// https://tools.ietf.org/html/rfc5987#section-3.2
|
// https://tools.ietf.org/html/rfc5987#section-3.2.
|
||||||
pub(crate) const HTTP_VALUE: &AsciiSet = &CONTROLS
|
pub(crate) const HTTP_VALUE: &AsciiSet = &CONTROLS
|
||||||
.add(b' ')
|
.add(b' ')
|
||||||
.add(b'"')
|
.add(b'"')
|
||||||
|
|
|
@ -173,11 +173,13 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_content_type() {
|
fn test_content_type() {
|
||||||
let req = TestRequest::with_header("content-type", "text/plain").finish();
|
let req = TestRequest::default()
|
||||||
|
.insert_header("content-type", "text/plain")
|
||||||
|
.finish();
|
||||||
assert_eq!(req.content_type(), "text/plain");
|
assert_eq!(req.content_type(), "text/plain");
|
||||||
let req =
|
let req = TestRequest::default()
|
||||||
TestRequest::with_header("content-type", "application/json; charset=utf=8")
|
.insert_header("content-type", "application/json; charset=utf=8")
|
||||||
.finish();
|
.finish();
|
||||||
assert_eq!(req.content_type(), "application/json");
|
assert_eq!(req.content_type(), "application/json");
|
||||||
let req = TestRequest::default().finish();
|
let req = TestRequest::default().finish();
|
||||||
assert_eq!(req.content_type(), "");
|
assert_eq!(req.content_type(), "");
|
||||||
|
@ -185,13 +187,15 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_mime_type() {
|
fn test_mime_type() {
|
||||||
let req = TestRequest::with_header("content-type", "application/json").finish();
|
let req = TestRequest::default()
|
||||||
|
.insert_header("content-type", "application/json")
|
||||||
|
.finish();
|
||||||
assert_eq!(req.mime_type().unwrap(), Some(mime::APPLICATION_JSON));
|
assert_eq!(req.mime_type().unwrap(), Some(mime::APPLICATION_JSON));
|
||||||
let req = TestRequest::default().finish();
|
let req = TestRequest::default().finish();
|
||||||
assert_eq!(req.mime_type().unwrap(), None);
|
assert_eq!(req.mime_type().unwrap(), None);
|
||||||
let req =
|
let req = TestRequest::default()
|
||||||
TestRequest::with_header("content-type", "application/json; charset=utf-8")
|
.insert_header("content-type", "application/json; charset=utf-8")
|
||||||
.finish();
|
.finish();
|
||||||
let mt = req.mime_type().unwrap().unwrap();
|
let mt = req.mime_type().unwrap().unwrap();
|
||||||
assert_eq!(mt.get_param(mime::CHARSET), Some(mime::UTF_8));
|
assert_eq!(mt.get_param(mime::CHARSET), Some(mime::UTF_8));
|
||||||
assert_eq!(mt.type_(), mime::APPLICATION);
|
assert_eq!(mt.type_(), mime::APPLICATION);
|
||||||
|
@ -200,11 +204,9 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_mime_type_error() {
|
fn test_mime_type_error() {
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
"content-type",
|
.insert_header("content-type", "applicationadfadsfasdflknadsfklnadsfjson")
|
||||||
"applicationadfadsfasdflknadsfklnadsfjson",
|
.finish();
|
||||||
)
|
|
||||||
.finish();
|
|
||||||
assert_eq!(Err(ContentTypeError::ParseError), req.mime_type());
|
assert_eq!(Err(ContentTypeError::ParseError), req.mime_type());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -213,27 +215,27 @@ mod tests {
|
||||||
let req = TestRequest::default().finish();
|
let req = TestRequest::default().finish();
|
||||||
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
|
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
|
||||||
|
|
||||||
let req = TestRequest::with_header("content-type", "application/json").finish();
|
let req = TestRequest::default()
|
||||||
|
.insert_header("content-type", "application/json")
|
||||||
|
.finish();
|
||||||
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
|
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
"content-type",
|
.insert_header("content-type", "application/json; charset=ISO-8859-2")
|
||||||
"application/json; charset=ISO-8859-2",
|
.finish();
|
||||||
)
|
|
||||||
.finish();
|
|
||||||
assert_eq!(ISO_8859_2, req.encoding().unwrap());
|
assert_eq!(ISO_8859_2, req.encoding().unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_encoding_error() {
|
fn test_encoding_error() {
|
||||||
let req = TestRequest::with_header("content-type", "applicatjson").finish();
|
let req = TestRequest::default()
|
||||||
|
.insert_header("content-type", "applicatjson")
|
||||||
|
.finish();
|
||||||
assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err());
|
assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err());
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
"content-type",
|
.insert_header("content-type", "application/json; charset=kkkttktk")
|
||||||
"application/json; charset=kkkttktk",
|
.finish();
|
||||||
)
|
|
||||||
.finish();
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Some(ContentTypeError::UnknownEncoding),
|
Some(ContentTypeError::UnknownEncoding),
|
||||||
req.encoding().err()
|
req.encoding().err()
|
||||||
|
@ -245,8 +247,9 @@ mod tests {
|
||||||
let req = TestRequest::default().finish();
|
let req = TestRequest::default().finish();
|
||||||
assert!(!req.chunked().unwrap());
|
assert!(!req.chunked().unwrap());
|
||||||
|
|
||||||
let req =
|
let req = TestRequest::default()
|
||||||
TestRequest::with_header(header::TRANSFER_ENCODING, "chunked").finish();
|
.insert_header(header::TRANSFER_ENCODING, "chunked")
|
||||||
|
.finish();
|
||||||
assert!(req.chunked().unwrap());
|
assert!(req.chunked().unwrap());
|
||||||
|
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
|
|
|
@ -2,7 +2,6 @@
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
cell::{Ref, RefMut},
|
cell::{Ref, RefMut},
|
||||||
convert::TryFrom,
|
|
||||||
fmt,
|
fmt,
|
||||||
future::Future,
|
future::Future,
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
|
@ -18,8 +17,8 @@ use crate::body::{Body, BodyStream, MessageBody, ResponseBody};
|
||||||
use crate::cookie::{Cookie, CookieJar};
|
use crate::cookie::{Cookie, CookieJar};
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::extensions::Extensions;
|
use crate::extensions::Extensions;
|
||||||
use crate::header::{Header, IntoHeaderPair, IntoHeaderValue};
|
use crate::header::{IntoHeaderPair, IntoHeaderValue};
|
||||||
use crate::http::header::{self, HeaderName, HeaderValue};
|
use crate::http::header::{self, HeaderValue};
|
||||||
use crate::http::{Error as HttpError, HeaderMap, StatusCode};
|
use crate::http::{Error as HttpError, HeaderMap, StatusCode};
|
||||||
use crate::message::{BoxedResponseHead, ConnectionType, ResponseHead};
|
use crate::message::{BoxedResponseHead, ConnectionType, ResponseHead};
|
||||||
|
|
||||||
|
@ -345,80 +344,18 @@ impl ResponseBuilder {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a header.
|
/// Insert a header, replacing any that were set with an equivalent field name.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::{http, Request, Response, Result};
|
/// # use actix_http::Response;
|
||||||
///
|
/// Response::Ok()
|
||||||
/// fn index(req: Request) -> Result<Response> {
|
/// .set_header(("X-TEST", "value"))
|
||||||
/// Ok(Response::Ok()
|
/// .set_header(ContentType(mime::APPLICATION_JSON))
|
||||||
/// .set(http::header::IfModifiedSince(
|
/// .finish()
|
||||||
/// "Sun, 07 Nov 1994 08:48:37 GMT".parse()?,
|
|
||||||
/// ))
|
|
||||||
/// .finish())
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
#[doc(hidden)]
|
|
||||||
pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self {
|
|
||||||
if let Some(parts) = parts(&mut self.head, &self.err) {
|
|
||||||
match hdr.try_into_value() {
|
|
||||||
Ok(value) => {
|
|
||||||
parts.headers.append(H::name(), value);
|
|
||||||
}
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Append a header to existing headers.
|
|
||||||
///
|
|
||||||
/// ```rust
|
|
||||||
/// use actix_http::{http, Request, Response};
|
|
||||||
///
|
|
||||||
/// fn index(req: Request) -> Response {
|
|
||||||
/// Response::Ok()
|
|
||||||
/// .header("X-TEST", "value")
|
|
||||||
/// .header(http::header::CONTENT_TYPE, "application/json")
|
|
||||||
/// .finish()
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
|
|
||||||
where
|
|
||||||
HeaderName: TryFrom<K>,
|
|
||||||
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
|
|
||||||
V: IntoHeaderValue,
|
|
||||||
{
|
|
||||||
if let Some(parts) = parts(&mut self.head, &self.err) {
|
|
||||||
match HeaderName::try_from(key) {
|
|
||||||
Ok(key) => match value.try_into_value() {
|
|
||||||
Ok(value) => {
|
|
||||||
parts.headers.append(key, value);
|
|
||||||
}
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
},
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert a header, replacing any that existed with an equivalent field name.
|
|
||||||
///
|
|
||||||
/// ```rust
|
|
||||||
/// use actix_http::{http, Request, Response};
|
|
||||||
///
|
|
||||||
/// fn index(req: Request) -> Response {
|
|
||||||
/// Response::Ok()
|
|
||||||
/// .set_header(("X-TEST", "value"))
|
|
||||||
/// .set_header(ContentType(mime::APPLICATION_JSON))
|
|
||||||
/// .finish()
|
|
||||||
/// }
|
|
||||||
/// ```
|
/// ```
|
||||||
pub fn insert_header<H>(&mut self, header: H) -> &mut Self
|
pub fn insert_header<H>(&mut self, header: H) -> &mut Self
|
||||||
where
|
where
|
||||||
H: IntoHeaderPair,
|
H: IntoHeaderPair,
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
{
|
||||||
if let Some(parts) = parts(&mut self.head, &self.err) {
|
if let Some(parts) = parts(&mut self.head, &self.err) {
|
||||||
match header.try_into_header_pair() {
|
match header.try_into_header_pair() {
|
||||||
|
@ -430,22 +367,18 @@ impl ResponseBuilder {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Append a header, keeping any that existed with an equivalent field name.
|
/// Append a header, keeping any that were set with an equivalent field name.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_http::{http, Request, Response};
|
/// # use actix_http::Response;
|
||||||
///
|
/// Response::Ok()
|
||||||
/// fn index(req: Request) -> Response {
|
/// .append_header(("X-TEST", "value"))
|
||||||
/// Response::Ok()
|
/// .append_header(ContentType(mime::APPLICATION_JSON))
|
||||||
/// .append_header(("X-TEST", "value"))
|
/// .finish()
|
||||||
/// .append_header(ContentType(mime::APPLICATION_JSON))
|
|
||||||
/// .finish()
|
|
||||||
/// }
|
|
||||||
/// ```
|
/// ```
|
||||||
pub fn append_header<H>(&mut self, header: H) -> &mut Self
|
pub fn append_header<H>(&mut self, header: H) -> &mut Self
|
||||||
where
|
where
|
||||||
H: IntoHeaderPair,
|
H: IntoHeaderPair,
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
{
|
||||||
if let Some(parts) = parts(&mut self.head, &self.err) {
|
if let Some(parts) = parts(&mut self.head, &self.err) {
|
||||||
match header.try_into_header_pair() {
|
match header.try_into_header_pair() {
|
||||||
|
@ -504,7 +437,7 @@ impl ResponseBuilder {
|
||||||
/// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
|
/// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn no_chunking(&mut self, len: u64) -> &mut Self {
|
pub fn no_chunking(&mut self, len: u64) -> &mut Self {
|
||||||
self.header(header::CONTENT_LENGTH, len);
|
self.insert_header((header::CONTENT_LENGTH, len));
|
||||||
|
|
||||||
if let Some(parts) = parts(&mut self.head, &self.err) {
|
if let Some(parts) = parts(&mut self.head, &self.err) {
|
||||||
parts.no_chunking(true);
|
parts.no_chunking(true);
|
||||||
|
@ -519,7 +452,7 @@ impl ResponseBuilder {
|
||||||
V: IntoHeaderValue,
|
V: IntoHeaderValue,
|
||||||
{
|
{
|
||||||
if let Some(parts) = parts(&mut self.head, &self.err) {
|
if let Some(parts) = parts(&mut self.head, &self.err) {
|
||||||
match value.try_into() {
|
match value.try_into_value() {
|
||||||
Ok(value) => {
|
Ok(value) => {
|
||||||
parts.headers.insert(header::CONTENT_TYPE, value);
|
parts.headers.insert(header::CONTENT_TYPE, value);
|
||||||
}
|
}
|
||||||
|
@ -689,8 +622,9 @@ impl ResponseBuilder {
|
||||||
} else {
|
} else {
|
||||||
true
|
true
|
||||||
};
|
};
|
||||||
|
|
||||||
if !contains {
|
if !contains {
|
||||||
self.header(header::CONTENT_TYPE, "application/json");
|
self.insert_header(header::ContentType(mime::APPLICATION_JSON));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.body(Body::from(body))
|
self.body(Body::from(body))
|
||||||
|
|
|
@ -13,7 +13,7 @@ use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use http::{
|
use http::{
|
||||||
header::{self, HeaderValue},
|
header::{self, HeaderValue},
|
||||||
Error as HttpError, Method, Uri, Version,
|
Method, Uri, Version,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
@ -38,7 +38,7 @@ use crate::{
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// let resp = TestRequest::with_header("content-type", "text/plain")
|
/// let resp = TestRequest::default().insert_header("content-type", "text/plain")
|
||||||
/// .run(&index)
|
/// .run(&index)
|
||||||
/// .unwrap();
|
/// .unwrap();
|
||||||
/// assert_eq!(resp.status(), StatusCode::OK);
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
@ -76,15 +76,6 @@ impl TestRequest {
|
||||||
TestRequest::default().uri(path).take()
|
TestRequest::default().uri(path).take()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a default TestRequest and then set a header.
|
|
||||||
pub fn with_header<H>(header: H) -> TestRequest
|
|
||||||
where
|
|
||||||
H: IntoHeaderPair,
|
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
|
||||||
TestRequest::default().header(header).take()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set HTTP version of this request.
|
/// Set HTTP version of this request.
|
||||||
pub fn version(&mut self, ver: Version) -> &mut Self {
|
pub fn version(&mut self, ver: Version) -> &mut Self {
|
||||||
parts(&mut self.0).version = ver;
|
parts(&mut self.0).version = ver;
|
||||||
|
@ -97,17 +88,35 @@ impl TestRequest {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set HTTP Uri of this request.
|
/// Set URI of this request.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
/// If provided URI is invalid.
|
||||||
pub fn uri(&mut self, path: &str) -> &mut Self {
|
pub fn uri(&mut self, path: &str) -> &mut Self {
|
||||||
parts(&mut self.0).uri = Uri::from_str(path).unwrap();
|
parts(&mut self.0).uri = Uri::from_str(path).unwrap();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a header.
|
/// Insert a header, replacing any that were set with an equivalent field name.
|
||||||
pub fn header<H>(&mut self, header: H) -> &mut Self
|
pub fn insert_header<H>(&mut self, header: H) -> &mut Self
|
||||||
|
where
|
||||||
|
H: IntoHeaderPair,
|
||||||
|
{
|
||||||
|
match header.try_into_header_pair() {
|
||||||
|
Ok((key, value)) => {
|
||||||
|
parts(&mut self.0).headers.insert(key, value);
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
panic!("Error inserting test header: {}.", err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append a header, keeping any that were set with an equivalent field name.
|
||||||
|
pub fn append_header<H>(&mut self, header: H) -> &mut Self
|
||||||
where
|
where
|
||||||
H: IntoHeaderPair,
|
H: IntoHeaderPair,
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
{
|
||||||
match header.try_into_header_pair() {
|
match header.try_into_header_pair() {
|
||||||
Ok((key, value)) => {
|
Ok((key, value)) => {
|
||||||
|
@ -115,7 +124,7 @@ impl TestRequest {
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
panic!("Error setting test header: {}.", err.into());
|
panic!("Error inserting test header: {}.", err.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -101,7 +101,7 @@ impl ResponseError for HandshakeError {
|
||||||
fn error_response(&self) -> Response {
|
fn error_response(&self) -> Response {
|
||||||
match self {
|
match self {
|
||||||
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
|
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
|
||||||
.header(header::ALLOW, "GET")
|
.insert_header((header::ALLOW, "GET"))
|
||||||
.finish(),
|
.finish(),
|
||||||
|
|
||||||
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
|
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
|
||||||
|
@ -198,8 +198,8 @@ pub fn handshake_response(req: &RequestHead) -> ResponseBuilder {
|
||||||
|
|
||||||
Response::build(StatusCode::SWITCHING_PROTOCOLS)
|
Response::build(StatusCode::SWITCHING_PROTOCOLS)
|
||||||
.upgrade("websocket")
|
.upgrade("websocket")
|
||||||
.header(header::TRANSFER_ENCODING, "chunked")
|
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||||
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
|
.insert_header((header::SEC_WEBSOCKET_ACCEPT, key))
|
||||||
.take()
|
.take()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,17 @@
|
||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
|
### Added
|
||||||
|
* `ClientRequest::insert_header` method which allows using typed headers. [#1869]
|
||||||
|
* `ClientRequest::append_header` method which allows using typed headers. [#1869]
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
* `ClientRequest::set`; use `ClientRequest::insert_header`. [#1869]
|
||||||
|
* `ClientRequest::set_header`; use `ClientRequest::insert_header`. [#1869]
|
||||||
|
* `ClientRequest::set_header_if_none`; use `ClientRequest::insert_header_if_none`. [#1869]
|
||||||
|
* `ClientRequest::header`; use `ClientRequest::append_header`. [#1869]
|
||||||
|
|
||||||
|
[#1869]: https://github.com/actix/actix-web/pull/1869
|
||||||
|
|
||||||
|
|
||||||
## 3.0.0-beta.1 - 2021-01-07
|
## 3.0.0-beta.1 - 2021-01-07
|
||||||
|
|
|
@ -182,8 +182,8 @@ impl Client {
|
||||||
{
|
{
|
||||||
let mut req = ClientRequest::new(method, url, self.0.clone());
|
let mut req = ClientRequest::new(method, url, self.0.clone());
|
||||||
|
|
||||||
for (key, value) in self.0.headers.iter() {
|
for header in self.0.headers.iter() {
|
||||||
req = req.set_header_if_none(key.clone(), value.clone());
|
req = req.insert_header_if_none(header);
|
||||||
}
|
}
|
||||||
req
|
req
|
||||||
}
|
}
|
||||||
|
@ -198,8 +198,8 @@ impl Client {
|
||||||
<Uri as TryFrom<U>>::Error: Into<HttpError>,
|
<Uri as TryFrom<U>>::Error: Into<HttpError>,
|
||||||
{
|
{
|
||||||
let mut req = self.request(head.method.clone(), url);
|
let mut req = self.request(head.method.clone(), url);
|
||||||
for (key, value) in head.headers.iter() {
|
for header in head.headers.iter() {
|
||||||
req = req.set_header_if_none(key.clone(), value.clone());
|
req = req.insert_header_if_none(header);
|
||||||
}
|
}
|
||||||
req
|
req
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,10 +9,10 @@ use serde::Serialize;
|
||||||
|
|
||||||
use actix_http::body::Body;
|
use actix_http::body::Body;
|
||||||
use actix_http::cookie::{Cookie, CookieJar};
|
use actix_http::cookie::{Cookie, CookieJar};
|
||||||
use actix_http::http::header::{self, Header, IntoHeaderValue};
|
use actix_http::http::header::{self, IntoHeaderPair};
|
||||||
use actix_http::http::{
|
use actix_http::http::{
|
||||||
uri, ConnectionType, Error as HttpError, HeaderMap, HeaderName, HeaderValue, Method,
|
uri, ConnectionType, Error as HttpError, HeaderMap, HeaderValue, Method, Uri,
|
||||||
Uri, Version,
|
Version,
|
||||||
};
|
};
|
||||||
use actix_http::{Error, RequestHead};
|
use actix_http::{Error, RequestHead};
|
||||||
|
|
||||||
|
@ -143,45 +143,49 @@ impl ClientRequest {
|
||||||
&self.head.peer_addr
|
&self.head.peer_addr
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
|
||||||
/// Returns request's headers.
|
/// Returns request's headers.
|
||||||
|
#[inline]
|
||||||
pub fn headers(&self) -> &HeaderMap {
|
pub fn headers(&self) -> &HeaderMap {
|
||||||
&self.head.headers
|
&self.head.headers
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
|
||||||
/// Returns request's mutable headers.
|
/// Returns request's mutable headers.
|
||||||
|
#[inline]
|
||||||
pub fn headers_mut(&mut self) -> &mut HeaderMap {
|
pub fn headers_mut(&mut self) -> &mut HeaderMap {
|
||||||
&mut self.head.headers
|
&mut self.head.headers
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a header.
|
/// Insert a header, replacing any that were set with an equivalent field name.
|
||||||
///
|
pub fn insert_header<H>(mut self, header: H) -> Self
|
||||||
/// ```rust
|
where
|
||||||
/// fn main() {
|
H: IntoHeaderPair,
|
||||||
/// # actix_rt::System::new("test").block_on(futures_util::future::lazy(|_| {
|
{
|
||||||
/// let req = awc::Client::new()
|
match header.try_into_header_pair() {
|
||||||
/// .get("http://www.rust-lang.org")
|
Ok((key, value)) => self.head.headers.insert(key, value),
|
||||||
/// .set(awc::http::header::Date::now())
|
|
||||||
/// .set(awc::http::header::ContentType(mime::TEXT_HTML));
|
|
||||||
/// # Ok::<_, ()>(())
|
|
||||||
/// # }));
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub fn set<H: Header>(mut self, hdr: H) -> Self {
|
|
||||||
match hdr.try_into_value() {
|
|
||||||
Ok(value) => {
|
|
||||||
self.head.headers.insert(H::name(), value);
|
|
||||||
}
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
Err(e) => self.err = Some(e.into()),
|
||||||
}
|
};
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Append a header.
|
/// Insert a header only if it is not yet set.
|
||||||
///
|
pub fn insert_header_if_none<H>(mut self, header: H) -> Self
|
||||||
/// Header gets appended to existing header.
|
where
|
||||||
/// To override header use `set_header()` method.
|
H: IntoHeaderPair,
|
||||||
|
{
|
||||||
|
match header.try_into_header_pair() {
|
||||||
|
Ok((key, value)) => {
|
||||||
|
if !self.head.headers.contains_key(&key) {
|
||||||
|
self.head.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.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use awc::{http, Client};
|
/// use awc::{http, Client};
|
||||||
|
@ -196,57 +200,15 @@ impl ClientRequest {
|
||||||
/// # });
|
/// # });
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn header<K, V>(mut self, key: K, value: V) -> Self
|
pub fn append_header<H>(mut self, header: H) -> Self
|
||||||
where
|
where
|
||||||
HeaderName: TryFrom<K>,
|
H: IntoHeaderPair,
|
||||||
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
|
|
||||||
V: IntoHeaderValue,
|
|
||||||
{
|
{
|
||||||
match HeaderName::try_from(key) {
|
match header.try_into_header_pair() {
|
||||||
Ok(key) => match value.try_into_value() {
|
Ok((key, value)) => self.head.headers.append(key, value),
|
||||||
Ok(value) => self.head.headers.append(key, value),
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
},
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
Err(e) => self.err = Some(e.into()),
|
||||||
}
|
};
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert a header, replaces existing header.
|
|
||||||
pub fn set_header<K, V>(mut self, key: K, value: V) -> Self
|
|
||||||
where
|
|
||||||
HeaderName: TryFrom<K>,
|
|
||||||
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
|
|
||||||
V: IntoHeaderValue,
|
|
||||||
{
|
|
||||||
match HeaderName::try_from(key) {
|
|
||||||
Ok(key) => match value.try_into_value() {
|
|
||||||
Ok(value) => self.head.headers.insert(key, value),
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
},
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Insert a header only if it is not yet set.
|
|
||||||
pub fn set_header_if_none<K, V>(mut self, key: K, value: V) -> Self
|
|
||||||
where
|
|
||||||
HeaderName: TryFrom<K>,
|
|
||||||
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
|
|
||||||
V: IntoHeaderValue,
|
|
||||||
{
|
|
||||||
match HeaderName::try_from(key) {
|
|
||||||
Ok(key) => {
|
|
||||||
if !self.head.headers.contains_key(&key) {
|
|
||||||
match value.try_into_value() {
|
|
||||||
Ok(value) => self.head.headers.insert(key, value),
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => self.err = Some(e.into()),
|
|
||||||
}
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -282,7 +244,7 @@ impl ClientRequest {
|
||||||
/// Set content length
|
/// Set content length
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn content_length(self, len: u64) -> Self {
|
pub fn content_length(self, len: u64) -> Self {
|
||||||
self.header(header::CONTENT_LENGTH, len)
|
self.append_header((header::CONTENT_LENGTH, len))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set HTTP basic authorization header
|
/// Set HTTP basic authorization header
|
||||||
|
@ -294,10 +256,10 @@ impl ClientRequest {
|
||||||
Some(password) => format!("{}:{}", username, password),
|
Some(password) => format!("{}:{}", username, password),
|
||||||
None => format!("{}:", username),
|
None => format!("{}:", username),
|
||||||
};
|
};
|
||||||
self.header(
|
self.append_header((
|
||||||
header::AUTHORIZATION,
|
header::AUTHORIZATION,
|
||||||
format!("Basic {}", base64::encode(&auth)),
|
format!("Basic {}", base64::encode(&auth)),
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set HTTP bearer authentication header
|
/// Set HTTP bearer authentication header
|
||||||
|
@ -305,7 +267,7 @@ impl ClientRequest {
|
||||||
where
|
where
|
||||||
T: fmt::Display,
|
T: fmt::Display,
|
||||||
{
|
{
|
||||||
self.header(header::AUTHORIZATION, format!("Bearer {}", token))
|
self.append_header((header::AUTHORIZATION, format!("Bearer {}", token)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a cookie
|
/// Set a cookie
|
||||||
|
@ -557,12 +519,15 @@ impl ClientRequest {
|
||||||
.unwrap_or(true);
|
.unwrap_or(true);
|
||||||
|
|
||||||
if https {
|
if https {
|
||||||
slf = slf.set_header_if_none(header::ACCEPT_ENCODING, HTTPS_ENCODING)
|
slf =
|
||||||
|
slf.insert_header_if_none((header::ACCEPT_ENCODING, HTTPS_ENCODING))
|
||||||
} else {
|
} else {
|
||||||
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
|
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
|
||||||
{
|
{
|
||||||
slf =
|
slf = slf.insert_header_if_none((
|
||||||
slf.set_header_if_none(header::ACCEPT_ENCODING, "gzip, deflate")
|
header::ACCEPT_ENCODING,
|
||||||
|
"gzip, deflate",
|
||||||
|
))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -595,7 +560,7 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_debug() {
|
async fn test_debug() {
|
||||||
let request = Client::new().get("/").header("x-test", "111");
|
let request = Client::new().get("/").append_header("x-test", "111");
|
||||||
let repr = format!("{:?}", request);
|
let repr = format!("{:?}", request);
|
||||||
assert!(repr.contains("ClientRequest"));
|
assert!(repr.contains("ClientRequest"));
|
||||||
assert!(repr.contains("x-test"));
|
assert!(repr.contains("x-test"));
|
||||||
|
@ -608,16 +573,16 @@ mod tests {
|
||||||
.version(Version::HTTP_2)
|
.version(Version::HTTP_2)
|
||||||
.set(header::Date(SystemTime::now().into()))
|
.set(header::Date(SystemTime::now().into()))
|
||||||
.content_type("plain/text")
|
.content_type("plain/text")
|
||||||
.header(header::SERVER, "awc");
|
.append_header(header::SERVER, "awc");
|
||||||
|
|
||||||
let req = if let Some(val) = Some("server") {
|
let req = if let Some(val) = Some("server") {
|
||||||
req.header(header::USER_AGENT, val)
|
req.append_header(header::USER_AGENT, val)
|
||||||
} else {
|
} else {
|
||||||
req
|
req
|
||||||
};
|
};
|
||||||
|
|
||||||
let req = if let Some(_val) = Option::<&str>::None {
|
let req = if let Some(_val) = Option::<&str>::None {
|
||||||
req.header(header::ALLOW, "1")
|
req.append_header(header::ALLOW, "1")
|
||||||
} else {
|
} else {
|
||||||
req
|
req
|
||||||
};
|
};
|
||||||
|
@ -660,7 +625,7 @@ mod tests {
|
||||||
.header(header::CONTENT_TYPE, "111")
|
.header(header::CONTENT_TYPE, "111")
|
||||||
.finish()
|
.finish()
|
||||||
.get("/")
|
.get("/")
|
||||||
.set_header(header::CONTENT_TYPE, "222");
|
.insert_header(header::CONTENT_TYPE, "222");
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
req.head
|
req.head
|
||||||
|
|
|
@ -52,7 +52,7 @@ async fn test_simple() {
|
||||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))))
|
.service(web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))))
|
||||||
});
|
});
|
||||||
|
|
||||||
let request = srv.get("/").header("x-test", "111").send();
|
let request = srv.get("/").append_header("x-test", "111").send();
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
@ -82,7 +82,7 @@ async fn test_json() {
|
||||||
|
|
||||||
let request = srv
|
let request = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.header("x-test", "111")
|
.append_header("x-test", "111")
|
||||||
.send_json(&"TEST".to_string());
|
.send_json(&"TEST".to_string());
|
||||||
let response = request.await.unwrap();
|
let response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -99,7 +99,7 @@ async fn test_form() {
|
||||||
let mut data = HashMap::new();
|
let mut data = HashMap::new();
|
||||||
let _ = data.insert("key".to_string(), "TEST".to_string());
|
let _ = data.insert("key".to_string(), "TEST".to_string());
|
||||||
|
|
||||||
let request = srv.get("/").header("x-test", "111").send_form(&data);
|
let request = srv.get("/").append_header("x-test", "111").send_form(&data);
|
||||||
let response = request.await.unwrap();
|
let response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,7 @@ async fn main() -> Result<(), Error> {
|
||||||
// Create request builder, configure request and send
|
// Create request builder, configure request and send
|
||||||
let mut response = client
|
let mut response = client
|
||||||
.get("https://www.rust-lang.org/")
|
.get("https://www.rust-lang.org/")
|
||||||
.header("User-Agent", "Actix-web")
|
.append_header("User-Agent", "Actix-web")
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
|
|
@ -347,25 +347,21 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_option() {
|
async fn test_option() {
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
"application/x-www-form-urlencoded",
|
.data(FormConfig::default().limit(4096))
|
||||||
)
|
.to_http_parts();
|
||||||
.data(FormConfig::default().limit(4096))
|
|
||||||
.to_http_parts();
|
|
||||||
|
|
||||||
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
|
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(r, None);
|
assert_eq!(r, None);
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
"application/x-www-form-urlencoded",
|
.insert_header((header::CONTENT_LENGTH, "9"))
|
||||||
)
|
.set_payload(Bytes::from_static(b"hello=world"))
|
||||||
.header(header::CONTENT_LENGTH, "9")
|
.to_http_parts();
|
||||||
.set_payload(Bytes::from_static(b"hello=world"))
|
|
||||||
.to_http_parts();
|
|
||||||
|
|
||||||
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
|
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
|
||||||
.await
|
.await
|
||||||
|
@ -377,13 +373,11 @@ mod tests {
|
||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
"application/x-www-form-urlencoded",
|
.insert_header((header::CONTENT_LENGTH, "9"))
|
||||||
)
|
.set_payload(Bytes::from_static(b"bye=world"))
|
||||||
.header(header::CONTENT_LENGTH, "9")
|
.to_http_parts();
|
||||||
.set_payload(Bytes::from_static(b"bye=world"))
|
|
||||||
.to_http_parts();
|
|
||||||
|
|
||||||
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
|
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
|
||||||
.await
|
.await
|
||||||
|
@ -393,13 +387,11 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_result() {
|
async fn test_result() {
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
"application/x-www-form-urlencoded",
|
.insert_header((header::CONTENT_LENGTH, "11"))
|
||||||
)
|
.set_payload(Bytes::from_static(b"hello=world"))
|
||||||
.header(header::CONTENT_LENGTH, "11")
|
.to_http_parts();
|
||||||
.set_payload(Bytes::from_static(b"hello=world"))
|
|
||||||
.to_http_parts();
|
|
||||||
|
|
||||||
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
|
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
|
||||||
.await
|
.await
|
||||||
|
@ -412,13 +404,11 @@ mod tests {
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
"application/x-www-form-urlencoded",
|
.insert_header((header::CONTENT_LENGTH, 9))
|
||||||
)
|
.set_payload(Bytes::from_static(b"bye=world"))
|
||||||
.header(header::CONTENT_LENGTH, "9")
|
.to_http_parts();
|
||||||
.set_payload(Bytes::from_static(b"bye=world"))
|
|
||||||
.to_http_parts();
|
|
||||||
|
|
||||||
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
|
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
|
||||||
.await
|
.await
|
||||||
|
|
11
src/guard.rs
11
src/guard.rs
|
@ -330,7 +330,8 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_header() {
|
fn test_header() {
|
||||||
let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked")
|
let req = TestRequest::default()
|
||||||
|
.insert_header((header::TRANSFER_ENCODING, "chunked"))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
|
|
||||||
let pred = Header("transfer-encoding", "chunked");
|
let pred = Header("transfer-encoding", "chunked");
|
||||||
|
@ -346,10 +347,10 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_host() {
|
fn test_host() {
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::HOST,
|
header::HOST,
|
||||||
header::HeaderValue::from_static("www.rust-lang.org"),
|
header::HeaderValue::from_static("www.rust-lang.org"),
|
||||||
)
|
))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
|
|
||||||
let pred = Host("www.rust-lang.org");
|
let pred = Host("www.rust-lang.org");
|
||||||
|
@ -374,10 +375,10 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_host_scheme() {
|
fn test_host_scheme() {
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::HOST,
|
header::HOST,
|
||||||
header::HeaderValue::from_static("https://www.rust-lang.org"),
|
header::HeaderValue::from_static("https://www.rust-lang.org"),
|
||||||
)
|
))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
|
|
||||||
let pred = Host("www.rust-lang.org").scheme("https");
|
let pred = Host("www.rust-lang.org").scheme("https");
|
||||||
|
|
12
src/info.rs
12
src/info.rs
|
@ -200,10 +200,10 @@ mod tests {
|
||||||
assert_eq!(info.host(), "localhost:8080");
|
assert_eq!(info.host(), "localhost:8080");
|
||||||
|
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::FORWARDED,
|
header::FORWARDED,
|
||||||
"for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
|
"for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
|
||||||
)
|
))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
|
|
||||||
let info = req.connection_info();
|
let info = req.connection_info();
|
||||||
|
@ -212,7 +212,7 @@ mod tests {
|
||||||
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
|
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
|
||||||
|
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(header::HOST, "rust-lang.org")
|
.insert_header((header::HOST, "rust-lang.org"))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
|
|
||||||
let info = req.connection_info();
|
let info = req.connection_info();
|
||||||
|
@ -221,20 +221,20 @@ mod tests {
|
||||||
assert_eq!(info.realip_remote_addr(), None);
|
assert_eq!(info.realip_remote_addr(), None);
|
||||||
|
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(X_FORWARDED_FOR, "192.0.2.60")
|
.insert_header((X_FORWARDED_FOR, "192.0.2.60"))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
let info = req.connection_info();
|
let info = req.connection_info();
|
||||||
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
|
assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
|
||||||
|
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(X_FORWARDED_HOST, "192.0.2.60")
|
.insert_header((X_FORWARDED_HOST, "192.0.2.60"))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
let info = req.connection_info();
|
let info = req.connection_info();
|
||||||
assert_eq!(info.host(), "192.0.2.60");
|
assert_eq!(info.host(), "192.0.2.60");
|
||||||
assert_eq!(info.realip_remote_addr(), None);
|
assert_eq!(info.realip_remote_addr(), None);
|
||||||
|
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(X_FORWARDED_PROTO, "https")
|
.insert_header((X_FORWARDED_PROTO, "https"))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
let info = req.connection_info();
|
let info = req.connection_info();
|
||||||
assert_eq!(info.scheme(), "https");
|
assert_eq!(info.scheme(), "https");
|
||||||
|
|
|
@ -212,8 +212,11 @@ mod tests {
|
||||||
|
|
||||||
let req = TestRequest::default().to_srv_request();
|
let req = TestRequest::default().to_srv_request();
|
||||||
let srv = |req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
ok(req
|
ok(req.into_response(
|
||||||
.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish()))
|
HttpResponse::Ok()
|
||||||
|
.insert_header((CONTENT_TYPE, "0002"))
|
||||||
|
.finish(),
|
||||||
|
))
|
||||||
};
|
};
|
||||||
let mut mw = DefaultHeaders::new()
|
let mut mw = DefaultHeaders::new()
|
||||||
.header(CONTENT_TYPE, "0001")
|
.header(CONTENT_TYPE, "0001")
|
||||||
|
|
|
@ -603,7 +603,7 @@ mod tests {
|
||||||
let srv = |req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
ok(req.into_response(
|
ok(req.into_response(
|
||||||
HttpResponse::build(StatusCode::OK)
|
HttpResponse::build(StatusCode::OK)
|
||||||
.header("X-Test", "ttt")
|
.insert_header(("X-Test", "ttt"))
|
||||||
.finish(),
|
.finish(),
|
||||||
))
|
))
|
||||||
};
|
};
|
||||||
|
@ -611,11 +611,12 @@ mod tests {
|
||||||
|
|
||||||
let mut srv = logger.new_transform(srv.into_service()).await.unwrap();
|
let mut srv = logger.new_transform(srv.into_service()).await.unwrap();
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
header::USER_AGENT,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("ACTIX-WEB"),
|
header::USER_AGENT,
|
||||||
)
|
header::HeaderValue::from_static("ACTIX-WEB"),
|
||||||
.to_srv_request();
|
))
|
||||||
|
.to_srv_request();
|
||||||
let _res = srv.call(req).await;
|
let _res = srv.call(req).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -624,7 +625,7 @@ mod tests {
|
||||||
let srv = |req: ServiceRequest| {
|
let srv = |req: ServiceRequest| {
|
||||||
ok(req.into_response(
|
ok(req.into_response(
|
||||||
HttpResponse::build(StatusCode::OK)
|
HttpResponse::build(StatusCode::OK)
|
||||||
.header("X-Test", "ttt")
|
.insert_header(("X-Test", "ttt"))
|
||||||
.finish(),
|
.finish(),
|
||||||
))
|
))
|
||||||
};
|
};
|
||||||
|
@ -633,23 +634,25 @@ mod tests {
|
||||||
|
|
||||||
let mut srv = logger.new_transform(srv.into_service()).await.unwrap();
|
let mut srv = logger.new_transform(srv.into_service()).await.unwrap();
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
header::USER_AGENT,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("ACTIX-WEB"),
|
header::USER_AGENT,
|
||||||
)
|
header::HeaderValue::from_static("ACTIX-WEB"),
|
||||||
.to_srv_request();
|
))
|
||||||
|
.to_srv_request();
|
||||||
let _res = srv.call(req).await.unwrap();
|
let _res = srv.call(req).await.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_url_path() {
|
async fn test_url_path() {
|
||||||
let mut format = Format::new("%T %U");
|
let mut format = Format::new("%T %U");
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
header::USER_AGENT,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("ACTIX-WEB"),
|
header::USER_AGENT,
|
||||||
)
|
header::HeaderValue::from_static("ACTIX-WEB"),
|
||||||
.uri("/test/route/yeah")
|
))
|
||||||
.to_srv_request();
|
.uri("/test/route/yeah")
|
||||||
|
.to_srv_request();
|
||||||
|
|
||||||
let now = OffsetDateTime::now_utc();
|
let now = OffsetDateTime::now_utc();
|
||||||
for unit in &mut format.0 {
|
for unit in &mut format.0 {
|
||||||
|
@ -676,12 +679,13 @@ mod tests {
|
||||||
async fn test_default_format() {
|
async fn test_default_format() {
|
||||||
let mut format = Format::default();
|
let mut format = Format::default();
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
header::USER_AGENT,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("ACTIX-WEB"),
|
header::USER_AGENT,
|
||||||
)
|
header::HeaderValue::from_static("ACTIX-WEB"),
|
||||||
.peer_addr("127.0.0.1:8081".parse().unwrap())
|
))
|
||||||
.to_srv_request();
|
.peer_addr("127.0.0.1:8081".parse().unwrap())
|
||||||
|
.to_srv_request();
|
||||||
|
|
||||||
let now = OffsetDateTime::now_utc();
|
let now = OffsetDateTime::now_utc();
|
||||||
for unit in &mut format.0 {
|
for unit in &mut format.0 {
|
||||||
|
@ -736,13 +740,14 @@ mod tests {
|
||||||
async fn test_remote_addr_format() {
|
async fn test_remote_addr_format() {
|
||||||
let mut format = Format::new("%{r}a");
|
let mut format = Format::new("%{r}a");
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
header::FORWARDED,
|
.insert_header((
|
||||||
header::HeaderValue::from_static(
|
header::FORWARDED,
|
||||||
"for=192.0.2.60;proto=http;by=203.0.113.43",
|
header::HeaderValue::from_static(
|
||||||
),
|
"for=192.0.2.60;proto=http;by=203.0.113.43",
|
||||||
)
|
),
|
||||||
.to_srv_request();
|
))
|
||||||
|
.to_srv_request();
|
||||||
|
|
||||||
let now = OffsetDateTime::now_utc();
|
let now = OffsetDateTime::now_utc();
|
||||||
for unit in &mut format.0 {
|
for unit in &mut format.0 {
|
||||||
|
|
|
@ -423,8 +423,9 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_debug() {
|
fn test_debug() {
|
||||||
let req =
|
let req = TestRequest::default()
|
||||||
TestRequest::with_header("content-type", "text/plain").to_http_request();
|
.insert_header(("content-type", "text/plain"))
|
||||||
|
.to_http_request();
|
||||||
let dbg = format!("{:?}", req);
|
let dbg = format!("{:?}", req);
|
||||||
assert!(dbg.contains("HttpRequest"));
|
assert!(dbg.contains("HttpRequest"));
|
||||||
}
|
}
|
||||||
|
@ -438,8 +439,8 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_request_cookies() {
|
fn test_request_cookies() {
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.header(header::COOKIE, "cookie1=value1")
|
.insert_header((header::COOKIE, "cookie1=value1"))
|
||||||
.header(header::COOKIE, "cookie2=value2")
|
.insert_header((header::COOKIE, "cookie2=value2"))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
{
|
{
|
||||||
let cookies = req.cookies().unwrap();
|
let cookies = req.cookies().unwrap();
|
||||||
|
@ -476,7 +477,8 @@ mod tests {
|
||||||
assert!(rmap.has_resource("/user/test.html"));
|
assert!(rmap.has_resource("/user/test.html"));
|
||||||
assert!(!rmap.has_resource("/test/unknown"));
|
assert!(!rmap.has_resource("/test/unknown"));
|
||||||
|
|
||||||
let req = TestRequest::with_header(header::HOST, "www.rust-lang.org")
|
let req = TestRequest::default()
|
||||||
|
.insert_header((header::HOST, "www.rust-lang.org"))
|
||||||
.rmap(rmap)
|
.rmap(rmap)
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
|
|
||||||
|
@ -506,7 +508,7 @@ mod tests {
|
||||||
assert!(rmap.has_resource("/index.html"));
|
assert!(rmap.has_resource("/index.html"));
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/test")
|
let req = TestRequest::with_uri("/test")
|
||||||
.header(header::HOST, "www.rust-lang.org")
|
.insert_header((header::HOST, "www.rust-lang.org"))
|
||||||
.rmap(rmap)
|
.rmap(rmap)
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
let url = req.url_for_static("index");
|
let url = req.url_for_static("index");
|
||||||
|
@ -557,7 +559,7 @@ mod tests {
|
||||||
let mut srv = init_service(App::new().service(web::resource("/").to(
|
let mut srv = init_service(App::new().service(web::resource("/").to(
|
||||||
|req: HttpRequest| {
|
|req: HttpRequest| {
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.set_header("pool_cap", req.app_state().pool().cap)
|
.insert_header(("pool_cap", req.app_state().pool().cap))
|
||||||
.finish()
|
.finish()
|
||||||
},
|
},
|
||||||
)))
|
)))
|
||||||
|
|
|
@ -1,30 +1,11 @@
|
||||||
use std::convert::TryFrom;
|
use std::fmt;
|
||||||
|
|
||||||
use actix_http::error::InternalError;
|
|
||||||
use actix_http::http::{
|
|
||||||
header::IntoHeaderPair, Error as HttpError, HeaderMap, HeaderName, StatusCode,
|
|
||||||
};
|
|
||||||
use actix_http::ResponseBuilder;
|
|
||||||
use bytes::{Bytes, BytesMut};
|
|
||||||
use std::{
|
|
||||||
fmt,
|
|
||||||
future::Future,
|
|
||||||
marker::PhantomData,
|
|
||||||
pin::Pin,
|
|
||||||
task::{Context, Poll},
|
|
||||||
};
|
|
||||||
|
|
||||||
use actix_http::{
|
use actix_http::{
|
||||||
error::InternalError,
|
error::InternalError,
|
||||||
http::{header::IntoHeaderPair, Error as HttpError, HeaderMap, StatusCode},
|
http::{header::IntoHeaderPair, Error as HttpError, HeaderMap, StatusCode},
|
||||||
Error, Response, ResponseBuilder,
|
ResponseBuilder,
|
||||||
};
|
};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures_util::{
|
|
||||||
future::{err, ok, Either as EitherFuture, Ready},
|
|
||||||
ready,
|
|
||||||
};
|
|
||||||
use pin_project::pin_project;
|
|
||||||
|
|
||||||
use crate::{Error, HttpRequest, HttpResponse};
|
use crate::{Error, HttpRequest, HttpResponse};
|
||||||
|
|
||||||
|
@ -73,7 +54,6 @@ pub trait Responder {
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
H: IntoHeaderPair,
|
H: IntoHeaderPair,
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
{
|
||||||
CustomResponder::new(self).with_header(header)
|
CustomResponder::new(self).with_header(header)
|
||||||
}
|
}
|
||||||
|
@ -219,12 +199,12 @@ impl<T: Responder> CustomResponder<T> {
|
||||||
/// fn index(req: HttpRequest) -> impl Responder {
|
/// fn index(req: HttpRequest) -> impl Responder {
|
||||||
/// web::Json(MyObj { name: "Name".to_string() })
|
/// web::Json(MyObj { name: "Name".to_string() })
|
||||||
/// .with_header(("x-version", "1.2.3"))
|
/// .with_header(("x-version", "1.2.3"))
|
||||||
|
/// .with_header(("x-version", "1.2.3"))
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn with_header<H>(mut self, header: H) -> Self
|
pub fn with_header<H>(mut self, header: H) -> Self
|
||||||
where
|
where
|
||||||
H: IntoHeaderPair,
|
H: IntoHeaderPair,
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
{
|
||||||
if self.headers.is_none() {
|
if self.headers.is_none() {
|
||||||
self.headers = Some(HeaderMap::new());
|
self.headers = Some(HeaderMap::new());
|
||||||
|
@ -423,8 +403,7 @@ pub(crate) mod tests {
|
||||||
let res = "test"
|
let res = "test"
|
||||||
.to_string()
|
.to_string()
|
||||||
.with_header(("content-type", "json"))
|
.with_header(("content-type", "json"))
|
||||||
.respond_to(&req)
|
.respond_to(&req);
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(res.status(), StatusCode::OK);
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
assert_eq!(res.body().bin_ref(), b"test");
|
assert_eq!(res.body().bin_ref(), b"test");
|
||||||
|
@ -443,9 +422,8 @@ pub(crate) mod tests {
|
||||||
|
|
||||||
let req = TestRequest::default().to_http_request();
|
let req = TestRequest::default().to_http_request();
|
||||||
let res = ("test".to_string(), StatusCode::OK)
|
let res = ("test".to_string(), StatusCode::OK)
|
||||||
.with_header(CONTENT_TYPE, mime::APPLICATION_JSON)
|
.with_header((CONTENT_TYPE, mime::APPLICATION_JSON))
|
||||||
.respond_to(&req)
|
.respond_to(&req);
|
||||||
.unwrap();
|
|
||||||
assert_eq!(res.status(), StatusCode::OK);
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
assert_eq!(res.body().bin_ref(), b"test");
|
assert_eq!(res.body().bin_ref(), b"test");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|
|
@ -588,14 +588,14 @@ mod tests {
|
||||||
fn test_fmt_debug() {
|
fn test_fmt_debug() {
|
||||||
let req = TestRequest::get()
|
let req = TestRequest::get()
|
||||||
.uri("/index.html?test=1")
|
.uri("/index.html?test=1")
|
||||||
.header("x-test", "111")
|
.insert_header(("x-test", "111"))
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
let s = format!("{:?}", req);
|
let s = format!("{:?}", req);
|
||||||
assert!(s.contains("ServiceRequest"));
|
assert!(s.contains("ServiceRequest"));
|
||||||
assert!(s.contains("test=1"));
|
assert!(s.contains("test=1"));
|
||||||
assert!(s.contains("x-test"));
|
assert!(s.contains("x-test"));
|
||||||
|
|
||||||
let res = HttpResponse::Ok().header("x-test", "111").finish();
|
let res = HttpResponse::Ok().insert_header(("x-test", "111")).finish();
|
||||||
let res = TestRequest::post()
|
let res = TestRequest::post()
|
||||||
.uri("/index.html?test=1")
|
.uri("/index.html?test=1")
|
||||||
.to_srv_response(res);
|
.to_srv_response(res);
|
||||||
|
|
50
src/test.rs
50
src/test.rs
|
@ -7,7 +7,7 @@ use std::{fmt, net, thread, time};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_http::http::header::{ContentType, IntoHeaderPair};
|
use actix_http::http::header::{ContentType, IntoHeaderPair};
|
||||||
use actix_http::http::{Error as HttpError, Method, StatusCode, Uri, Version};
|
use actix_http::http::{Method, StatusCode, Uri, Version};
|
||||||
use actix_http::test::TestRequest as HttpTestRequest;
|
use actix_http::test::TestRequest as HttpTestRequest;
|
||||||
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
|
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
|
||||||
use actix_router::{Path, ResourceDef, Url};
|
use actix_router::{Path, ResourceDef, Url};
|
||||||
|
@ -349,7 +349,7 @@ where
|
||||||
///
|
///
|
||||||
/// #[test]
|
/// #[test]
|
||||||
/// fn test_index() {
|
/// fn test_index() {
|
||||||
/// let req = test::TestRequest::with_header("content-type", "text/plain")
|
/// let req = test::TestRequest::default().insert_header("content-type", "text/plain")
|
||||||
/// .to_http_request();
|
/// .to_http_request();
|
||||||
///
|
///
|
||||||
/// let resp = index(req).await.unwrap();
|
/// let resp = index(req).await.unwrap();
|
||||||
|
@ -389,15 +389,6 @@ impl TestRequest {
|
||||||
TestRequest::default().uri(path)
|
TestRequest::default().uri(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create TestRequest and set header
|
|
||||||
pub fn with_header<H>(header: H) -> TestRequest
|
|
||||||
where
|
|
||||||
H: IntoHeaderPair,
|
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
|
||||||
TestRequest::default().header(header)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create TestRequest and set method to `Method::GET`
|
/// Create TestRequest and set method to `Method::GET`
|
||||||
pub fn get() -> TestRequest {
|
pub fn get() -> TestRequest {
|
||||||
TestRequest::default().method(Method::GET)
|
TestRequest::default().method(Method::GET)
|
||||||
|
@ -441,17 +432,25 @@ impl TestRequest {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a header
|
/// Insert a header, replacing any that were set with an equivalent field name.
|
||||||
pub fn header<H>(mut self, header: H) -> Self
|
pub fn insert_header<H>(mut self, header: H) -> Self
|
||||||
where
|
where
|
||||||
H: IntoHeaderPair,
|
H: IntoHeaderPair,
|
||||||
H::Error: Into<HttpError>,
|
|
||||||
{
|
{
|
||||||
self.req.header(header);
|
self.req.insert_header(header);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set cookie for this request
|
/// Append a header, keeping any that were set with an equivalent field name.
|
||||||
|
pub fn append_header<H>(mut self, header: H) -> Self
|
||||||
|
where
|
||||||
|
H: IntoHeaderPair,
|
||||||
|
{
|
||||||
|
self.req.insert_header(header);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set cookie for this request.
|
||||||
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
||||||
self.req.cookie(cookie);
|
self.req.cookie(cookie);
|
||||||
self
|
self
|
||||||
|
@ -481,7 +480,7 @@ impl TestRequest {
|
||||||
let bytes = serde_urlencoded::to_string(data)
|
let bytes = serde_urlencoded::to_string(data)
|
||||||
.expect("Failed to serialize test data as a urlencoded form");
|
.expect("Failed to serialize test data as a urlencoded form");
|
||||||
self.req.set_payload(bytes);
|
self.req.set_payload(bytes);
|
||||||
self.req.header(ContentType::form_url_encoded());
|
self.req.insert_header(ContentType::form_url_encoded());
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -491,7 +490,7 @@ impl TestRequest {
|
||||||
let bytes =
|
let bytes =
|
||||||
serde_json::to_string(data).expect("Failed to serialize test data to json");
|
serde_json::to_string(data).expect("Failed to serialize test data to json");
|
||||||
self.req.set_payload(bytes);
|
self.req.set_payload(bytes);
|
||||||
self.req.header(ContentType::json());
|
self.req.insert_header(ContentType::json());
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1016,9 +1015,10 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_basics() {
|
async fn test_basics() {
|
||||||
let req = TestRequest::with_hdr(header::ContentType::json())
|
let req = TestRequest::default()
|
||||||
.version(Version::HTTP_2)
|
.version(Version::HTTP_2)
|
||||||
.set(header::Date(SystemTime::now().into()))
|
.insert_header(header::ContentType::json())
|
||||||
|
.insert_header(header::Date(SystemTime::now().into()))
|
||||||
.param("test", "123")
|
.param("test", "123")
|
||||||
.data(10u32)
|
.data(10u32)
|
||||||
.app_data(20u64)
|
.app_data(20u64)
|
||||||
|
@ -1055,7 +1055,7 @@ mod tests {
|
||||||
|
|
||||||
let put_req = TestRequest::put()
|
let put_req = TestRequest::put()
|
||||||
.uri("/index.html")
|
.uri("/index.html")
|
||||||
.header(header::CONTENT_TYPE, "application/json")
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
||||||
.to_request();
|
.to_request();
|
||||||
|
|
||||||
let result = read_response(&mut app, put_req).await;
|
let result = read_response(&mut app, put_req).await;
|
||||||
|
@ -1063,7 +1063,7 @@ mod tests {
|
||||||
|
|
||||||
let patch_req = TestRequest::patch()
|
let patch_req = TestRequest::patch()
|
||||||
.uri("/index.html")
|
.uri("/index.html")
|
||||||
.header(header::CONTENT_TYPE, "application/json")
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
||||||
.to_request();
|
.to_request();
|
||||||
|
|
||||||
let result = read_response(&mut app, patch_req).await;
|
let result = read_response(&mut app, patch_req).await;
|
||||||
|
@ -1086,7 +1086,7 @@ mod tests {
|
||||||
|
|
||||||
let req = TestRequest::post()
|
let req = TestRequest::post()
|
||||||
.uri("/index.html")
|
.uri("/index.html")
|
||||||
.header(header::CONTENT_TYPE, "application/json")
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
||||||
.to_request();
|
.to_request();
|
||||||
|
|
||||||
let result = read_response(&mut app, req).await;
|
let result = read_response(&mut app, req).await;
|
||||||
|
@ -1131,7 +1131,7 @@ mod tests {
|
||||||
|
|
||||||
let req = TestRequest::post()
|
let req = TestRequest::post()
|
||||||
.uri("/people")
|
.uri("/people")
|
||||||
.header(header::CONTENT_TYPE, "application/json")
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
||||||
.set_payload(payload)
|
.set_payload(payload)
|
||||||
.to_request();
|
.to_request();
|
||||||
|
|
||||||
|
@ -1152,7 +1152,7 @@ mod tests {
|
||||||
|
|
||||||
let resp = TestRequest::post()
|
let resp = TestRequest::post()
|
||||||
.uri("/people")
|
.uri("/people")
|
||||||
.header(header::CONTENT_TYPE, "application/json")
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
||||||
.set_payload(payload)
|
.set_payload(payload)
|
||||||
.send_request(&mut app)
|
.send_request(&mut app)
|
||||||
.await;
|
.await;
|
||||||
|
|
|
@ -381,11 +381,11 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_form() {
|
async fn test_form() {
|
||||||
let (req, mut pl) =
|
let (req, mut pl) = TestRequest::default()
|
||||||
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
|
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
.header(CONTENT_LENGTH, "11")
|
.insert_header((CONTENT_LENGTH, 11))
|
||||||
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
|
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
let Form(s) = Form::<Info>::from_request(&req, &mut pl).await.unwrap();
|
let Form(s) = Form::<Info>::from_request(&req, &mut pl).await.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
@ -414,25 +414,26 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_urlencoded_error() {
|
async fn test_urlencoded_error() {
|
||||||
let (req, mut pl) =
|
let (req, mut pl) = TestRequest::default()
|
||||||
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
|
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
.header(CONTENT_LENGTH, "xxxx")
|
.insert_header((CONTENT_LENGTH, "xxxx"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
|
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
|
||||||
assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
|
assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
|
||||||
|
|
||||||
let (req, mut pl) =
|
let (req, mut pl) = TestRequest::default()
|
||||||
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
|
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
.header(CONTENT_LENGTH, "1000000")
|
.insert_header((CONTENT_LENGTH, "1000000"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
|
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
|
||||||
assert!(eq(
|
assert!(eq(
|
||||||
info.err().unwrap(),
|
info.err().unwrap(),
|
||||||
UrlencodedError::Overflow { size: 0, limit: 0 }
|
UrlencodedError::Overflow { size: 0, limit: 0 }
|
||||||
));
|
));
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::with_header(CONTENT_TYPE, "text/plain")
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(CONTENT_LENGTH, "10")
|
.insert_header((CONTENT_TYPE, "text/plain"))
|
||||||
|
.insert_header((CONTENT_LENGTH, 10))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
|
let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
|
||||||
assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
|
assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
|
||||||
|
@ -440,11 +441,11 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_urlencoded() {
|
async fn test_urlencoded() {
|
||||||
let (req, mut pl) =
|
let (req, mut pl) = TestRequest::default()
|
||||||
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
|
.insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
.header(CONTENT_LENGTH, "11")
|
.insert_header((CONTENT_LENGTH, 11))
|
||||||
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
|
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
|
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
@ -455,13 +456,14 @@ mod tests {
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
CONTENT_TYPE,
|
.insert_header((
|
||||||
"application/x-www-form-urlencoded; charset=utf-8",
|
CONTENT_TYPE,
|
||||||
)
|
"application/x-www-form-urlencoded; charset=utf-8",
|
||||||
.header(CONTENT_LENGTH, "11")
|
))
|
||||||
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
|
.insert_header((CONTENT_LENGTH, 11))
|
||||||
.to_http_parts();
|
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
|
||||||
|
.to_http_parts();
|
||||||
|
|
||||||
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
|
let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
@ -497,8 +499,8 @@ mod tests {
|
||||||
let ctype = HeaderValue::from_static("application/x-www-form-urlencoded");
|
let ctype = HeaderValue::from_static("application/x-www-form-urlencoded");
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(CONTENT_TYPE, ctype)
|
.insert_header((CONTENT_TYPE, ctype))
|
||||||
.header(CONTENT_LENGTH, HeaderValue::from_static("20"))
|
.insert_header((CONTENT_LENGTH, HeaderValue::from_static("20")))
|
||||||
.set_payload(Bytes::from_static(b"hello=test&counter=4"))
|
.set_payload(Bytes::from_static(b"hello=test&counter=4"))
|
||||||
.app_data(web::Data::new(FormConfig::default().limit(10)))
|
.app_data(web::Data::new(FormConfig::default().limit(10)))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
|
@ -427,7 +427,7 @@ mod tests {
|
||||||
use crate::{
|
use crate::{
|
||||||
error::InternalError,
|
error::InternalError,
|
||||||
http::{
|
http::{
|
||||||
header::{self, HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
|
header::{self, CONTENT_LENGTH, CONTENT_TYPE},
|
||||||
StatusCode,
|
StatusCode,
|
||||||
},
|
},
|
||||||
test::{load_stream, TestRequest},
|
test::{load_stream, TestRequest},
|
||||||
|
@ -469,14 +469,14 @@ mod tests {
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_custom_error_responder() {
|
async fn test_custom_error_responder() {
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("application/json"),
|
header::HeaderValue::from_static("application/json"),
|
||||||
)
|
))
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_LENGTH,
|
header::CONTENT_LENGTH,
|
||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
))
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
||||||
let msg = MyObject {
|
let msg = MyObject {
|
||||||
|
@ -500,14 +500,14 @@ mod tests {
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_extract() {
|
async fn test_extract() {
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("application/json"),
|
header::HeaderValue::from_static("application/json"),
|
||||||
)
|
))
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_LENGTH,
|
header::CONTENT_LENGTH,
|
||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
))
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
|
@ -521,14 +521,14 @@ mod tests {
|
||||||
);
|
);
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("application/json"),
|
header::HeaderValue::from_static("application/json"),
|
||||||
)
|
))
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_LENGTH,
|
header::CONTENT_LENGTH,
|
||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
))
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.app_data(JsonConfig::default().limit(10))
|
.app_data(JsonConfig::default().limit(10))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
@ -538,14 +538,14 @@ mod tests {
|
||||||
.contains("Json payload size is bigger than allowed"));
|
.contains("Json payload size is bigger than allowed"));
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("application/json"),
|
header::HeaderValue::from_static("application/json"),
|
||||||
)
|
))
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_LENGTH,
|
header::CONTENT_LENGTH,
|
||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
))
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.app_data(
|
.app_data(
|
||||||
JsonConfig::default()
|
JsonConfig::default()
|
||||||
|
@ -564,23 +564,23 @@ mod tests {
|
||||||
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("application/text"),
|
header::HeaderValue::from_static("application/text"),
|
||||||
)
|
))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
|
let json = JsonBody::<MyObject>::new(&req, &mut pl, None).await;
|
||||||
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("application/json"),
|
header::HeaderValue::from_static("application/json"),
|
||||||
)
|
))
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_LENGTH,
|
header::CONTENT_LENGTH,
|
||||||
header::HeaderValue::from_static("10000"),
|
header::HeaderValue::from_static("10000"),
|
||||||
)
|
))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
let json = JsonBody::<MyObject>::new(&req, &mut pl, None)
|
let json = JsonBody::<MyObject>::new(&req, &mut pl, None)
|
||||||
|
@ -589,14 +589,14 @@ mod tests {
|
||||||
assert!(json_eq(json.err().unwrap(), JsonPayloadError::Overflow));
|
assert!(json_eq(json.err().unwrap(), JsonPayloadError::Overflow));
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("application/json"),
|
header::HeaderValue::from_static("application/json"),
|
||||||
)
|
))
|
||||||
.header(
|
.insert_header((
|
||||||
header::CONTENT_LENGTH,
|
header::CONTENT_LENGTH,
|
||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
))
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
|
@ -611,17 +611,18 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_with_json_and_bad_content_type() {
|
async fn test_with_json_and_bad_content_type() {
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("text/plain"),
|
header::CONTENT_TYPE,
|
||||||
)
|
header::HeaderValue::from_static("text/plain"),
|
||||||
.header(
|
))
|
||||||
header::CONTENT_LENGTH,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("16"),
|
header::CONTENT_LENGTH,
|
||||||
)
|
header::HeaderValue::from_static("16"),
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
))
|
||||||
.app_data(JsonConfig::default().limit(4096))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.to_http_parts();
|
.app_data(JsonConfig::default().limit(4096))
|
||||||
|
.to_http_parts();
|
||||||
|
|
||||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||||
assert!(s.is_err())
|
assert!(s.is_err())
|
||||||
|
@ -629,19 +630,20 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_with_json_and_good_custom_content_type() {
|
async fn test_with_json_and_good_custom_content_type() {
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("text/plain"),
|
header::CONTENT_TYPE,
|
||||||
)
|
header::HeaderValue::from_static("text/plain"),
|
||||||
.header(
|
))
|
||||||
header::CONTENT_LENGTH,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("16"),
|
header::CONTENT_LENGTH,
|
||||||
)
|
header::HeaderValue::from_static("16"),
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
))
|
||||||
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||||
}))
|
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||||
.to_http_parts();
|
}))
|
||||||
|
.to_http_parts();
|
||||||
|
|
||||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||||
assert!(s.is_ok())
|
assert!(s.is_ok())
|
||||||
|
@ -649,19 +651,20 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_with_json_and_bad_custom_content_type() {
|
async fn test_with_json_and_bad_custom_content_type() {
|
||||||
let (req, mut pl) = TestRequest::with_header(
|
let (req, mut pl) = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("text/html"),
|
header::CONTENT_TYPE,
|
||||||
)
|
header::HeaderValue::from_static("text/html"),
|
||||||
.header(
|
))
|
||||||
header::CONTENT_LENGTH,
|
.insert_header((
|
||||||
header::HeaderValue::from_static("16"),
|
header::CONTENT_LENGTH,
|
||||||
)
|
header::HeaderValue::from_static("16"),
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
))
|
||||||
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||||
}))
|
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||||
.to_http_parts();
|
}))
|
||||||
|
.to_http_parts();
|
||||||
|
|
||||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||||
assert!(s.is_err())
|
assert!(s.is_err())
|
||||||
|
@ -670,8 +673,8 @@ mod tests {
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_with_config_in_data_wrapper() {
|
async fn test_with_config_in_data_wrapper() {
|
||||||
let (req, mut pl) = TestRequest::default()
|
let (req, mut pl) = TestRequest::default()
|
||||||
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
|
.insert_header((CONTENT_TYPE, mime::APPLICATION_JSON))
|
||||||
.header(CONTENT_LENGTH, HeaderValue::from_static("16"))
|
.insert_header((CONTENT_LENGTH, 16))
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.app_data(web::Data::new(JsonConfig::default().limit(10)))
|
.app_data(web::Data::new(JsonConfig::default().limit(10)))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
|
@ -364,14 +364,13 @@ mod tests {
|
||||||
let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON);
|
let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON);
|
||||||
assert!(cfg.check_mimetype(&req).is_err());
|
assert!(cfg.check_mimetype(&req).is_err());
|
||||||
|
|
||||||
let req = TestRequest::with_header(
|
let req = TestRequest::default()
|
||||||
header::CONTENT_TYPE,
|
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
|
||||||
"application/x-www-form-urlencoded",
|
.to_http_request();
|
||||||
)
|
|
||||||
.to_http_request();
|
|
||||||
assert!(cfg.check_mimetype(&req).is_err());
|
assert!(cfg.check_mimetype(&req).is_err());
|
||||||
|
|
||||||
let req = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
|
let req = TestRequest::default()
|
||||||
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
assert!(cfg.check_mimetype(&req).is_ok());
|
assert!(cfg.check_mimetype(&req).is_ok());
|
||||||
}
|
}
|
||||||
|
@ -432,25 +431,25 @@ mod tests {
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/bytes-app-data")
|
let req = TestRequest::with_uri("/bytes-app-data")
|
||||||
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
|
.insert_header(header::ContentType(mime::APPLICATION_JSON))
|
||||||
.to_request();
|
.to_request();
|
||||||
let resp = call_service(&mut srv, req).await;
|
let resp = call_service(&mut srv, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/bytes-data")
|
let req = TestRequest::with_uri("/bytes-data")
|
||||||
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
|
.insert_header(header::ContentType(mime::APPLICATION_JSON))
|
||||||
.to_request();
|
.to_request();
|
||||||
let resp = call_service(&mut srv, req).await;
|
let resp = call_service(&mut srv, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/string-app-data")
|
let req = TestRequest::with_uri("/string-app-data")
|
||||||
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
|
.insert_header(header::ContentType(mime::APPLICATION_JSON))
|
||||||
.to_request();
|
.to_request();
|
||||||
let resp = call_service(&mut srv, req).await;
|
let resp = call_service(&mut srv, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/string-data")
|
let req = TestRequest::with_uri("/string-data")
|
||||||
.header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
|
.insert_header(header::ContentType(mime::APPLICATION_JSON))
|
||||||
.to_request();
|
.to_request();
|
||||||
let resp = call_service(&mut srv, req).await;
|
let resp = call_service(&mut srv, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
@ -458,7 +457,8 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_bytes() {
|
async fn test_bytes() {
|
||||||
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
|
let (req, mut pl) = TestRequest::default()
|
||||||
|
.insert_header((header::CONTENT_LENGTH, "11"))
|
||||||
.set_payload(Bytes::from_static(b"hello=world"))
|
.set_payload(Bytes::from_static(b"hello=world"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
|
@ -468,7 +468,8 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_string() {
|
async fn test_string() {
|
||||||
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
|
let (req, mut pl) = TestRequest::default()
|
||||||
|
.insert_header((header::CONTENT_LENGTH, "11"))
|
||||||
.set_payload(Bytes::from_static(b"hello=world"))
|
.set_payload(Bytes::from_static(b"hello=world"))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
|
@ -478,7 +479,8 @@ mod tests {
|
||||||
|
|
||||||
#[actix_rt::test]
|
#[actix_rt::test]
|
||||||
async fn test_message_body() {
|
async fn test_message_body() {
|
||||||
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx")
|
let (req, mut pl) = TestRequest::default()
|
||||||
|
.insert_header((header::CONTENT_LENGTH, "xxxx"))
|
||||||
.to_srv_request()
|
.to_srv_request()
|
||||||
.into_parts();
|
.into_parts();
|
||||||
let res = HttpMessageBody::new(&req, &mut pl).await;
|
let res = HttpMessageBody::new(&req, &mut pl).await;
|
||||||
|
@ -487,7 +489,8 @@ mod tests {
|
||||||
_ => unreachable!("error"),
|
_ => unreachable!("error"),
|
||||||
}
|
}
|
||||||
|
|
||||||
let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "1000000")
|
let (req, mut pl) = TestRequest::default()
|
||||||
|
.insert_header((header::CONTENT_LENGTH, "1000000"))
|
||||||
.to_srv_request()
|
.to_srv_request()
|
||||||
.into_parts();
|
.into_parts();
|
||||||
let res = HttpMessageBody::new(&req, &mut pl).await;
|
let res = HttpMessageBody::new(&req, &mut pl).await;
|
||||||
|
|
|
@ -108,7 +108,7 @@ async fn test_body_gzip() {
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.header(ACCEPT_ENCODING, "gzip")
|
.append_header((ACCEPT_ENCODING, "gzip"))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -137,7 +137,7 @@ async fn test_body_gzip2() {
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.header(ACCEPT_ENCODING, "gzip")
|
.append_header((ACCEPT_ENCODING, "gzip"))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -178,7 +178,7 @@ async fn test_body_encoding_override() {
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.header(ACCEPT_ENCODING, "deflate")
|
.append_header((ACCEPT_ENCODING, "deflate"))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -197,7 +197,7 @@ async fn test_body_encoding_override() {
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.request(actix_web::http::Method::GET, srv.url("/raw"))
|
.request(actix_web::http::Method::GET, srv.url("/raw"))
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.header(ACCEPT_ENCODING, "deflate")
|
.append_header((ACCEPT_ENCODING, "deflate"))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -231,7 +231,7 @@ async fn test_body_gzip_large() {
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.header(ACCEPT_ENCODING, "gzip")
|
.append_header((ACCEPT_ENCODING, "gzip"))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -269,7 +269,7 @@ async fn test_body_gzip_large_random() {
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.header(ACCEPT_ENCODING, "gzip")
|
.append_header((ACCEPT_ENCODING, "gzip"))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -300,7 +300,7 @@ async fn test_body_chunked_implicit() {
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.header(ACCEPT_ENCODING, "gzip")
|
.append_header((ACCEPT_ENCODING, "gzip"))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -333,7 +333,7 @@ async fn test_body_br_streaming() {
|
||||||
|
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.header(ACCEPT_ENCODING, "br")
|
.append_header((ACCEPT_ENCODING, "br"))
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
@ -406,7 +406,7 @@ async fn test_body_deflate() {
|
||||||
// client request
|
// client request
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.header(ACCEPT_ENCODING, "deflate")
|
.append_header((ACCEPT_ENCODING, "deflate"))
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
@ -433,7 +433,7 @@ async fn test_body_brotli() {
|
||||||
// client request
|
// client request
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.get("/")
|
.get("/")
|
||||||
.header(ACCEPT_ENCODING, "br")
|
.append_header((ACCEPT_ENCODING, "br"))
|
||||||
.no_decompress()
|
.no_decompress()
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
@ -466,7 +466,7 @@ async fn test_encoding() {
|
||||||
|
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "gzip")
|
.insert_header((CONTENT_ENCODING, "gzip"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -492,7 +492,7 @@ async fn test_gzip_encoding() {
|
||||||
|
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "gzip")
|
.append_header((CONTENT_ENCODING, "gzip"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -519,7 +519,7 @@ async fn test_gzip_encoding_large() {
|
||||||
|
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "gzip")
|
.append_header((CONTENT_ENCODING, "gzip"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -551,7 +551,7 @@ async fn test_reading_gzip_encoding_large_random() {
|
||||||
|
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "gzip")
|
.append_header((CONTENT_ENCODING, "gzip"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -578,7 +578,7 @@ async fn test_reading_deflate_encoding() {
|
||||||
// client request
|
// client request
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "deflate")
|
.append_header((CONTENT_ENCODING, "deflate"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -605,7 +605,7 @@ async fn test_reading_deflate_encoding_large() {
|
||||||
// client request
|
// client request
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "deflate")
|
.append_header((CONTENT_ENCODING, "deflate"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -637,7 +637,7 @@ async fn test_reading_deflate_encoding_large_random() {
|
||||||
// client request
|
// client request
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "deflate")
|
.append_header((CONTENT_ENCODING, "deflate"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -664,7 +664,7 @@ async fn test_brotli_encoding() {
|
||||||
// client request
|
// client request
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "br")
|
.append_header((CONTENT_ENCODING, "br"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -699,7 +699,7 @@ async fn test_brotli_encoding_large() {
|
||||||
// client request
|
// client request
|
||||||
let request = srv
|
let request = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(CONTENT_ENCODING, "br")
|
.append_header((CONTENT_ENCODING, "br"))
|
||||||
.send_body(enc.clone());
|
.send_body(enc.clone());
|
||||||
let mut response = request.await.unwrap();
|
let mut response = request.await.unwrap();
|
||||||
assert!(response.status().is_success());
|
assert!(response.status().is_success());
|
||||||
|
@ -739,7 +739,7 @@ async fn test_brotli_encoding_large_openssl() {
|
||||||
// client request
|
// client request
|
||||||
let mut response = srv
|
let mut response = srv
|
||||||
.post("/")
|
.post("/")
|
||||||
.header(actix_web::http::header::CONTENT_ENCODING, "br")
|
.append_header((actix_web::http::header::CONTENT_ENCODING, "br"))
|
||||||
.send_body(enc)
|
.send_body(enc)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
Loading…
Reference in New Issue