1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-27 17:22:57 +01:00

clippy fmt

This commit is contained in:
Nikolay Kim 2018-08-23 09:48:01 -07:00
parent e9c139bdea
commit 1716380f08
41 changed files with 616 additions and 617 deletions

View File

@ -776,8 +776,7 @@ mod tests {
.route("/test", Method::GET, |_: HttpRequest| HttpResponse::Ok())
.route("/test", Method::POST, |_: HttpRequest| {
HttpResponse::Created()
})
.finish();
}).finish();
let req = TestRequest::with_uri("/test").method(Method::GET).request();
let resp = app.run(req);

View File

@ -768,168 +768,161 @@ impl ClientConnector {
).map_err(move |_, act, _| {
act.release_key(&key2);
()
})
.and_then(move |res, act, _| {
#[cfg(feature = "alpn")]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::Either::B(fut::err(()))
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
fut::Either::A(
act.connector
.connect_async(&key.host, stream)
.into_actor(act)
.then(move |res, _, _| {
match res {
Err(e) => {
let _ = waiter.tx.send(Err(
ClientConnectorError::SslError(e),
));
}
Ok(stream) => {
let _ =
waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
}
}).and_then(move |res, act, _| {
#[cfg(feature = "alpn")]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::Either::B(fut::err(()))
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
fut::Either::A(
act.connector
.connect_async(&key.host, stream)
.into_actor(act)
.then(move |res, _, _| {
match res {
Err(e) => {
let _ = waiter.tx.send(Err(
ClientConnectorError::SslError(e),
));
}
fut::ok(())
}),
)
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
fut::Either::B(fut::ok(()))
}
}
}
#[cfg(all(feature = "tls", not(feature = "alpn")))]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::Either::B(fut::err(()))
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
fut::Either::A(
act.connector
.connect_async(&conn.0.host, stream)
.into_actor(act)
.then(move |res, _, _| {
match res {
Err(e) => {
let _ = waiter.tx.send(Err(
ClientConnectorError::SslError(e),
));
}
Ok(stream) => {
let _ =
waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
}
Ok(stream) => {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
}
fut::ok(())
}),
)
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
fut::Either::B(fut::ok(()))
}
}
fut::ok(())
}),
)
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
fut::Either::B(fut::ok(()))
}
}
}
#[cfg(
all(
feature = "rust-tls",
not(any(feature = "alpn", feature = "tls"))
)
)]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::Either::B(fut::err(()))
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
let host =
DNSNameRef::try_from_ascii_str(&key.host).unwrap();
fut::Either::A(
act.connector
.connect_async(host, stream)
.into_actor(act)
.then(move |res, _, _| {
match res {
Err(e) => {
let _ = waiter.tx.send(Err(
ClientConnectorError::SslError(e),
));
}
Ok(stream) => {
let _ =
waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
}
#[cfg(all(feature = "tls", not(feature = "alpn")))]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::Either::B(fut::err(()))
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
fut::Either::A(
act.connector
.connect_async(&conn.0.host, stream)
.into_actor(act)
.then(move |res, _, _| {
match res {
Err(e) => {
let _ = waiter.tx.send(Err(
ClientConnectorError::SslError(e),
));
}
fut::ok(())
}),
)
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
fut::Either::B(fut::ok(()))
}
Ok(stream) => {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
}
}
fut::ok(())
}),
)
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
fut::Either::B(fut::ok(()))
}
}
}
#[cfg(not(any(feature = "alpn", feature = "tls", feature = "rust-tls")))]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::err(())
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
let _ = waiter
.tx
.send(Err(ClientConnectorError::SslIsNotSupported));
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
};
fut::ok(())
#[cfg(
all(
feature = "rust-tls",
not(any(feature = "alpn", feature = "tls"))
)
)]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::Either::B(fut::err(()))
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
let host = DNSNameRef::try_from_ascii_str(&key.host).unwrap();
fut::Either::A(
act.connector
.connect_async(host, stream)
.into_actor(act)
.then(move |res, _, _| {
match res {
Err(e) => {
let _ = waiter.tx.send(Err(
ClientConnectorError::SslError(e),
));
}
Ok(stream) => {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
}
}
fut::ok(())
}),
)
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
fut::Either::B(fut::ok(()))
}
}
})
.spawn(ctx);
}
#[cfg(not(any(feature = "alpn", feature = "tls", feature = "rust-tls")))]
match res {
Err(err) => {
let _ = waiter.tx.send(Err(err.into()));
fut::err(())
}
Ok(stream) => {
act.stats.opened += 1;
if conn.0.ssl {
let _ =
waiter.tx.send(Err(ClientConnectorError::SslIsNotSupported));
} else {
let _ = waiter.tx.send(Ok(Connection::new(
conn.0.clone(),
Some(conn),
Box::new(stream),
)));
};
fut::ok(())
}
}
}).spawn(ctx);
}
}

View File

@ -302,10 +302,9 @@ fn content_encoder(buf: BytesMut, req: &mut ClientRequest) -> Output {
req.replace_body(body);
let enc = match encoding {
#[cfg(feature = "flate2")]
ContentEncoding::Deflate => ContentEncoder::Deflate(ZlibEncoder::new(
transfer,
Compression::default(),
)),
ContentEncoding::Deflate => {
ContentEncoder::Deflate(ZlibEncoder::new(transfer, Compression::default()))
}
#[cfg(feature = "flate2")]
ContentEncoding::Gzip => {
ContentEncoder::Gzip(GzEncoder::new(transfer, Compression::default()))

View File

@ -103,7 +103,7 @@ impl<T> Path<T> {
impl<T> From<T> for Path<T> {
fn from(inner: T) -> Path<T> {
Path{inner}
Path { inner }
}
}
@ -802,8 +802,8 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
let mut cfg = FormConfig::default();
cfg.limit(4096);
@ -837,8 +837,8 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "9")
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
match Option::<Form<Info>>::from_request(&req, &cfg)
.poll()
@ -857,8 +857,8 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "9")
.set_payload(Bytes::from_static(b"bye=world"))
.finish();
.set_payload(Bytes::from_static(b"bye=world"))
.finish();
match Option::<Form<Info>>::from_request(&req, &cfg)
.poll()
@ -875,8 +875,8 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
match Result::<Form<Info>, Error>::from_request(&req, &FormConfig::default())
.poll()
@ -895,8 +895,8 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "9")
.set_payload(Bytes::from_static(b"bye=world"))
.finish();
.set_payload(Bytes::from_static(b"bye=world"))
.finish();
match Result::<Form<Info>, Error>::from_request(&req, &FormConfig::default())
.poll()

View File

@ -369,11 +369,7 @@ impl<C: StaticFileConfig> Responder for NamedFile<C> {
.body("This resource only supports GET and HEAD."));
}
let etag = if C::is_use_etag() {
self.etag()
} else {
None
};
let etag = if C::is_use_etag() { self.etag() } else { None };
let last_modified = if C::is_use_last_modifier() {
self.last_modified()
} else {
@ -518,7 +514,8 @@ impl Stream for ChunkedReadFile {
max_bytes = cmp::min(size.saturating_sub(counter), 65_536) as usize;
let mut buf = Vec::with_capacity(max_bytes);
file.seek(io::SeekFrom::Start(offset))?;
let nbytes = file.by_ref().take(max_bytes as u64).read_to_end(&mut buf)?;
let nbytes =
file.by_ref().take(max_bytes as u64).read_to_end(&mut buf)?;
if nbytes == 0 {
return Err(io::ErrorKind::UnexpectedEof.into());
}
@ -869,8 +866,7 @@ impl HttpRange {
length: length as u64,
}))
}
})
.collect::<Result<_, _>>()?;
}).collect::<Result<_, _>>()?;
let ranges: Vec<HttpRange> = all_ranges.into_iter().filter_map(|x| x).collect();
@ -986,9 +982,7 @@ mod tests {
use header::{ContentDisposition, DispositionParam, DispositionType};
let cd = ContentDisposition {
disposition: DispositionType::Attachment,
parameters: vec![DispositionParam::Filename(
String::from("test.png")
)],
parameters: vec![DispositionParam::Filename(String::from("test.png"))],
};
let mut file = NamedFile::open("tests/test.png")
.unwrap()

View File

@ -354,15 +354,16 @@ impl<T, E: Into<Error>> From<Result<T, E>> for AsyncResult<T> {
}
impl<T, E> From<Result<Box<Future<Item = T, Error = E>>, E>> for AsyncResult<T>
where T: 'static,
E: Into<Error> + 'static
where
T: 'static,
E: Into<Error> + 'static,
{
#[inline]
fn from(res: Result<Box<Future<Item = T, Error = E>>, E>) -> Self {
match res {
Ok(fut) => AsyncResult(
Some(AsyncResultItem::Future(
Box::new(fut.map_err(|e| e.into()))))),
Ok(fut) => AsyncResult(Some(AsyncResultItem::Future(Box::new(
fut.map_err(|e| e.into()),
)))),
Err(err) => AsyncResult(Some(AsyncResultItem::Err(err.into()))),
}
}

View File

@ -223,8 +223,7 @@ pub fn from_comma_delimited<T: FromStr>(
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y),
})
.filter_map(|x| x.trim().parse().ok()),
}).filter_map(|x| x.trim().parse().ok()),
)
}
Ok(result)

View File

@ -279,8 +279,7 @@ mod tests {
true,
StatusCode::MOVED_PERMANENTLY,
))
})
.finish();
}).finish();
// trailing slashes
let params = vec![

View File

@ -479,8 +479,7 @@ where
body.extend_from_slice(&chunk);
Ok(body)
}
})
.map(|body| body.freeze()),
}).map(|body| body.freeze()),
));
self.poll()
}
@ -588,8 +587,7 @@ where
body.extend_from_slice(&chunk);
Ok(body)
}
})
.and_then(move |body| {
}).and_then(move |body| {
if (encoding as *const Encoding) == UTF_8 {
serde_urlencoded::from_bytes::<U>(&body)
.map_err(|_| UrlencodedError::Parse)
@ -694,8 +692,7 @@ mod tests {
.header(
header::TRANSFER_ENCODING,
Bytes::from_static(b"some va\xadscc\xacas0xsdasdlue"),
)
.finish();
).finish();
assert!(req.chunked().is_err());
}
@ -734,7 +731,7 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "xxxx")
.finish();
.finish();
assert_eq!(
req.urlencoded::<Info>().poll().err().unwrap(),
UrlencodedError::UnknownLength
@ -744,7 +741,7 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "1000000")
.finish();
.finish();
assert_eq!(
req.urlencoded::<Info>().poll().err().unwrap(),
UrlencodedError::Overflow
@ -765,8 +762,8 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
let result = req.urlencoded::<Info>().poll().ok().unwrap();
assert_eq!(
@ -780,8 +777,8 @@ mod tests {
header::CONTENT_TYPE,
"application/x-www-form-urlencoded; charset=utf-8",
).header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
.set_payload(Bytes::from_static(b"hello=world"))
.finish();
let result = req.urlencoded().poll().ok().unwrap();
assert_eq!(
@ -830,8 +827,7 @@ mod tests {
b"Lorem Ipsum is simply dummy text of the printing and typesetting\n\
industry. Lorem Ipsum has been the industry's standard dummy\n\
Contrary to popular belief, Lorem Ipsum is not simply random text.",
))
.finish();
)).finish();
let mut r = Readlines::new(&req);
match r.poll().ok().unwrap() {
Async::Ready(Some(s)) => assert_eq!(

View File

@ -264,7 +264,8 @@ impl<S> HttpRequest<S> {
if self.extensions().get::<Cookies>().is_none() {
let mut cookies = Vec::new();
for hdr in self.request().inner.headers.get_all(header::COOKIE) {
let s = str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
let s =
str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
for cookie_str in s.split(';').map(|s| s.trim()) {
if !cookie_str.is_empty() {
cookies.push(Cookie::parse_encoded(cookie_str)?.into_owned());

View File

@ -142,8 +142,7 @@ impl HttpResponse {
HeaderValue::from_str(&cookie.to_string())
.map(|c| {
h.append(header::SET_COOKIE, c);
})
.map_err(|e| e.into())
}).map_err(|e| e.into())
}
/// Remove all cookies with the given name from this response. Returns
@ -1079,8 +1078,7 @@ mod tests {
.http_only(true)
.max_age(Duration::days(1))
.finish(),
)
.del_cookie(&cookies[0])
).del_cookie(&cookies[0])
.finish();
let mut val: Vec<_> = resp

View File

@ -174,8 +174,7 @@ mod tests {
.header(
header::FORWARDED,
"for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
)
.request();
).request();
let mut info = ConnectionInfo::default();
info.update(&req);

View File

@ -327,8 +327,7 @@ impl<T: HttpMessage + 'static, U: DeserializeOwned + 'static> Future for JsonBod
body.extend_from_slice(&chunk);
Ok(body)
}
})
.and_then(|body| Ok(serde_json::from_slice::<U>(&body)?));
}).and_then(|body| Ok(serde_json::from_slice::<U>(&body)?));
self.fut = Some(Box::new(fut));
self.poll()
}
@ -388,8 +387,7 @@ mod tests {
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/text"),
)
.finish();
).finish();
let mut json = req.json::<MyObject>();
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType);
@ -397,12 +395,10 @@ mod tests {
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
).header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("10000"),
)
.finish();
).finish();
let mut json = req.json::<MyObject>().limit(100);
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::Overflow);
@ -410,12 +406,10 @@ mod tests {
.header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
)
.header(
).header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
).set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();
let mut json = req.json::<MyObject>();
@ -442,9 +436,8 @@ mod tests {
).header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();
).set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish();
assert!(handler.handle(&req).as_err().is_none())
}
}

View File

@ -127,7 +127,6 @@ extern crate tokio_uds;
extern crate url;
#[macro_use]
extern crate serde;
extern crate serde_urlencoded;
#[cfg(feature = "brotli")]
extern crate brotli2;
extern crate encoding;
@ -135,6 +134,7 @@ extern crate encoding;
extern crate flate2;
extern crate h2 as http2;
extern crate num_cpus;
extern crate serde_urlencoded;
#[macro_use]
extern crate percent_encoding;
extern crate serde_json;
@ -256,12 +256,12 @@ pub mod dev {
pub use extractor::{FormConfig, PayloadConfig};
pub use handler::{AsyncResult, Handler};
pub use httpmessage::{MessageBody, Readlines, UrlEncoded};
pub use pipeline::Pipeline;
pub use httpresponse::HttpResponseBuilder;
pub use info::ConnectionInfo;
pub use json::{JsonBody, JsonConfig};
pub use param::{FromParam, Params};
pub use payload::{Payload, PayloadBuffer};
pub use pipeline::Pipeline;
pub use resource::Resource;
pub use route::Route;
pub use router::{ResourceDef, ResourceInfo, ResourceType, Router};
@ -283,7 +283,9 @@ pub mod http {
/// Various http headers
pub mod header {
pub use header::*;
pub use header::{ContentDisposition, DispositionType, DispositionParam, Charset, LanguageTag};
pub use header::{
Charset, ContentDisposition, DispositionParam, DispositionType, LanguageTag,
};
}
pub use header::ContentEncoding;
pub use httpresponse::ConnectionType;

View File

@ -387,12 +387,10 @@ impl<S> Middleware<S> for Cors {
header::ACCESS_CONTROL_MAX_AGE,
format!("{}", max_age).as_str(),
);
})
.if_some(headers, |headers, resp| {
}).if_some(headers, |headers, resp| {
let _ =
resp.header(header::ACCESS_CONTROL_ALLOW_HEADERS, headers);
})
.if_true(self.inner.origins.is_all(), |resp| {
}).if_true(self.inner.origins.is_all(), |resp| {
if self.inner.send_wildcard {
resp.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*");
} else {
@ -402,17 +400,14 @@ impl<S> Middleware<S> for Cors {
origin.clone(),
);
}
})
.if_true(self.inner.origins.is_some(), |resp| {
}).if_true(self.inner.origins.is_some(), |resp| {
resp.header(
header::ACCESS_CONTROL_ALLOW_ORIGIN,
self.inner.origins_str.as_ref().unwrap().clone(),
);
})
.if_true(self.inner.supports_credentials, |resp| {
}).if_true(self.inner.supports_credentials, |resp| {
resp.header(header::ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
})
.header(
}).header(
header::ACCESS_CONTROL_ALLOW_METHODS,
&self
.inner
@ -420,8 +415,7 @@ impl<S> Middleware<S> for Cors {
.iter()
.fold(String::new(), |s, v| s + "," + v.as_str())
.as_str()[1..],
)
.finish(),
).finish(),
))
} else {
// Only check requests with a origin header.
@ -838,9 +832,10 @@ impl<S: 'static> CorsBuilder<S> {
if !self.expose_hdrs.is_empty() {
cors.expose_hdrs = Some(
self.expose_hdrs.iter()
self.expose_hdrs
.iter()
.fold(String::new(), |s, v| format!("{}, {}", s, v.as_str()))[2..]
.to_owned()
.to_owned(),
);
}
Cors {
@ -977,8 +972,7 @@ mod tests {
.header(
header::ACCESS_CONTROL_REQUEST_HEADERS,
"AUTHORIZATION,ACCEPT",
)
.method(Method::OPTIONS)
).method(Method::OPTIONS)
.finish();
let resp = cors.start(&req).unwrap().response();
@ -1102,7 +1096,8 @@ mod tests {
);
{
let headers = resp.headers()
let headers = resp
.headers()
.get(header::ACCESS_CONTROL_EXPOSE_HEADERS)
.unwrap()
.to_str()

View File

@ -93,8 +93,7 @@ fn origin(headers: &HeaderMap) -> Option<Result<Cow<str>, CsrfError>> {
.to_str()
.map_err(|_| CsrfError::BadOrigin)
.map(|o| o.into())
})
.or_else(|| {
}).or_else(|| {
headers.get(header::REFERER).map(|referer| {
Uri::try_from(Bytes::from(referer.as_bytes()))
.ok()
@ -251,7 +250,7 @@ mod tests {
"Referer",
"https://www.example.com/some/path?query=param",
).method(Method::POST)
.finish();
.finish();
assert!(csrf.start(&req).is_ok());
}

View File

@ -131,7 +131,7 @@ mod tests {
ErrorHandlers::new()
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500),
).middleware(MiddlewareOne)
.handler(|_| HttpResponse::Ok())
.handler(|_| HttpResponse::Ok())
});
let request = srv.get().finish().unwrap();

View File

@ -579,8 +579,7 @@ mod tests {
App::new()
.middleware(SessionStorage::new(
CookieSessionBackend::signed(&[0; 32]).secure(false),
))
.resource("/", |r| {
)).resource("/", |r| {
r.f(|req| {
let _ = req.session().set("counter", 100);
"test"
@ -599,8 +598,7 @@ mod tests {
App::new()
.middleware(SessionStorage::new(
CookieSessionBackend::signed(&[0; 32]).secure(false),
))
.resource("/", |r| {
)).resource("/", |r| {
r.with(|ses: Session| {
let _ = ses.set("counter", 100);
"test"

View File

@ -756,10 +756,7 @@ mod tests {
{
use http::header::{DispositionParam, DispositionType};
let cd = field.content_disposition().unwrap();
assert_eq!(
cd.disposition,
DispositionType::FormData
);
assert_eq!(cd.disposition, DispositionType::FormData);
assert_eq!(
cd.parameters[0],
DispositionParam::Name("file".into())
@ -813,7 +810,6 @@ mod tests {
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
}

View File

@ -236,7 +236,7 @@ macro_rules! FROM_STR {
($type:ty) => {
impl FromParam for $type {
type Err = InternalError<<$type as FromStr>::Err>;
fn from_param(val: &str) -> Result<Self, Self::Err> {
<$type as FromStr>::from_str(val)
.map_err(|e| InternalError::new(e, StatusCode::BAD_REQUEST))

View File

@ -513,8 +513,7 @@ where
.fold(BytesMut::new(), |mut b, c| {
b.extend_from_slice(c);
b
})
.freeze()
}).freeze()
}
}
@ -553,8 +552,7 @@ mod tests {
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
#[test]
@ -578,8 +576,7 @@ mod tests {
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
#[test]
@ -596,8 +593,7 @@ mod tests {
payload.readany().err().unwrap();
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
#[test]
@ -625,8 +621,7 @@ mod tests {
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
#[test]
@ -659,8 +654,7 @@ mod tests {
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
#[test]
@ -693,8 +687,7 @@ mod tests {
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
#[test]
@ -715,7 +708,6 @@ mod tests {
let res: Result<(), ()> = Ok(());
result(res)
}))
.unwrap();
})).unwrap();
}
}

View File

@ -52,9 +52,7 @@ impl<S: 'static, H: PipelineHandler<S>> PipelineState<S, H> {
PipelineState::Finishing(ref mut state) => state.poll(info, mws),
PipelineState::Completed(ref mut state) => state.poll(info),
PipelineState::Response(ref mut state) => state.poll(info, mws),
PipelineState::None | PipelineState::Error => {
None
}
PipelineState::None | PipelineState::Error => None,
}
}
}
@ -448,10 +446,16 @@ impl<S: 'static, H> ProcessResponse<S, H> {
) -> Option<PipelineState<S, H>> {
// connection is dead at this point
match mem::replace(&mut self.iostate, IOState::Done) {
IOState::Response =>
Some(FinishingMiddlewares::init(info, mws, self.resp.take().unwrap())),
IOState::Payload(_) =>
Some(FinishingMiddlewares::init(info, mws, self.resp.take().unwrap())),
IOState::Response => Some(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
)),
IOState::Payload(_) => Some(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
)),
IOState::Actor(mut ctx) => {
if info.disconnected.take().is_some() {
ctx.disconnected();
@ -467,18 +471,25 @@ impl<S: 'static, H> ProcessResponse<S, H> {
Frame::Chunk(None) => {
info.context = Some(ctx);
return Some(FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
))
info,
mws,
self.resp.take().unwrap(),
));
}
Frame::Chunk(Some(_)) => (),
Frame::Drain(fut) => {let _ = fut.send(());},
Frame::Drain(fut) => {
let _ = fut.send(());
}
}
}
}
Ok(Async::Ready(None)) =>
Ok(Async::Ready(None)) => {
return Some(FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
)),
info,
mws,
self.resp.take().unwrap(),
))
}
Ok(Async::NotReady) => {
self.iostate = IOState::Actor(ctx);
return None;
@ -486,12 +497,20 @@ impl<S: 'static, H> ProcessResponse<S, H> {
Err(err) => {
info.context = Some(ctx);
info.error = Some(err);
return Some(FinishingMiddlewares::init(info, mws, self.resp.take().unwrap()));
return Some(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
));
}
}
}
}
IOState::Done => Some(FinishingMiddlewares::init(info, mws, self.resp.take().unwrap()))
IOState::Done => Some(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
)),
}
}
@ -505,22 +524,32 @@ impl<S: 'static, H> ProcessResponse<S, H> {
'inner: loop {
let result = match mem::replace(&mut self.iostate, IOState::Done) {
IOState::Response => {
let encoding =
self.resp.as_ref().unwrap().content_encoding().unwrap_or(info.encoding);
let encoding = self
.resp
.as_ref()
.unwrap()
.content_encoding()
.unwrap_or(info.encoding);
let result =
match io.start(&info.req, self.resp.as_mut().unwrap(), encoding) {
Ok(res) => res,
Err(err) => {
info.error = Some(err.into());
return Ok(FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
));
}
};
let result = match io.start(
&info.req,
self.resp.as_mut().unwrap(),
encoding,
) {
Ok(res) => res,
Err(err) => {
info.error = Some(err.into());
return Ok(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
));
}
};
if let Some(err) = self.resp.as_ref().unwrap().error() {
if self.resp.as_ref().unwrap().status().is_server_error() {
if self.resp.as_ref().unwrap().status().is_server_error()
{
error!(
"Error occured during request handling, status: {} {}",
self.resp.as_ref().unwrap().status(), err
@ -556,7 +585,9 @@ impl<S: 'static, H> ProcessResponse<S, H> {
if let Err(err) = io.write_eof() {
info.error = Some(err.into());
return Ok(FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
info,
mws,
self.resp.take().unwrap(),
));
}
break;
@ -567,7 +598,9 @@ impl<S: 'static, H> ProcessResponse<S, H> {
Err(err) => {
info.error = Some(err.into());
return Ok(FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
info,
mws,
self.resp.take().unwrap(),
));
}
Ok(result) => result,
@ -580,7 +613,9 @@ impl<S: 'static, H> ProcessResponse<S, H> {
Err(err) => {
info.error = Some(err);
return Ok(FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
info,
mws,
self.resp.take().unwrap(),
));
}
},
@ -603,26 +638,30 @@ impl<S: 'static, H> ProcessResponse<S, H> {
info.error = Some(err.into());
return Ok(
FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
info,
mws,
self.resp.take().unwrap(),
),
);
}
break 'inner;
}
Frame::Chunk(Some(chunk)) => {
match io.write(&chunk) {
Err(err) => {
info.context = Some(ctx);
info.error = Some(err.into());
return Ok(
FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
),
);
}
Ok(result) => res = Some(result),
Frame::Chunk(Some(chunk)) => match io
.write(&chunk)
{
Err(err) => {
info.context = Some(ctx);
info.error = Some(err.into());
return Ok(
FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
),
);
}
}
Ok(result) => res = Some(result),
},
Frame::Drain(fut) => self.drain = Some(fut),
}
}
@ -642,7 +681,9 @@ impl<S: 'static, H> ProcessResponse<S, H> {
info.context = Some(ctx);
info.error = Some(err);
return Ok(FinishingMiddlewares::init(
info, mws, self.resp.take().unwrap(),
info,
mws,
self.resp.take().unwrap(),
));
}
}
@ -682,7 +723,11 @@ impl<S: 'static, H> ProcessResponse<S, H> {
info.context = Some(ctx);
}
info.error = Some(err.into());
return Ok(FinishingMiddlewares::init(info, mws, self.resp.take().unwrap()));
return Ok(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
));
}
}
}
@ -696,11 +741,19 @@ impl<S: 'static, H> ProcessResponse<S, H> {
Ok(_) => (),
Err(err) => {
info.error = Some(err.into());
return Ok(FinishingMiddlewares::init(info, mws, self.resp.take().unwrap()));
return Ok(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
));
}
}
self.resp.as_mut().unwrap().set_response_size(io.written());
Ok(FinishingMiddlewares::init(info, mws, self.resp.take().unwrap()))
Ok(FinishingMiddlewares::init(
info,
mws,
self.resp.take().unwrap(),
))
}
_ => Err(PipelineState::Response(self)),
}

View File

@ -264,8 +264,7 @@ mod tests {
.header(
header::HOST,
header::HeaderValue::from_static("www.rust-lang.org"),
)
.finish();
).finish();
let pred = Host("www.rust-lang.org");
assert!(pred.check(&req, req.state()));

View File

@ -715,8 +715,7 @@ mod tests {
let app = App::new()
.scope("/app", |scope| {
scope.resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/path1").request();
let resp = app.run(req);
@ -730,8 +729,7 @@ mod tests {
scope
.resource("", |r| r.f(|_| HttpResponse::Ok()))
.resource("/", |r| r.f(|_| HttpResponse::Created()))
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app").request();
let resp = app.run(req);
@ -747,8 +745,7 @@ mod tests {
let app = App::new()
.scope("/app/", |scope| {
scope.resource("", |r| r.f(|_| HttpResponse::Ok()))
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app").request();
let resp = app.run(req);
@ -764,8 +761,7 @@ mod tests {
let app = App::new()
.scope("/app/", |scope| {
scope.resource("/", |r| r.f(|_| HttpResponse::Ok()))
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app").request();
let resp = app.run(req);
@ -783,12 +779,12 @@ mod tests {
scope
.route("/path1", Method::GET, |_: HttpRequest<_>| {
HttpResponse::Ok()
})
.route("/path1", Method::DELETE, |_: HttpRequest<_>| {
HttpResponse::Ok()
})
})
.finish();
}).route(
"/path1",
Method::DELETE,
|_: HttpRequest<_>| HttpResponse::Ok(),
)
}).finish();
let req = TestRequest::with_uri("/app/path1").request();
let resp = app.run(req);
@ -814,8 +810,7 @@ mod tests {
scope
.filter(pred::Get())
.resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/path1")
.method(Method::POST)
@ -840,8 +835,7 @@ mod tests {
.body(format!("project: {}", &r.match_info()["project"]))
})
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/ab-project1/path1").request();
let resp = app.run(req);
@ -869,8 +863,7 @@ mod tests {
scope.with_state("/t1", State, |scope| {
scope.resource("/path1", |r| r.f(|_| HttpResponse::Created()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1/path1").request();
let resp = app.run(req);
@ -888,8 +881,7 @@ mod tests {
.resource("", |r| r.f(|_| HttpResponse::Ok()))
.resource("/", |r| r.f(|_| HttpResponse::Created()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1").request();
let resp = app.run(req);
@ -909,8 +901,7 @@ mod tests {
scope.with_state("/t1/", State, |scope| {
scope.resource("", |r| r.f(|_| HttpResponse::Ok()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1").request();
let resp = app.run(req);
@ -930,8 +921,7 @@ mod tests {
scope.with_state("/t1/", State, |scope| {
scope.resource("/", |r| r.f(|_| HttpResponse::Ok()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1").request();
let resp = app.run(req);
@ -953,8 +943,7 @@ mod tests {
.filter(pred::Get())
.resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1/path1")
.method(Method::POST)
@ -976,8 +965,7 @@ mod tests {
scope.nested("/t1", |scope| {
scope.resource("/path1", |r| r.f(|_| HttpResponse::Created()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1/path1").request();
let resp = app.run(req);
@ -993,8 +981,7 @@ mod tests {
.resource("", |r| r.f(|_| HttpResponse::Ok()))
.resource("/", |r| r.f(|_| HttpResponse::Created()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1").request();
let resp = app.run(req);
@ -1014,8 +1001,7 @@ mod tests {
.filter(pred::Get())
.resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/t1/path1")
.method(Method::POST)
@ -1044,8 +1030,7 @@ mod tests {
})
})
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/project_1/path1").request();
let resp = app.run(req);
@ -1077,8 +1062,7 @@ mod tests {
})
})
})
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/test/1/path1").request();
let resp = app.run(req);
@ -1104,8 +1088,7 @@ mod tests {
scope
.resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
.default_resource(|r| r.f(|_| HttpResponse::BadRequest()))
})
.finish();
}).finish();
let req = TestRequest::with_uri("/app/path2").request();
let resp = app.run(req);
@ -1121,8 +1104,7 @@ mod tests {
let app = App::new()
.scope("/app1", |scope| {
scope.default_resource(|r| r.f(|_| HttpResponse::BadRequest()))
})
.scope("/app2", |scope| scope)
}).scope("/app2", |scope| scope)
.default_resource(|r| r.f(|_| HttpResponse::MethodNotAllowed()))
.finish();

View File

@ -166,9 +166,9 @@ impl H1Decoder {
{
true
} else {
version == Version::HTTP_11
&& !(conn.contains("close")
|| conn.contains("upgrade"))
version == Version::HTTP_11 && !(conn
.contains("close")
|| conn.contains("upgrade"))
}
} else {
false

View File

@ -152,8 +152,7 @@ impl<T: AsyncWrite, H: 'static> Writer for H1Writer<T, H> {
let reason = msg.reason().as_bytes();
if let Body::Binary(ref bytes) = body {
buffer.reserve(
256
+ msg.headers().len() * AVERAGE_HEADER_SIZE
256 + msg.headers().len() * AVERAGE_HEADER_SIZE
+ bytes.len()
+ reason.len(),
);

View File

@ -115,46 +115,51 @@ where
if disconnected {
item.flags.insert(EntryFlags::EOF);
} else {
let retry = item.payload.need_read() == PayloadStatus::Read;
loop {
match item.task.poll_io(&mut item.stream) {
Ok(Async::Ready(ready)) => {
if ready {
let retry = item.payload.need_read() == PayloadStatus::Read;
loop {
match item.task.poll_io(&mut item.stream) {
Ok(Async::Ready(ready)) => {
if ready {
item.flags.insert(
EntryFlags::EOF | EntryFlags::FINISHED,
);
} else {
item.flags.insert(EntryFlags::EOF);
}
not_ready = false;
}
Ok(Async::NotReady) => {
if item.payload.need_read()
== PayloadStatus::Read
&& !retry
{
continue;
}
}
Err(err) => {
error!("Unhandled error: {}", err);
item.flags.insert(
EntryFlags::EOF | EntryFlags::FINISHED,
EntryFlags::EOF
| EntryFlags::ERROR
| EntryFlags::WRITE_DONE,
);
} else {
item.flags.insert(EntryFlags::EOF);
}
not_ready = false;
}
Ok(Async::NotReady) => {
if item.payload.need_read() == PayloadStatus::Read
&& !retry
{
continue;
item.stream.reset(Reason::INTERNAL_ERROR);
}
}
Err(err) => {
error!("Unhandled error: {}", err);
item.flags.insert(
EntryFlags::EOF
| EntryFlags::ERROR
| EntryFlags::WRITE_DONE,
);
item.stream.reset(Reason::INTERNAL_ERROR);
}
break;
}
break;
}
}
}
if item.flags.contains(EntryFlags::EOF) && !item.flags.contains(EntryFlags::FINISHED) {
if item.flags.contains(EntryFlags::EOF)
&& !item.flags.contains(EntryFlags::FINISHED)
{
match item.task.poll_completed() {
Ok(Async::NotReady) => (),
Ok(Async::Ready(_)) => {
item.flags.insert(EntryFlags::FINISHED | EntryFlags::WRITE_DONE);
item.flags.insert(
EntryFlags::FINISHED | EntryFlags::WRITE_DONE,
);
}
Err(err) => {
item.flags.insert(

View File

@ -250,9 +250,7 @@ impl<H: 'static> Writer for H2Writer<H> {
return Ok(Async::Ready(()));
}
}
Err(e) => {
return Err(io::Error::new(io::ErrorKind::Other, e))
}
Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
}
}
}

View File

@ -403,19 +403,24 @@ where
}
}
impl<H: IntoHttpHandler> Into<(Box<Service>, Vec<(Token, net::TcpListener)>)> for HttpServer<H> {
impl<H: IntoHttpHandler> Into<(Box<Service>, Vec<(Token, net::TcpListener)>)>
for HttpServer<H>
{
fn into(mut self) -> (Box<Service>, Vec<(Token, net::TcpListener)>) {
let sockets: Vec<_> = mem::replace(&mut self.sockets, Vec::new())
.into_iter()
.map(|item| (item.token, item.lst))
.collect();
(Box::new(HttpService {
factory: self.factory,
host: self.host,
keep_alive: self.keep_alive,
handlers: self.handlers,
}), sockets)
(
Box::new(HttpService {
factory: self.factory,
host: self.host,
keep_alive: self.keep_alive,
handlers: self.handlers,
}),
sockets,
)
}
}

View File

@ -125,12 +125,12 @@ mod h1writer;
mod h2;
mod h2writer;
pub(crate) mod helpers;
mod http;
pub(crate) mod input;
pub(crate) mod message;
pub(crate) mod output;
mod server;
pub(crate) mod settings;
mod http;
mod ssl;
mod worker;
@ -138,12 +138,12 @@ use actix::Message;
pub use self::message::Request;
pub use self::http::HttpServer;
#[doc(hidden)]
pub use self::server::{
ConnectionRateTag, ConnectionTag, Connections, Server, Service, ServiceHandler,
};
pub use self::settings::ServerSettings;
pub use self::http::HttpServer;
#[doc(hidden)]
pub use self::ssl::*;

View File

@ -273,10 +273,9 @@ impl Output {
let enc = match encoding {
#[cfg(feature = "flate2")]
ContentEncoding::Deflate => ContentEncoder::Deflate(ZlibEncoder::new(
transfer,
Compression::fast(),
)),
ContentEncoding::Deflate => {
ContentEncoder::Deflate(ZlibEncoder::new(transfer, Compression::fast()))
}
#[cfg(feature = "flate2")]
ContentEncoding::Gzip => {
ContentEncoder::Gzip(GzEncoder::new(transfer, Compression::fast()))

View File

@ -1,16 +1,21 @@
use std::{mem, net};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::time::Duration;
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
use std::{mem, net};
use num_cpus;
use futures::{Future, Stream, Sink};
use futures::sync::{mpsc, mpsc::unbounded};
use futures::{Future, Sink, Stream};
use num_cpus;
use actix::{fut, signal, Actor, ActorFuture, Addr, Arbiter, AsyncContext,
Context, Handler, Response, System, StreamHandler, WrapFuture};
use actix::{
fut, signal, Actor, ActorFuture, Addr, Arbiter, AsyncContext, Context, Handler,
Response, StreamHandler, System, WrapFuture,
};
use super::accept::{AcceptLoop, AcceptNotify, Command};
use super::worker::{StopWorker, Worker, WorkerClient, Conn};
use super::worker::{Conn, StopWorker, Worker, WorkerClient};
use super::{PauseServer, ResumeServer, StopServer, Token};
#[doc(hidden)]
@ -39,7 +44,9 @@ impl Service for Box<Service> {
/// TCP connections.
pub trait ServiceHandler {
/// Handle incoming stream
fn handle(&mut self, token: Token, io: net::TcpStream, peer: Option<net::SocketAddr>);
fn handle(
&mut self, token: Token, io: net::TcpStream, peer: Option<net::SocketAddr>,
);
/// Shutdown open handlers
fn shutdown(&self, _: bool) {}
@ -156,7 +163,7 @@ impl Server {
/// Add new service to server
pub fn service<T>(mut self, srv: T) -> Self
where
T: Into<(Box<Service>, Vec<(Token, net::TcpListener)>)>
T: Into<(Box<Service>, Vec<(Token, net::TcpListener)>)>,
{
let (srv, sockets) = srv.into();
self.services.push(srv);
@ -213,8 +220,9 @@ impl Server {
info!("Starting server on http://{:?}", s.1.local_addr().ok());
}
}
let rx = self.accept.start(
mem::replace(&mut self.sockets, Vec::new()), workers);
let rx = self
.accept
.start(mem::replace(&mut self.sockets, Vec::new()), workers);
// start http server actor
let signals = self.subscribe_to_signals();
@ -242,7 +250,9 @@ impl Server {
}
}
fn start_worker(&self, idx: usize, notify: AcceptNotify) -> (Addr<Worker>, WorkerClient) {
fn start_worker(
&self, idx: usize, notify: AcceptNotify,
) -> (Addr<Worker>, WorkerClient) {
let (tx, rx) = unbounded::<Conn<net::TcpStream>>();
let conns = Connections::new(notify, self.maxconn, self.maxconnrate);
let worker = WorkerClient::new(idx, tx, conns.clone());
@ -250,7 +260,10 @@ impl Server {
let addr = Arbiter::start(move |ctx: &mut Context<_>| {
ctx.add_message_stream(rx);
let handlers: Vec<_> = services.into_iter().map(|s| s.create(conns.clone())).collect();
let handlers: Vec<_> = services
.into_iter()
.map(|s| s.create(conns.clone()))
.collect();
Worker::new(conns, handlers)
});
@ -258,8 +271,7 @@ impl Server {
}
}
impl Actor for Server
{
impl Actor for Server {
type Context = Context<Self>;
}
@ -391,7 +403,8 @@ impl StreamHandler<ServerCommand, ()> for Server {
break;
}
let (addr, worker) = self.start_worker(new_idx, self.accept.get_notify());
let (addr, worker) =
self.start_worker(new_idx, self.accept.get_notify());
self.workers.push((new_idx, addr));
self.accept.send(Command::Worker(worker));
}
@ -413,14 +426,15 @@ impl Connections {
0
};
Connections (
Arc::new(ConnectionsInner {
notify,
maxconn, maxconnrate,
maxconn_low, maxconnrate_low,
conn: AtomicUsize::new(0),
connrate: AtomicUsize::new(0),
}))
Connections(Arc::new(ConnectionsInner {
notify,
maxconn,
maxconnrate,
maxconn_low,
maxconnrate_low,
conn: AtomicUsize::new(0),
connrate: AtomicUsize::new(0),
}))
}
pub(crate) fn available(&self) -> bool {
@ -473,7 +487,6 @@ impl ConnectionsInner {
self.notify.notify();
}
}
}
/// Type responsible for max connection stat.
@ -498,7 +511,7 @@ impl Drop for ConnectionTag {
/// Type responsible for max connection rate stat.
///
/// Max connections rate stat get updated on drop.
pub struct ConnectionRateTag (Arc<ConnectionsInner>);
pub struct ConnectionRateTag(Arc<ConnectionsInner>);
impl ConnectionRateTag {
fn new(inner: Arc<ConnectionsInner>) -> Self {

View File

@ -6,7 +6,7 @@ pub use self::openssl::OpensslAcceptor;
#[cfg(feature = "tls")]
mod nativetls;
#[cfg(feature = "tls")]
pub use self::nativetls::{TlsStream, NativeTlsAcceptor};
pub use self::nativetls::{NativeTlsAcceptor, TlsStream};
#[cfg(feature = "rust-tls")]
mod rustls;

View File

@ -2,7 +2,7 @@ use std::net::Shutdown;
use std::{io, time};
use futures::{Async, Future, Poll};
use native_tls::{self, TlsAcceptor, HandshakeError};
use native_tls::{self, HandshakeError, TlsAcceptor};
use tokio_io::{AsyncRead, AsyncWrite};
use server::{AcceptorService, IoStream};
@ -29,14 +29,16 @@ pub struct TlsStream<S> {
/// Future returned from `NativeTlsAcceptor::accept` which will resolve
/// once the accept handshake has finished.
pub struct Accept<S>{
pub struct Accept<S> {
inner: Option<Result<native_tls::TlsStream<S>, HandshakeError<S>>>,
}
impl NativeTlsAcceptor {
/// Create `NativeTlsAcceptor` instance
pub fn new(acceptor: TlsAcceptor) -> Self {
NativeTlsAcceptor { acceptor: acceptor.into() }
NativeTlsAcceptor {
acceptor: acceptor.into(),
}
}
}
@ -49,7 +51,9 @@ impl<Io: IoStream> AcceptorService<Io> for NativeTlsAcceptor {
}
fn accept(&self, io: Io) -> Self::Future {
Accept { inner: Some(self.acceptor.accept(io)) }
Accept {
inner: Some(self.acceptor.accept(io)),
}
}
}
@ -78,18 +82,19 @@ impl<Io: IoStream> Future for Accept<Io> {
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.inner.take().expect("cannot poll MidHandshake twice") {
Ok(stream) => Ok(TlsStream { inner: stream }.into()),
Err(HandshakeError::Failure(e)) => Err(io::Error::new(io::ErrorKind::Other, e)),
Err(HandshakeError::WouldBlock(s)) => {
match s.handshake() {
Ok(stream) => Ok(TlsStream { inner: stream }.into()),
Err(HandshakeError::Failure(e)) =>
Err(io::Error::new(io::ErrorKind::Other, e)),
Err(HandshakeError::WouldBlock(s)) => {
self.inner = Some(Err(HandshakeError::WouldBlock(s)));
Ok(Async::NotReady)
}
}
Err(HandshakeError::Failure(e)) => {
Err(io::Error::new(io::ErrorKind::Other, e))
}
Err(HandshakeError::WouldBlock(s)) => match s.handshake() {
Ok(stream) => Ok(TlsStream { inner: stream }.into()),
Err(HandshakeError::Failure(e)) => {
Err(io::Error::new(io::ErrorKind::Other, e))
}
Err(HandshakeError::WouldBlock(s)) => {
self.inner = Some(Err(HandshakeError::WouldBlock(s)));
Ok(Async::NotReady)
}
},
}
}
}
@ -124,9 +129,7 @@ impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
}
}
impl<S: AsyncRead + AsyncWrite> AsyncRead for TlsStream<S> {
}
impl<S: AsyncRead + AsyncWrite> AsyncRead for TlsStream<S> {}
impl<S: AsyncRead + AsyncWrite> AsyncWrite for TlsStream<S> {
fn shutdown(&mut self) -> Poll<(), io::Error> {
@ -137,4 +140,4 @@ impl<S: AsyncRead + AsyncWrite> AsyncWrite for TlsStream<S> {
}
self.inner.get_mut().shutdown()
}
}
}

View File

@ -20,8 +20,9 @@ impl<T, R, F: Fn(T) -> R + 'static> FnWith<T, R> for F {
#[doc(hidden)]
pub trait WithFactory<T, S, R>: 'static
where T: FromRequest<S>,
R: Responder,
where
T: FromRequest<S>,
R: Responder,
{
fn create(self) -> With<T, S, R>;
@ -30,10 +31,11 @@ where T: FromRequest<S>,
#[doc(hidden)]
pub trait WithAsyncFactory<T, S, R, I, E>: 'static
where T: FromRequest<S>,
R: Future<Item=I, Error=E>,
I: Responder,
E: Into<Error>,
where
T: FromRequest<S>,
R: Future<Item = I, Error = E>,
I: Responder,
E: Into<Error>,
{
fn create(self) -> WithAsync<T, S, R, I, E>;
@ -305,7 +307,6 @@ where
}
}
macro_rules! with_factory_tuple ({$(($n:tt, $T:ident)),+} => {
impl<$($T,)+ State, Func, Res> WithFactory<($($T,)+), State, Res> for Func
where Func: Fn($($T,)+) -> Res + 'static,
@ -349,8 +350,27 @@ with_factory_tuple!((a, A), (b, B), (c, C), (d, D));
with_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E));
with_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F));
with_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F), (g, G));
with_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F), (g, G), (h, H));
with_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F), (g, G), (h, H), (i, I));
with_factory_tuple!(
(a, A),
(b, B),
(c, C),
(d, D),
(e, E),
(f, F),
(g, G),
(h, H)
);
with_factory_tuple!(
(a, A),
(b, B),
(c, C),
(d, D),
(e, E),
(f, F),
(g, G),
(h, H),
(i, I)
);
with_async_factory_tuple!((a, A));
with_async_factory_tuple!((a, A), (b, B));
@ -359,5 +379,24 @@ with_async_factory_tuple!((a, A), (b, B), (c, C), (d, D));
with_async_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E));
with_async_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F));
with_async_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F), (g, G));
with_async_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F), (g, G), (h, H));
with_async_factory_tuple!((a, A), (b, B), (c, C), (d, D), (e, E), (f, F), (g, G), (h, H), (i, I));
with_async_factory_tuple!(
(a, A),
(b, B),
(c, C),
(d, D),
(e, E),
(f, F),
(g, G),
(h, H)
);
with_async_factory_tuple!(
(a, A),
(b, B),
(c, C),
(d, D),
(e, E),
(f, F),
(g, G),
(h, H),
(i, I)
);

View File

@ -387,8 +387,7 @@ mod tests {
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
)
.finish();
).finish();
assert_eq!(
HandshakeError::NoConnectionUpgrade,
handshake(&req).err().unwrap()
@ -398,12 +397,10 @@ mod tests {
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
)
.header(
).header(
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
)
.finish();
).finish();
assert_eq!(
HandshakeError::NoVersionHeader,
handshake(&req).err().unwrap()
@ -413,16 +410,13 @@ mod tests {
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
)
.header(
).header(
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
)
.header(
).header(
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("5"),
)
.finish();
).finish();
assert_eq!(
HandshakeError::UnsupportedVersion,
handshake(&req).err().unwrap()
@ -432,16 +426,13 @@ mod tests {
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
)
.header(
).header(
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
)
.header(
).header(
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"),
)
.finish();
).finish();
assert_eq!(
HandshakeError::BadWebsocketKey,
handshake(&req).err().unwrap()
@ -451,20 +442,16 @@ mod tests {
.header(
header::UPGRADE,
header::HeaderValue::from_static("websocket"),
)
.header(
).header(
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
)
.header(
).header(
header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"),
)
.header(
).header(
header::SEC_WEBSOCKET_KEY,
header::HeaderValue::from_static("13"),
)
.finish();
).finish();
assert_eq!(
StatusCode::SWITCHING_PROTOCOLS,
handshake(&req).unwrap().finish().status()

View File

@ -118,8 +118,7 @@ fn test_client_gzip_encoding() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Deflate)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -148,8 +147,7 @@ fn test_client_gzip_encoding_large() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Deflate)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -181,8 +179,7 @@ fn test_client_gzip_encoding_large_random() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Deflate)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -200,7 +197,6 @@ fn test_client_gzip_encoding_large_random() {
assert_eq!(bytes, Bytes::from(data));
}
#[cfg(all(unix, feature = "uds"))]
#[test]
fn test_compatible_with_unix_socket_stream() {
@ -218,8 +214,7 @@ fn test_client_brotli_encoding() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -252,8 +247,7 @@ fn test_client_brotli_encoding_large_random() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Gzip)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -282,8 +276,7 @@ fn test_client_deflate_encoding() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Br)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -316,8 +309,7 @@ fn test_client_deflate_encoding_large_random() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Br)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -346,8 +338,7 @@ fn test_client_streaming_explicit() {
.chunked()
.content_encoding(http::ContentEncoding::Identity)
.body(body))
})
.responder()
}).responder()
})
});

View File

@ -191,8 +191,7 @@ fn test_form_extractor() {
.uri(srv.url("/test1/index.html"))
.form(FormData {
username: "test".to_string(),
})
.unwrap();
}).unwrap();
let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success());
@ -306,8 +305,7 @@ fn test_path_and_query_extractor2_async() {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(move |_| {
Ok(format!("Welcome {} - {}!", p.username, data.0))
})
.responder()
}).responder()
},
)
});
@ -336,8 +334,7 @@ fn test_path_and_query_extractor3_async() {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(move |_| {
Ok(format!("Welcome {} - {}!", p.username, data.0))
})
.responder()
}).responder()
})
});
});
@ -361,8 +358,7 @@ fn test_path_and_query_extractor4_async() {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(move |_| {
Ok(format!("Welcome {} - {}!", p.username, data.0))
})
.responder()
}).responder()
})
});
});
@ -387,8 +383,7 @@ fn test_path_and_query_extractor2_async2() {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(move |_| {
Ok(format!("Welcome {} - {}!", p.username, data.0))
})
.responder()
}).responder()
},
)
});
@ -422,15 +417,13 @@ fn test_path_and_query_extractor2_async2() {
fn test_path_and_query_extractor2_async3() {
let mut srv = test::TestServer::new(|app| {
app.resource("/{username}/index.html", |r| {
r.route().with(
|data: Json<Value>, p: Path<PParam>, _: Query<PParam>| {
r.route()
.with(|data: Json<Value>, p: Path<PParam>, _: Query<PParam>| {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(move |_| {
Ok(format!("Welcome {} - {}!", p.username, data.0))
})
.responder()
},
)
}).responder()
})
});
});
@ -467,8 +460,7 @@ fn test_path_and_query_extractor2_async4() {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(move |_| {
Ok(format!("Welcome {} - {}!", data.1.username, (data.0).0))
})
.responder()
}).responder()
})
});
});

View File

@ -84,11 +84,10 @@ fn test_middleware_multiple() {
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
}).middleware(MiddlewareTest {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.handler(|_| HttpResponse::Ok())
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
}).handler(|_| HttpResponse::Ok())
});
let request = srv.get().finish().unwrap();
@ -143,11 +142,10 @@ fn test_resource_middleware_multiple() {
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
}).middleware(MiddlewareTest {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.handler(|_| HttpResponse::Ok())
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
}).handler(|_| HttpResponse::Ok())
});
let request = srv.get().finish().unwrap();
@ -176,8 +174,7 @@ fn test_scope_middleware() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
}).resource("/test", |r| r.f(|_| HttpResponse::Ok()))
})
});
@ -207,13 +204,11 @@ fn test_scope_middleware_multiple() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.middleware(MiddlewareTest {
}).middleware(MiddlewareTest {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
}).resource("/test", |r| r.f(|_| HttpResponse::Ok()))
})
});
@ -242,8 +237,7 @@ fn test_middleware_async_handler() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/", |r| {
}).resource("/", |r| {
r.route().a(|_| {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(|_| Ok(HttpResponse::Ok()))
@ -312,8 +306,7 @@ fn test_scope_middleware_async_handler() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| {
}).resource("/test", |r| {
r.route().a(|_| {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(|_| Ok(HttpResponse::Ok()))
@ -379,8 +372,7 @@ fn test_scope_middleware_async_error() {
start: Arc::clone(&act_req),
response: Arc::clone(&act_resp),
finish: Arc::clone(&act_fin),
})
.resource("/test", |r| r.f(index_test_middleware_async_error))
}).resource("/test", |r| r.f(index_test_middleware_async_error))
})
});
@ -514,13 +506,11 @@ fn test_async_middleware_multiple() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.middleware(MiddlewareAsyncTest {
}).middleware(MiddlewareAsyncTest {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
}).resource("/test", |r| r.f(|_| HttpResponse::Ok()))
});
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
@ -550,13 +540,11 @@ fn test_async_sync_middleware_multiple() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.middleware(MiddlewareTest {
}).middleware(MiddlewareTest {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
}).resource("/test", |r| r.f(|_| HttpResponse::Ok()))
});
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
@ -587,8 +575,7 @@ fn test_async_scope_middleware() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
}).resource("/test", |r| r.f(|_| HttpResponse::Ok()))
})
});
@ -620,13 +607,11 @@ fn test_async_scope_middleware_multiple() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.middleware(MiddlewareAsyncTest {
}).middleware(MiddlewareAsyncTest {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
}).resource("/test", |r| r.f(|_| HttpResponse::Ok()))
})
});
@ -658,13 +643,11 @@ fn test_async_async_scope_middleware_multiple() {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.middleware(MiddlewareTest {
}).middleware(MiddlewareTest {
start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3),
})
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
}).resource("/test", |r| r.f(|_| HttpResponse::Ok()))
})
});
@ -1012,8 +995,7 @@ fn test_session_storage_middleware() {
App::new()
.middleware(SessionStorage::new(
CookieSessionBackend::signed(&[0; 32]).secure(false),
))
.resource("/index", move |r| {
)).resource("/index", move |r| {
r.f(|req| {
let res = req.session().set(COMPLEX_NAME, COMPLEX_PAYLOAD);
assert!(res.is_ok());
@ -1033,8 +1015,7 @@ fn test_session_storage_middleware() {
HttpResponse::Ok()
})
})
.resource("/expect_cookie", move |r| {
}).resource("/expect_cookie", move |r| {
r.f(|req| {
let _cookies = req.cookies().expect("To get cookies");

View File

@ -59,8 +59,8 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
#[test]
#[cfg(unix)]
fn test_start() {
use std::sync::mpsc;
use actix::System;
use std::sync::mpsc;
let _ = test::TestServer::unused_addr();
let (tx, rx) = mpsc::channel();
@ -119,9 +119,9 @@ fn test_start() {
#[test]
#[cfg(unix)]
fn test_shutdown() {
use std::sync::mpsc;
use std::net;
use actix::System;
use std::net;
use std::sync::mpsc;
let _ = test::TestServer::unused_addr();
let (tx, rx) = mpsc::channel();
@ -162,8 +162,8 @@ fn test_shutdown() {
#[test]
#[cfg(unix)]
fn test_panic() {
use std::sync::mpsc;
use actix::System;
use std::sync::mpsc;
let _ = test::TestServer::unused_addr();
let (tx, rx) = mpsc::channel();
@ -176,8 +176,7 @@ fn test_panic() {
r.method(http::Method::GET).f(|_| -> &'static str {
panic!("error");
});
})
.resource("/", |r| {
}).resource("/", |r| {
r.method(http::Method::GET).f(|_| HttpResponse::Ok())
})
}).workers(1);
@ -628,8 +627,7 @@ fn test_gzip_encoding() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -661,8 +659,7 @@ fn test_gzip_encoding_large() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -698,8 +695,7 @@ fn test_reading_gzip_encoding_large_random() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -731,8 +727,7 @@ fn test_reading_deflate_encoding() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -764,8 +759,7 @@ fn test_reading_deflate_encoding_large() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -801,8 +795,7 @@ fn test_reading_deflate_encoding_large_random() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -835,8 +828,7 @@ fn test_brotli_encoding() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -869,8 +861,7 @@ fn test_brotli_encoding_large() {
Ok(HttpResponse::Ok()
.content_encoding(http::ContentEncoding::Identity)
.body(bytes))
})
.responder()
}).responder()
})
});
@ -946,14 +937,23 @@ fn test_server_cookies() {
use actix_web::http;
let mut srv = test::TestServer::with_factory(|| {
App::new().resource("/", |r| r.f(|_| HttpResponse::Ok().cookie(http::CookieBuilder::new("first", "first_value").http_only(true).finish())
.cookie(http::Cookie::new("second", "first_value"))
.cookie(http::Cookie::new("second", "second_value"))
.finish())
)
App::new().resource("/", |r| {
r.f(|_| {
HttpResponse::Ok()
.cookie(
http::CookieBuilder::new("first", "first_value")
.http_only(true)
.finish(),
).cookie(http::Cookie::new("second", "first_value"))
.cookie(http::Cookie::new("second", "second_value"))
.finish()
})
})
});
let first_cookie = http::CookieBuilder::new("first", "first_value").http_only(true).finish();
let first_cookie = http::CookieBuilder::new("first", "first_value")
.http_only(true)
.finish();
let second_cookie = http::Cookie::new("second", "second_value");
let request = srv.get().finish().unwrap();
@ -972,10 +972,12 @@ fn test_server_cookies() {
let first_cookie = first_cookie.to_string();
let second_cookie = second_cookie.to_string();
//Check that we have exactly two instances of raw cookie headers
let cookies = response.headers().get_all(http::header::SET_COOKIE)
.iter()
.map(|header| header.to_str().expect("To str").to_string())
.collect::<Vec<_>>();
let cookies = response
.headers()
.get_all(http::header::SET_COOKIE)
.iter()
.map(|header| header.to_str().expect("To str").to_string())
.collect::<Vec<_>>();
assert_eq!(cookies.len(), 2);
if cookies[0] == first_cookie {
assert_eq!(cookies[1], second_cookie);

View File

@ -71,7 +71,7 @@ fn start_ws_resource(req: &HttpRequest) -> Result<HttpResponse, Error> {
#[test]
fn test_simple_path() {
const PATH:&str = "/v1/ws/";
const PATH: &str = "/v1/ws/";
// Create a websocket at a specific path.
let mut srv = test::TestServer::new(|app| {
@ -103,7 +103,6 @@ fn test_simple_path() {
);
}
#[test]
fn test_empty_close_code() {
let mut srv = test::TestServer::new(|app| app.handler(|req| ws::start(req, Ws)));
@ -214,8 +213,7 @@ impl Ws2 {
act.send(ctx);
}
actix::fut::ok(())
})
.wait(ctx);
}).wait(ctx);
}
}