From 1716380f0890a1e936d84181effeb63906c1e609 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Thu, 23 Aug 2018 09:48:01 -0700 Subject: [PATCH] clippy fmt --- src/application.rs | 3 +- src/client/connector.rs | 295 +++++++++++++++++----------------- src/client/writer.rs | 7 +- src/extractor.rs | 22 +-- src/fs.rs | 16 +- src/handler.rs | 11 +- src/header/mod.rs | 3 +- src/helpers.rs | 3 +- src/httpmessage.rs | 24 ++- src/httprequest.rs | 3 +- src/httpresponse.rs | 6 +- src/info.rs | 3 +- src/json.rs | 23 +-- src/lib.rs | 8 +- src/middleware/cors.rs | 29 ++-- src/middleware/csrf.rs | 5 +- src/middleware/errhandlers.rs | 2 +- src/middleware/session.rs | 6 +- src/multipart.rs | 8 +- src/param.rs | 2 +- src/payload.rs | 24 +-- src/pipeline.rs | 151 +++++++++++------ src/pred.rs | 3 +- src/scope.rs | 66 +++----- src/server/h1decoder.rs | 6 +- src/server/h1writer.rs | 3 +- src/server/h2.rs | 65 ++++---- src/server/h2writer.rs | 4 +- src/server/http.rs | 19 ++- src/server/mod.rs | 4 +- src/server/output.rs | 7 +- src/server/server.rs | 65 +++++--- src/server/ssl/mod.rs | 2 +- src/server/ssl/nativetls.rs | 41 ++--- src/with.rs | 61 +++++-- src/ws/mod.rs | 39 ++--- tests/test_client.rs | 25 +-- tests/test_handlers.rs | 28 ++-- tests/test_middleware.rs | 69 +++----- tests/test_server.rs | 66 ++++---- tests/test_ws.rs | 6 +- 41 files changed, 616 insertions(+), 617 deletions(-) diff --git a/src/application.rs b/src/application.rs index 4c8946c4e..3ef753f5f 100644 --- a/src/application.rs +++ b/src/application.rs @@ -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); diff --git a/src/client/connector.rs b/src/client/connector.rs index 75b2e149f..61347682a 100644 --- a/src/client/connector.rs +++ b/src/client/connector.rs @@ -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); } } diff --git a/src/client/writer.rs b/src/client/writer.rs index 81ad96510..45abfb773 100644 --- a/src/client/writer.rs +++ b/src/client/writer.rs @@ -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())) diff --git a/src/extractor.rs b/src/extractor.rs index 6d156d47a..7b0b4b003 100644 --- a/src/extractor.rs +++ b/src/extractor.rs @@ -103,7 +103,7 @@ impl Path { impl From for Path { fn from(inner: T) -> Path { - 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::>::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::>::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::, 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::, Error>::from_request(&req, &FormConfig::default()) .poll() diff --git a/src/fs.rs b/src/fs.rs index 4c8192126..10cdaff7b 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -369,11 +369,7 @@ impl Responder for NamedFile { .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::>()?; + }).collect::>()?; let ranges: Vec = 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() diff --git a/src/handler.rs b/src/handler.rs index 661cd0285..2b6cc6604 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -354,15 +354,16 @@ impl> From> for AsyncResult { } impl From>, E>> for AsyncResult -where T: 'static, - E: Into + 'static +where + T: 'static, + E: Into + 'static, { #[inline] fn from(res: Result>, 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()))), } } diff --git a/src/header/mod.rs b/src/header/mod.rs index cdd2ad200..74e4b03e5 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -223,8 +223,7 @@ pub fn from_comma_delimited( .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) diff --git a/src/helpers.rs b/src/helpers.rs index 400b12253..e82d61616 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -279,8 +279,7 @@ mod tests { true, StatusCode::MOVED_PERMANENTLY, )) - }) - .finish(); + }).finish(); // trailing slashes let params = vec![ diff --git a/src/httpmessage.rs b/src/httpmessage.rs index 5db2f075b..60f77b07e 100644 --- a/src/httpmessage.rs +++ b/src/httpmessage.rs @@ -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::(&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::().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::().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::().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!( diff --git a/src/httprequest.rs b/src/httprequest.rs index 128dcbf17..f4de81529 100644 --- a/src/httprequest.rs +++ b/src/httprequest.rs @@ -264,7 +264,8 @@ impl HttpRequest { if self.extensions().get::().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()); diff --git a/src/httpresponse.rs b/src/httpresponse.rs index 7700d3523..f02570188 100644 --- a/src/httpresponse.rs +++ b/src/httpresponse.rs @@ -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 diff --git a/src/info.rs b/src/info.rs index b15ba9886..aeffc5ba2 100644 --- a/src/info.rs +++ b/src/info.rs @@ -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); diff --git a/src/json.rs b/src/json.rs index 86eefca96..178143f11 100644 --- a/src/json.rs +++ b/src/json.rs @@ -327,8 +327,7 @@ impl Future for JsonBod body.extend_from_slice(&chunk); Ok(body) } - }) - .and_then(|body| Ok(serde_json::from_slice::(&body)?)); + }).and_then(|body| Ok(serde_json::from_slice::(&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::(); 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::().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::(); @@ -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()) } } diff --git a/src/lib.rs b/src/lib.rs index 72fe26c10..4eeb5adac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/middleware/cors.rs b/src/middleware/cors.rs index a61727409..e75dc73ee 100644 --- a/src/middleware/cors.rs +++ b/src/middleware/cors.rs @@ -387,12 +387,10 @@ impl Middleware 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 Middleware 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 Middleware 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 CorsBuilder { 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() diff --git a/src/middleware/csrf.rs b/src/middleware/csrf.rs index cda1d324c..02cd150d5 100644 --- a/src/middleware/csrf.rs +++ b/src/middleware/csrf.rs @@ -93,8 +93,7 @@ fn origin(headers: &HeaderMap) -> Option, 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()); } diff --git a/src/middleware/errhandlers.rs b/src/middleware/errhandlers.rs index 83c66aae1..c7d19d334 100644 --- a/src/middleware/errhandlers.rs +++ b/src/middleware/errhandlers.rs @@ -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(); diff --git a/src/middleware/session.rs b/src/middleware/session.rs index cc7aab6b4..7bf5c0e95 100644 --- a/src/middleware/session.rs +++ b/src/middleware/session.rs @@ -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" diff --git a/src/multipart.rs b/src/multipart.rs index dbf3d179e..fe809294f 100644 --- a/src/multipart.rs +++ b/src/multipart.rs @@ -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(); } } diff --git a/src/param.rs b/src/param.rs index 2704b60d0..063159d72 100644 --- a/src/param.rs +++ b/src/param.rs @@ -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 { <$type as FromStr>::from_str(val) .map_err(|e| InternalError::new(e, StatusCode::BAD_REQUEST)) diff --git a/src/payload.rs b/src/payload.rs index b20bec652..1d9281f51 100644 --- a/src/payload.rs +++ b/src/payload.rs @@ -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(); } } diff --git a/src/pipeline.rs b/src/pipeline.rs index 7f206a9fd..1940f9308 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -52,9 +52,7 @@ impl> PipelineState { 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 ProcessResponse { ) -> Option> { // 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 ProcessResponse { 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 ProcessResponse { 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 ProcessResponse { '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 ProcessResponse { 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 ProcessResponse { 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 ProcessResponse { 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 ProcessResponse { 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 ProcessResponse { 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 ProcessResponse { 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 ProcessResponse { 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)), } diff --git a/src/pred.rs b/src/pred.rs index 22f12ac2a..99d6e608b 100644 --- a/src/pred.rs +++ b/src/pred.rs @@ -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())); diff --git a/src/scope.rs b/src/scope.rs index baf891c36..8298f534a 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -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(); diff --git a/src/server/h1decoder.rs b/src/server/h1decoder.rs index d1948a0d1..084ae8b2f 100644 --- a/src/server/h1decoder.rs +++ b/src/server/h1decoder.rs @@ -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 diff --git a/src/server/h1writer.rs b/src/server/h1writer.rs index 8c948471f..8981f9df9 100644 --- a/src/server/h1writer.rs +++ b/src/server/h1writer.rs @@ -152,8 +152,7 @@ impl Writer for H1Writer { 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(), ); diff --git a/src/server/h2.rs b/src/server/h2.rs index 0835f5920..986888ff8 100644 --- a/src/server/h2.rs +++ b/src/server/h2.rs @@ -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( diff --git a/src/server/h2writer.rs b/src/server/h2writer.rs index ce61b3ed7..398e9817a 100644 --- a/src/server/h2writer.rs +++ b/src/server/h2writer.rs @@ -250,9 +250,7 @@ impl Writer for H2Writer { 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)), } } } diff --git a/src/server/http.rs b/src/server/http.rs index f0cbacdb9..05f0b2442 100644 --- a/src/server/http.rs +++ b/src/server/http.rs @@ -403,19 +403,24 @@ where } } -impl Into<(Box, Vec<(Token, net::TcpListener)>)> for HttpServer { +impl Into<(Box, Vec<(Token, net::TcpListener)>)> + for HttpServer +{ fn into(mut self) -> (Box, 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, + ) } } diff --git a/src/server/mod.rs b/src/server/mod.rs index 901260be3..2ac933a76 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -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::*; diff --git a/src/server/output.rs b/src/server/output.rs index 970e03d8d..74b083388 100644 --- a/src/server/output.rs +++ b/src/server/output.rs @@ -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())) diff --git a/src/server/server.rs b/src/server/server.rs index 0646c100c..7bab70f03 100644 --- a/src/server/server.rs +++ b/src/server/server.rs @@ -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 { /// TCP connections. pub trait ServiceHandler { /// Handle incoming stream - fn handle(&mut self, token: Token, io: net::TcpStream, peer: Option); + fn handle( + &mut self, token: Token, io: net::TcpStream, peer: Option, + ); /// Shutdown open handlers fn shutdown(&self, _: bool) {} @@ -156,7 +163,7 @@ impl Server { /// Add new service to server pub fn service(mut self, srv: T) -> Self where - T: Into<(Box, Vec<(Token, net::TcpListener)>)> + T: Into<(Box, 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, WorkerClient) { + fn start_worker( + &self, idx: usize, notify: AcceptNotify, + ) -> (Addr, WorkerClient) { let (tx, rx) = unbounded::>(); 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; } @@ -391,7 +403,8 @@ impl StreamHandler 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); +pub struct ConnectionRateTag(Arc); impl ConnectionRateTag { fn new(inner: Arc) -> Self { diff --git a/src/server/ssl/mod.rs b/src/server/ssl/mod.rs index b29a7d4a6..bd931fb82 100644 --- a/src/server/ssl/mod.rs +++ b/src/server/ssl/mod.rs @@ -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; diff --git a/src/server/ssl/nativetls.rs b/src/server/ssl/nativetls.rs index c3f2c38d4..e35f12d2d 100644 --- a/src/server/ssl/nativetls.rs +++ b/src/server/ssl/nativetls.rs @@ -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 { /// Future returned from `NativeTlsAcceptor::accept` which will resolve /// once the accept handshake has finished. -pub struct Accept{ +pub struct Accept { inner: Option, HandshakeError>>, } impl NativeTlsAcceptor { /// Create `NativeTlsAcceptor` instance pub fn new(acceptor: TlsAcceptor) -> Self { - NativeTlsAcceptor { acceptor: acceptor.into() } + NativeTlsAcceptor { + acceptor: acceptor.into(), + } } } @@ -49,7 +51,9 @@ impl AcceptorService 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 Future for Accept { fn poll(&mut self) -> Poll { 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 io::Write for TlsStream { } } - -impl AsyncRead for TlsStream { -} +impl AsyncRead for TlsStream {} impl AsyncWrite for TlsStream { fn shutdown(&mut self) -> Poll<(), io::Error> { @@ -137,4 +140,4 @@ impl AsyncWrite for TlsStream { } self.inner.get_mut().shutdown() } -} \ No newline at end of file +} diff --git a/src/with.rs b/src/with.rs index caffe0acb..5e2c01414 100644 --- a/src/with.rs +++ b/src/with.rs @@ -20,8 +20,9 @@ impl R + 'static> FnWith for F { #[doc(hidden)] pub trait WithFactory: 'static -where T: FromRequest, - R: Responder, +where + T: FromRequest, + R: Responder, { fn create(self) -> With; @@ -30,10 +31,11 @@ where T: FromRequest, #[doc(hidden)] pub trait WithAsyncFactory: 'static -where T: FromRequest, - R: Future, - I: Responder, - E: Into, +where + T: FromRequest, + R: Future, + I: Responder, + E: Into, { fn create(self) -> WithAsync; @@ -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) +); diff --git a/src/ws/mod.rs b/src/ws/mod.rs index 6b37bc7e0..c16f8d6d2 100644 --- a/src/ws/mod.rs +++ b/src/ws/mod.rs @@ -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() diff --git a/tests/test_client.rs b/tests/test_client.rs index 16d95bf29..d7341ce1f 100644 --- a/tests/test_client.rs +++ b/tests/test_client.rs @@ -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() }) }); diff --git a/tests/test_handlers.rs b/tests/test_handlers.rs index 4243cd3a8..3ea709c92 100644 --- a/tests/test_handlers.rs +++ b/tests/test_handlers.rs @@ -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, p: Path, _: Query| { + r.route() + .with(|data: Json, p: Path, _: Query| { 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() }) }); }); diff --git a/tests/test_middleware.rs b/tests/test_middleware.rs index 4fa1c81da..6cb6ee363 100644 --- a/tests/test_middleware.rs +++ b/tests/test_middleware.rs @@ -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"); diff --git a/tests/test_server.rs b/tests/test_server.rs index 36c1b6e6b..c573c4e12 100644 --- a/tests/test_server.rs +++ b/tests/test_server.rs @@ -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::>(); + let cookies = response + .headers() + .get_all(http::header::SET_COOKIE) + .iter() + .map(|header| header.to_str().expect("To str").to_string()) + .collect::>(); assert_eq!(cookies.len(), 2); if cookies[0] == first_cookie { assert_eq!(cookies[1], second_cookie); diff --git a/tests/test_ws.rs b/tests/test_ws.rs index aa57faf66..49118fc7f 100644 --- a/tests/test_ws.rs +++ b/tests/test_ws.rs @@ -71,7 +71,7 @@ fn start_ws_resource(req: &HttpRequest) -> Result { #[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); } }