1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-07-02 03:55:48 +00:00

update tests and clippy warnings

This commit is contained in:
Nikolay Kim 2019-12-08 12:31:16 +06:00
parent 6c9f9fff73
commit 4a8a9ef405
22 changed files with 152 additions and 201 deletions

View file

@ -18,7 +18,6 @@ use super::{Cookie, SameSite};
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let cookie: Cookie = Cookie::build("name", "value") /// let cookie: Cookie = Cookie::build("name", "value")
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
/// .path("/") /// .path("/")
@ -26,7 +25,6 @@ use super::{Cookie, SameSite};
/// .http_only(true) /// .http_only(true)
/// .max_age(84600) /// .max_age(84600)
/// .finish(); /// .finish();
/// # }
/// ``` /// ```
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CookieBuilder { pub struct CookieBuilder {
@ -65,13 +63,11 @@ impl CookieBuilder {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .expires(time::now()) /// .expires(time::now())
/// .finish(); /// .finish();
/// ///
/// assert!(c.expires().is_some()); /// assert!(c.expires().is_some());
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn expires(mut self, when: Tm) -> CookieBuilder { pub fn expires(mut self, when: Tm) -> CookieBuilder {
@ -86,13 +82,11 @@ impl CookieBuilder {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .max_age(1800) /// .max_age(1800)
/// .finish(); /// .finish();
/// ///
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60))); /// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn max_age(self, seconds: i64) -> CookieBuilder { pub fn max_age(self, seconds: i64) -> CookieBuilder {
@ -106,13 +100,11 @@ impl CookieBuilder {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .max_age_time(time::Duration::minutes(30)) /// .max_age_time(time::Duration::minutes(30))
/// .finish(); /// .finish();
/// ///
/// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60))); /// assert_eq!(c.max_age(), Some(time::Duration::seconds(30 * 60)));
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn max_age_time(mut self, value: Duration) -> CookieBuilder { pub fn max_age_time(mut self, value: Duration) -> CookieBuilder {
@ -222,14 +214,12 @@ impl CookieBuilder {
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let c = Cookie::build("foo", "bar") /// let c = Cookie::build("foo", "bar")
/// .permanent() /// .permanent()
/// .finish(); /// .finish();
/// ///
/// assert_eq!(c.max_age(), Some(Duration::days(365 * 20))); /// assert_eq!(c.max_age(), Some(Duration::days(365 * 20)));
/// # assert!(c.expires().is_some()); /// # assert!(c.expires().is_some());
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn permanent(mut self) -> CookieBuilder { pub fn permanent(mut self) -> CookieBuilder {

View file

@ -190,7 +190,6 @@ impl CookieJar {
/// use actix_http::cookie::{CookieJar, Cookie}; /// use actix_http::cookie::{CookieJar, Cookie};
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut jar = CookieJar::new(); /// let mut jar = CookieJar::new();
/// ///
/// // Assume this cookie originally had a path of "/" and domain of "a.b". /// // Assume this cookie originally had a path of "/" and domain of "a.b".
@ -204,7 +203,6 @@ impl CookieJar {
/// assert_eq!(delta.len(), 1); /// assert_eq!(delta.len(), 1);
/// assert_eq!(delta[0].name(), "name"); /// assert_eq!(delta[0].name(), "name");
/// assert_eq!(delta[0].max_age(), Some(Duration::seconds(0))); /// assert_eq!(delta[0].max_age(), Some(Duration::seconds(0)));
/// # }
/// ``` /// ```
/// ///
/// Removing a new cookie does not result in a _removal_ cookie: /// Removing a new cookie does not result in a _removal_ cookie:
@ -243,7 +241,6 @@ impl CookieJar {
/// use actix_http::cookie::{CookieJar, Cookie}; /// use actix_http::cookie::{CookieJar, Cookie};
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut jar = CookieJar::new(); /// let mut jar = CookieJar::new();
/// ///
/// // Add an original cookie and a new cookie. /// // Add an original cookie and a new cookie.
@ -261,7 +258,6 @@ impl CookieJar {
/// jar.force_remove(Cookie::new("key", "value")); /// jar.force_remove(Cookie::new("key", "value"));
/// assert_eq!(jar.delta().count(), 0); /// assert_eq!(jar.delta().count(), 0);
/// assert_eq!(jar.iter().count(), 0); /// assert_eq!(jar.iter().count(), 0);
/// # }
/// ``` /// ```
pub fn force_remove<'a>(&mut self, cookie: Cookie<'a>) { pub fn force_remove<'a>(&mut self, cookie: Cookie<'a>) {
self.original_cookies.remove(cookie.name()); self.original_cookies.remove(cookie.name());

View file

@ -647,13 +647,11 @@ impl<'c> Cookie<'c> {
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut c = Cookie::new("name", "value"); /// let mut c = Cookie::new("name", "value");
/// assert_eq!(c.max_age(), None); /// assert_eq!(c.max_age(), None);
/// ///
/// c.set_max_age(Duration::hours(10)); /// c.set_max_age(Duration::hours(10));
/// assert_eq!(c.max_age(), Some(Duration::hours(10))); /// assert_eq!(c.max_age(), Some(Duration::hours(10)));
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn set_max_age(&mut self, value: Duration) { pub fn set_max_age(&mut self, value: Duration) {
@ -701,7 +699,6 @@ impl<'c> Cookie<'c> {
/// ```rust /// ```rust
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// ///
/// # fn main() {
/// let mut c = Cookie::new("name", "value"); /// let mut c = Cookie::new("name", "value");
/// assert_eq!(c.expires(), None); /// assert_eq!(c.expires(), None);
/// ///
@ -710,7 +707,6 @@ impl<'c> Cookie<'c> {
/// ///
/// c.set_expires(now); /// c.set_expires(now);
/// assert!(c.expires().is_some()) /// assert!(c.expires().is_some())
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn set_expires(&mut self, time: Tm) { pub fn set_expires(&mut self, time: Tm) {
@ -726,7 +722,6 @@ impl<'c> Cookie<'c> {
/// use actix_http::cookie::Cookie; /// use actix_http::cookie::Cookie;
/// use chrono::Duration; /// use chrono::Duration;
/// ///
/// # fn main() {
/// let mut c = Cookie::new("foo", "bar"); /// let mut c = Cookie::new("foo", "bar");
/// assert!(c.expires().is_none()); /// assert!(c.expires().is_none());
/// assert!(c.max_age().is_none()); /// assert!(c.max_age().is_none());
@ -734,7 +729,6 @@ impl<'c> Cookie<'c> {
/// c.make_permanent(); /// c.make_permanent();
/// assert!(c.expires().is_some()); /// assert!(c.expires().is_some());
/// assert_eq!(c.max_age(), Some(Duration::days(365 * 20))); /// assert_eq!(c.max_age(), Some(Duration::days(365 * 20)));
/// # }
/// ``` /// ```
pub fn make_permanent(&mut self) { pub fn make_permanent(&mut self) {
let twenty_years = Duration::days(365 * 20); let twenty_years = Duration::days(365 * 20);

View file

@ -474,14 +474,12 @@ impl ResponseError for ContentTypeError {
/// default. /// default.
/// ///
/// ```rust /// ```rust
/// # extern crate actix_http;
/// # use std::io; /// # use std::io;
/// # use actix_http::*; /// # use actix_http::*;
/// ///
/// fn index(req: Request) -> Result<&'static str> { /// fn index(req: Request) -> Result<&'static str> {
/// Err(error::ErrorBadRequest(io::Error::new(io::ErrorKind::Other, "error"))) /// Err(error::ErrorBadRequest(io::Error::new(io::ErrorKind::Other, "error")))
/// } /// }
/// # fn main() {}
/// ``` /// ```
pub struct InternalError<T> { pub struct InternalError<T> {
cause: T, cause: T,

View file

@ -354,7 +354,6 @@ impl ResponseBuilder {
/// )) /// ))
/// .finish()) /// .finish())
/// } /// }
/// fn main() {}
/// ``` /// ```
#[doc(hidden)] #[doc(hidden)]
pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self { pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self {
@ -380,7 +379,6 @@ impl ResponseBuilder {
/// .header(http::header::CONTENT_TYPE, "application/json") /// .header(http::header::CONTENT_TYPE, "application/json")
/// .finish() /// .finish()
/// } /// }
/// fn main() {}
/// ``` /// ```
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
where where
@ -413,7 +411,6 @@ impl ResponseBuilder {
/// .set_header(http::header::CONTENT_TYPE, "application/json") /// .set_header(http::header::CONTENT_TYPE, "application/json")
/// .finish() /// .finish()
/// } /// }
/// fn main() {}
/// ``` /// ```
pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where where

View file

@ -21,8 +21,6 @@ use crate::Request;
/// Test `Request` builder /// Test `Request` builder
/// ///
/// ```rust,ignore /// ```rust,ignore
/// # extern crate http;
/// # extern crate actix_web;
/// # use http::{header, StatusCode}; /// # use http::{header, StatusCode};
/// # use actix_web::*; /// # use actix_web::*;
/// use actix_web::test::TestRequest; /// use actix_web::test::TestRequest;
@ -35,15 +33,13 @@ use crate::Request;
/// } /// }
/// } /// }
/// ///
/// fn main() { /// let resp = TestRequest::with_header("content-type", "text/plain")
/// let resp = TestRequest::with_header("content-type", "text/plain") /// .run(&index)
/// .run(&index) /// .unwrap();
/// .unwrap(); /// assert_eq!(resp.status(), StatusCode::OK);
/// assert_eq!(resp.status(), StatusCode::OK);
/// ///
/// let resp = TestRequest::default().run(&index).unwrap(); /// let resp = TestRequest::default().run(&index).unwrap();
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST); /// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// }
/// ``` /// ```
pub struct TestRequest(Option<Inner>); pub struct TestRequest(Option<Inner>);

View file

@ -12,7 +12,7 @@
//! [*Session*](struct.Session.html) extractor must be used. Session //! [*Session*](struct.Session.html) extractor must be used. Session
//! extractor allows us to get or set session data. //! extractor allows us to get or set session data.
//! //!
//! ```rust //! ```rust,no_run
//! use actix_web::{web, App, HttpServer, HttpResponse, Error}; //! use actix_web::{web, App, HttpServer, HttpResponse, Error};
//! use actix_session::{Session, CookieSession}; //! use actix_session::{Session, CookieSession};
//! //!
@ -28,8 +28,8 @@
//! Ok("Welcome!") //! Ok("Welcome!")
//! } //! }
//! //!
//! fn main() -> std::io::Result<()> { //! #[actix_rt::main]
//! # std::thread::spawn(|| //! async fn main() -> std::io::Result<()> {
//! HttpServer::new( //! HttpServer::new(
//! || App::new().wrap( //! || App::new().wrap(
//! CookieSession::signed(&[0; 32]) // <- create cookie based session middleware //! CookieSession::signed(&[0; 32]) // <- create cookie based session middleware
@ -37,9 +37,8 @@
//! ) //! )
//! .service(web::resource("/").to(|| HttpResponse::Ok()))) //! .service(web::resource("/").to(|| HttpResponse::Ok())))
//! .bind("127.0.0.1:59880")? //! .bind("127.0.0.1:59880")?
//! .run() //! .start()
//! # ); //! .await
//! # Ok(())
//! } //! }
//! ``` //! ```
use std::cell::RefCell; use std::cell::RefCell;

View file

@ -19,6 +19,6 @@ proc-macro2 = "^1"
[dev-dependencies] [dev-dependencies]
actix-rt = { version = "1.0.0-alpha.2" } actix-rt = { version = "1.0.0-alpha.2" }
actix-web = { version = "2.0.0-alpha.2" } actix-web = { version = "2.0.0-alpha.2" }
actix-http = { version = "0.3.0-alpha.2", features=["openssl"] } actix-http = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.2", features=["openssl"] } actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
futures = { version = "0.3.1" } futures = { version = "0.3.1" }

View file

@ -195,7 +195,7 @@ impl<T: AsyncRead + AsyncWrite + Unpin> AsyncSocket for Socket<T> {
pub struct BoxedSocket(Box<dyn AsyncSocket>); pub struct BoxedSocket(Box<dyn AsyncSocket>);
impl fmt::Debug for BoxedSocket { impl fmt::Debug for BoxedSocket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "BoxedSocket") write!(f, "BoxedSocket")
} }
} }

View file

@ -1,4 +1,9 @@
#![allow(clippy::borrow_interior_mutable_const)] #![deny(rust_2018_idioms, warnings)]
#![allow(
clippy::type_complexity,
clippy::borrow_interior_mutable_const,
clippy::needless_doctest_main
)]
//! An HTTP Client //! An HTTP Client
//! //!
//! ```rust //! ```rust
@ -11,9 +16,9 @@
//! let mut client = Client::default(); //! let mut client = Client::default();
//! //!
//! let response = client.get("http://www.rust-lang.org") // <- Create request builder //! let response = client.get("http://www.rust-lang.org") // <- Create request builder
//! .header("User-Agent", "Actix-web") //! .header("User-Agent", "Actix-web")
//! .send() // <- Send http request //! .send() // <- Send http request
//! .await; //! .await;
//! //!
//! println!("Response: {:?}", response); //! println!("Response: {:?}", response);
//! } //! }
@ -50,22 +55,18 @@ use self::connect::{Connect, ConnectorWrapper};
/// An HTTP Client /// An HTTP Client
/// ///
/// ```rust /// ```rust
/// use actix_rt::System;
/// use awc::Client; /// use awc::Client;
/// ///
/// fn main() { /// #[actix_rt::main]
/// System::new("test").block_on(async { /// async fn main() {
/// let mut client = Client::default(); /// let mut client = Client::default();
/// ///
/// client.get("http://www.rust-lang.org") // <- Create request builder /// let res = client.get("http://www.rust-lang.org") // <- Create request builder
/// .header("User-Agent", "Actix-web") /// .header("User-Agent", "Actix-web")
/// .send() // <- Send http request /// .send() // <- Send http request
/// .await /// .await; // <- send request and wait for response
/// .and_then(|response| { // <- server http response ///
/// println!("Response: {:?}", response); /// println!("Response: {:?}", res);
/// Ok(())
/// })
/// });
/// } /// }
/// ``` /// ```
#[derive(Clone)] #[derive(Clone)]

View file

@ -565,7 +565,7 @@ impl ClientRequest {
} }
impl fmt::Debug for ClientRequest { impl fmt::Debug for ClientRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!( writeln!(
f, f,
"\nClientRequest {:?} {}:{}", "\nClientRequest {:?} {}:{}",

View file

@ -29,11 +29,11 @@ impl<S> HttpMessage for ClientResponse<S> {
&self.head.headers &self.head.headers
} }
fn extensions(&self) -> Ref<Extensions> { fn extensions(&self) -> Ref<'_, Extensions> {
self.head.extensions() self.head.extensions()
} }
fn extensions_mut(&self) -> RefMut<Extensions> { fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.head.extensions_mut() self.head.extensions_mut()
} }
@ -43,7 +43,7 @@ impl<S> HttpMessage for ClientResponse<S> {
/// Load request cookies. /// Load request cookies.
#[inline] #[inline]
fn cookies(&self) -> Result<Ref<Vec<Cookie<'static>>>, CookieParseError> { fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
struct Cookies(Vec<Cookie<'static>>); struct Cookies(Vec<Cookie<'static>>);
if self.extensions().get::<Cookies>().is_none() { if self.extensions().get::<Cookies>().is_none() {
@ -131,13 +131,16 @@ where
{ {
type Item = Result<Bytes, PayloadError>; type Item = Result<Bytes, PayloadError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.get_mut().payload).poll_next(cx) Pin::new(&mut self.get_mut().payload).poll_next(cx)
} }
} }
impl<S> fmt::Debug for ClientResponse<S> { impl<S> fmt::Debug for ClientResponse<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?; writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?;
writeln!(f, " headers:")?; writeln!(f, " headers:")?;
for (key, val) in self.headers().iter() { for (key, val) in self.headers().iter() {
@ -203,7 +206,7 @@ where
{ {
type Output = Result<Bytes, PayloadError>; type Output = Result<Bytes, PayloadError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
if let Some(err) = this.err.take() { if let Some(err) = this.err.take() {
@ -295,7 +298,7 @@ where
{ {
type Output = Result<U, JsonPayloadError>; type Output = Result<U, JsonPayloadError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.err.take() { if let Some(err) = self.err.take() {
return Poll::Ready(Err(err)); return Poll::Ready(Err(err));
} }
@ -335,7 +338,7 @@ where
{ {
type Output = Result<Bytes, PayloadError>; type Output = Result<Bytes, PayloadError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
loop { loop {

View file

@ -62,7 +62,7 @@ impl SendClientRequest {
response_decompress: bool, response_decompress: bool,
timeout: Option<Duration>, timeout: Option<Duration>,
) -> SendClientRequest { ) -> SendClientRequest {
let delay = timeout.map(|t| delay_for(t)); let delay = timeout.map(delay_for);
SendClientRequest::Fut(send, delay, response_decompress) SendClientRequest::Fut(send, delay, response_decompress)
} }
} }
@ -71,7 +71,7 @@ impl Future for SendClientRequest {
type Output = type Output =
Result<ClientResponse<Decoder<Payload<PayloadStream>>>, SendRequestError>; Result<ClientResponse<Decoder<Payload<PayloadStream>>>, SendRequestError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut(); let this = self.get_mut();
match this { match this {

View file

@ -304,7 +304,7 @@ impl WebsocketsRequest {
let (head, framed) = if let Some(to) = self.config.timeout { let (head, framed) = if let Some(to) = self.config.timeout {
timeout(to, fut) timeout(to, fut)
.await .await
.map_err(|_| SendRequestError::Timeout.into()) .map_err(|_| SendRequestError::Timeout)
.and_then(|res| res)? .and_then(|res| res)?
} else { } else {
fut.await? fut.await?
@ -379,7 +379,7 @@ impl WebsocketsRequest {
} }
impl fmt::Debug for WebsocketsRequest { impl fmt::Debug for WebsocketsRequest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!( writeln!(
f, f,
"\nWebsocketsRequest {}:{}", "\nWebsocketsRequest {}:{}",

View file

@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use brotli::write::BrotliEncoder; use brotli::CompressorWriter;
use bytes::Bytes; use bytes::Bytes;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
use flate2::write::GzEncoder; use flate2::write::GzEncoder;
@ -514,9 +514,9 @@ async fn test_client_brotli_encoding() {
let srv = TestServer::start(|| { let srv = TestServer::start(|| {
HttpService::new(App::new().service(web::resource("/").route(web::to( HttpService::new(App::new().service(web::resource("/").route(web::to(
|data: Bytes| { |data: Bytes| {
let mut e = BrotliEncoder::new(Vec::new(), 5); let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
e.write_all(&data).unwrap(); e.write_all(&data).unwrap();
let data = e.finish().unwrap(); let data = e.into_inner();
HttpResponse::Ok() HttpResponse::Ok()
.header("content-encoding", "br") .header("content-encoding", "br")
.body(data) .body(data)
@ -534,39 +534,36 @@ async fn test_client_brotli_encoding() {
assert_eq!(bytes, Bytes::from_static(STR.as_ref())); assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
} }
// #[actix_rt::test] #[actix_rt::test]
// async fn test_client_brotli_encoding_large_random() { async fn test_client_brotli_encoding_large_random() {
// let data = rand::thread_rng() let data = rand::thread_rng()
// .sample_iter(&rand::distributions::Alphanumeric) .sample_iter(&rand::distributions::Alphanumeric)
// .take(70_000) .take(70_000)
// .collect::<String>(); .collect::<String>();
// let srv = test::TestServer::start(|app| { let srv = TestServer::start(|| {
// app.handler(|req: &HttpRequest| { HttpService::new(App::new().service(web::resource("/").route(web::to(
// req.body() |data: Bytes| {
// .and_then(move |bytes: Bytes| { let mut e = CompressorWriter::new(Vec::new(), 0, 5, 0);
// Ok(HttpResponse::Ok() e.write_all(&data).unwrap();
// .content_encoding(http::ContentEncoding::Gzip) let data = e.into_inner();
// .body(bytes)) HttpResponse::Ok()
// }) .header("content-encoding", "br")
// .responder() .body(data)
// }) },
// }); ))))
.tcp()
});
// // client request // client request
// let request = srv let mut response = srv.post("/").send_body(data.clone()).await.unwrap();
// .client(http::Method::POST, "/") assert!(response.status().is_success());
// .content_encoding(http::ContentEncoding::Br)
// .body(data.clone())
// .unwrap();
// let response = request.send().await.unwrap();
// assert!(response.status().is_success());
// // read response // read response
// let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
// assert_eq!(bytes.len(), data.len()); assert_eq!(bytes.len(), data.len());
// assert_eq!(bytes, Bytes::from(data)); assert_eq!(bytes, Bytes::from(data));
// } }
// #[actix_rt::test] // #[actix_rt::test]
// async fn test_client_deflate_encoding() { // async fn test_client_deflate_encoding() {

View file

@ -38,7 +38,7 @@ pub struct App<T, B> {
data_factories: Vec<FnDataFactory>, data_factories: Vec<FnDataFactory>,
config: AppConfigInner, config: AppConfigInner,
external: Vec<ResourceDef>, external: Vec<ResourceDef>,
_t: PhantomData<(B)>, _t: PhantomData<B>,
} }
impl App<AppEntry, Body> { impl App<AppEntry, Body> {
@ -93,13 +93,11 @@ where
/// HttpResponse::Ok() /// HttpResponse::Ok()
/// } /// }
/// ///
/// fn main() { /// let app = App::new()
/// let app = App::new() /// .data(MyData{ counter: Cell::new(0) })
/// .data(MyData{ counter: Cell::new(0) }) /// .service(
/// .service( /// web::resource("/index.html").route(
/// web::resource("/index.html").route( /// web::get().to(index)));
/// web::get().to(index)));
/// }
/// ``` /// ```
pub fn data<U: 'static>(mut self, data: U) -> Self { pub fn data<U: 'static>(mut self, data: U) -> Self {
self.data.push(Box::new(Data::new(data))); self.data.push(Box::new(Data::new(data)));

View file

@ -195,6 +195,7 @@ macro_rules! tuple_from_req ({$fut_type:ident, $(($n:tt, $T:ident)),+} => {
/// FromRequest implementation for tuple /// FromRequest implementation for tuple
#[doc(hidden)] #[doc(hidden)]
#[allow(unused_parens)]
impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+) impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+)
{ {
type Error = Error; type Error = Error;

View file

@ -259,16 +259,15 @@ impl Guard for HeaderGuard {
/// Return predicate that matches if request contains specified Host name. /// Return predicate that matches if request contains specified Host name.
/// ///
/// ```rust,ignore /// ```rust
/// # extern crate actix_web; /// use actix_web::{web, guard::Host, App, HttpResponse};
/// use actix_web::{guard::Host, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// App::new().resource("/index.html", |r| { /// App::new().service(
/// r.route() /// web::resource("/index.html")
/// .guard(Host("www.rust-lang.org")) /// .guard(Host("www.rust-lang.org"))
/// .f(|_| HttpResponse::MethodNotAllowed()) /// .to(|| HttpResponse::MethodNotAllowed())
/// }); /// );
/// } /// }
/// ``` /// ```
pub fn Host<H: AsRef<str>>(host: H) -> HostGuard { pub fn Host<H: AsRef<str>>(host: H) -> HostGuard {

View file

@ -1,25 +1,27 @@
#![deny(rust_2018_idioms, warnings)] #![deny(rust_2018_idioms, warnings)]
#![allow(clippy::type_complexity, clippy::borrow_interior_mutable_const)] #![allow(
clippy::needless_doctest_main,
clippy::type_complexity,
clippy::borrow_interior_mutable_const
)]
//! Actix web is a small, pragmatic, and extremely fast web framework //! Actix web is a small, pragmatic, and extremely fast web framework
//! for Rust. //! for Rust.
//! //!
//! ```rust //! ```rust,no_run
//! use actix_web::{web, App, Responder, HttpServer}; //! use actix_web::{web, App, Responder, HttpServer};
//! # use std::thread;
//! //!
//! async fn index(info: web::Path<(String, u32)>) -> impl Responder { //! async fn index(info: web::Path<(String, u32)>) -> impl Responder {
//! format!("Hello {}! id:{}", info.0, info.1) //! format!("Hello {}! id:{}", info.0, info.1)
//! } //! }
//! //!
//! fn main() -> std::io::Result<()> { //! #[actix_rt::main]
//! # thread::spawn(|| { //! async fn main() -> std::io::Result<()> {
//! HttpServer::new(|| App::new().service( //! HttpServer::new(|| App::new().service(
//! web::resource("/{name}/{id}/index.html").to(index)) //! web::resource("/{name}/{id}/index.html").to(index))
//! ) //! )
//! .bind("127.0.0.1:8080")? //! .bind("127.0.0.1:8080")?
//! .run() //! .start()
//! # }); //! .await
//! # Ok(())
//! } //! }
//! ``` //! ```
//! //!
@ -170,7 +172,6 @@ pub mod client {
//! An HTTP Client //! An HTTP Client
//! //!
//! ```rust //! ```rust
//! use actix_rt::System;
//! use actix_web::client::Client; //! use actix_web::client::Client;
//! //!
//! #[actix_rt::main] //! #[actix_rt::main]

View file

@ -140,7 +140,7 @@ where
#[pin] #[pin]
fut: S::Future, fut: S::Future,
encoding: ContentEncoding, encoding: ContentEncoding,
_t: PhantomData<(B)>, _t: PhantomData<B>,
} }
impl<S, B> Future for CompressResponse<S, B> impl<S, B> Future for CompressResponse<S, B>
@ -178,6 +178,7 @@ struct AcceptEncoding {
impl Eq for AcceptEncoding {} impl Eq for AcceptEncoding {}
impl Ord for AcceptEncoding { impl Ord for AcceptEncoding {
#[allow(clippy::comparison_chain)]
fn cmp(&self, other: &AcceptEncoding) -> cmp::Ordering { fn cmp(&self, other: &AcceptEncoding) -> cmp::Ordering {
if self.quality > other.quality { if self.quality > other.quality {
cmp::Ordering::Less cmp::Ordering::Less

View file

@ -44,13 +44,11 @@ pub use crate::types::*;
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/users/{userid}/{friend}")
/// web::resource("/users/{userid}/{friend}") /// .route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::get().to(|| HttpResponse::Ok())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) /// );
/// );
/// }
/// ``` /// ```
pub fn resource(path: &str) -> Resource { pub fn resource(path: &str) -> Resource {
Resource::new(path) Resource::new(path)
@ -64,14 +62,12 @@ pub fn resource(path: &str) -> Resource {
/// ```rust /// ```rust
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::scope("/{project_id}")
/// web::scope("/{project_id}") /// .service(web::resource("/path1").to(|| HttpResponse::Ok()))
/// .service(web::resource("/path1").to(|| HttpResponse::Ok())) /// .service(web::resource("/path2").to(|| HttpResponse::Ok()))
/// .service(web::resource("/path2").to(|| HttpResponse::Ok())) /// .service(web::resource("/path3").to(|| HttpResponse::MethodNotAllowed()))
/// .service(web::resource("/path3").to(|| HttpResponse::MethodNotAllowed())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, three routes get added: /// In the above example, three routes get added:
@ -93,12 +89,10 @@ pub fn route() -> Route {
/// ```rust /// ```rust
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/{project_id}")
/// web::resource("/{project_id}") /// .route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::get().to(|| HttpResponse::Ok())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, one `GET` route get added: /// In the above example, one `GET` route get added:
@ -113,12 +107,10 @@ pub fn get() -> Route {
/// ```rust /// ```rust
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/{project_id}")
/// web::resource("/{project_id}") /// .route(web::post().to(|| HttpResponse::Ok()))
/// .route(web::post().to(|| HttpResponse::Ok())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, one `POST` route get added: /// In the above example, one `POST` route get added:
@ -133,12 +125,10 @@ pub fn post() -> Route {
/// ```rust /// ```rust
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/{project_id}")
/// web::resource("/{project_id}") /// .route(web::put().to(|| HttpResponse::Ok()))
/// .route(web::put().to(|| HttpResponse::Ok())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, one `PUT` route get added: /// In the above example, one `PUT` route get added:
@ -153,12 +143,10 @@ pub fn put() -> Route {
/// ```rust /// ```rust
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/{project_id}")
/// web::resource("/{project_id}") /// .route(web::patch().to(|| HttpResponse::Ok()))
/// .route(web::patch().to(|| HttpResponse::Ok())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, one `PATCH` route get added: /// In the above example, one `PATCH` route get added:
@ -173,12 +161,10 @@ pub fn patch() -> Route {
/// ```rust /// ```rust
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/{project_id}")
/// web::resource("/{project_id}") /// .route(web::delete().to(|| HttpResponse::Ok()))
/// .route(web::delete().to(|| HttpResponse::Ok())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, one `DELETE` route get added: /// In the above example, one `DELETE` route get added:
@ -193,12 +179,10 @@ pub fn delete() -> Route {
/// ```rust /// ```rust
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/{project_id}")
/// web::resource("/{project_id}") /// .route(web::head().to(|| HttpResponse::Ok()))
/// .route(web::head().to(|| HttpResponse::Ok())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, one `HEAD` route get added: /// In the above example, one `HEAD` route get added:
@ -213,12 +197,10 @@ pub fn head() -> Route {
/// ```rust /// ```rust
/// use actix_web::{web, http, App, HttpResponse}; /// use actix_web::{web, http, App, HttpResponse};
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::resource("/{project_id}")
/// web::resource("/{project_id}") /// .route(web::method(http::Method::GET).to(|| HttpResponse::Ok()))
/// .route(web::method(http::Method::GET).to(|| HttpResponse::Ok())) /// );
/// );
/// }
/// ``` /// ```
/// ///
/// In the above example, one `GET` route get added: /// In the above example, one `GET` route get added:
@ -261,13 +243,11 @@ where
/// Ok(req.into_response(HttpResponse::Ok().finish())) /// Ok(req.into_response(HttpResponse::Ok().finish()))
/// } /// }
/// ///
/// fn main() { /// let app = App::new().service(
/// let app = App::new().service( /// web::service("/users/*")
/// web::service("/users/*") /// .guard(guard::Header("content-type", "text/plain"))
/// .guard(guard::Header("content-type", "text/plain")) /// .finish(my_service)
/// .finish(my_service) /// );
/// );
/// }
/// ``` /// ```
pub fn service(path: &str) -> WebService { pub fn service(path: &str) -> WebService {
WebService::new(path) WebService::new(path)

View file

@ -6,7 +6,7 @@ use actix_http::http::header::{
}; };
use actix_http::{Error, HttpService, Response}; use actix_http::{Error, HttpService, Response};
use actix_http_test::TestServer; use actix_http_test::TestServer;
use brotli::write::{BrotliDecoder, BrotliEncoder}; use brotli::DecompressorWriter;
use bytes::Bytes; use bytes::Bytes;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
use flate2::write::{GzEncoder, ZlibDecoder, ZlibEncoder}; use flate2::write::{GzEncoder, ZlibDecoder, ZlibEncoder};
@ -322,9 +322,9 @@ async fn test_body_br_streaming() {
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
// decode br // decode br
let mut e = BrotliDecoder::new(Vec::with_capacity(2048)); let mut e = DecompressorWriter::new(Vec::with_capacity(2048), 0);
e.write_all(bytes.as_ref()).unwrap(); e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap(); let dec = e.into_inner().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
} }
@ -433,9 +433,9 @@ async fn test_body_brotli() {
let bytes = response.body().await.unwrap(); let bytes = response.body().await.unwrap();
// decode brotli // decode brotli
let mut e = BrotliDecoder::new(Vec::with_capacity(2048)); let mut e = DecompressorWriter::new(Vec::with_capacity(2048), 0);
e.write_all(bytes.as_ref()).unwrap(); e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap(); let dec = e.into_inner().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref())); assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
} }