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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -19,6 +19,6 @@ proc-macro2 = "^1"
[dev-dependencies]
actix-rt = { version = "1.0.0-alpha.2" }
actix-web = { version = "2.0.0-alpha.2" }
actix-http = { version = "0.3.0-alpha.2", features=["openssl"] }
actix-http-test = { version = "0.3.0-alpha.2", features=["openssl"] }
actix-http = { version = "1.0.0-alpha.3", features=["openssl"] }
actix-http-test = { version = "1.0.0-alpha.3", features=["openssl"] }
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>);
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")
}
}

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
//!
//! ```rust
@ -50,22 +55,18 @@ use self::connect::{Connect, ConnectorWrapper};
/// An HTTP Client
///
/// ```rust
/// use actix_rt::System;
/// use awc::Client;
///
/// fn main() {
/// System::new("test").block_on(async {
/// #[actix_rt::main]
/// async fn main() {
/// 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")
/// .send() // <- Send http request
/// .await
/// .and_then(|response| { // <- server http response
/// println!("Response: {:?}", response);
/// Ok(())
/// })
/// });
/// .await; // <- send request and wait for response
///
/// println!("Response: {:?}", res);
/// }
/// ```
#[derive(Clone)]

View File

@ -565,7 +565,7 @@ impl 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!(
f,
"\nClientRequest {:?} {}:{}",

View File

@ -29,11 +29,11 @@ impl<S> HttpMessage for ClientResponse<S> {
&self.head.headers
}
fn extensions(&self) -> Ref<Extensions> {
fn extensions(&self) -> Ref<'_, Extensions> {
self.head.extensions()
}
fn extensions_mut(&self) -> RefMut<Extensions> {
fn extensions_mut(&self) -> RefMut<'_, Extensions> {
self.head.extensions_mut()
}
@ -43,7 +43,7 @@ impl<S> HttpMessage for ClientResponse<S> {
/// Load request cookies.
#[inline]
fn cookies(&self) -> Result<Ref<Vec<Cookie<'static>>>, CookieParseError> {
fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
struct Cookies(Vec<Cookie<'static>>);
if self.extensions().get::<Cookies>().is_none() {
@ -131,13 +131,16 @@ where
{
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)
}
}
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, " headers:")?;
for (key, val) in self.headers().iter() {
@ -203,7 +206,7 @@ where
{
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();
if let Some(err) = this.err.take() {
@ -295,7 +298,7 @@ where
{
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() {
return Poll::Ready(Err(err));
}
@ -335,7 +338,7 @@ where
{
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();
loop {

View File

@ -62,7 +62,7 @@ impl SendClientRequest {
response_decompress: bool,
timeout: Option<Duration>,
) -> SendClientRequest {
let delay = timeout.map(|t| delay_for(t));
let delay = timeout.map(delay_for);
SendClientRequest::Fut(send, delay, response_decompress)
}
}
@ -71,7 +71,7 @@ impl Future for SendClientRequest {
type Output =
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();
match this {

View File

@ -304,7 +304,7 @@ impl WebsocketsRequest {
let (head, framed) = if let Some(to) = self.config.timeout {
timeout(to, fut)
.await
.map_err(|_| SendRequestError::Timeout.into())
.map_err(|_| SendRequestError::Timeout)
.and_then(|res| res)?
} else {
fut.await?
@ -379,7 +379,7 @@ impl 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!(
f,
"\nWebsocketsRequest {}:{}",

View File

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

View File

@ -38,7 +38,7 @@ pub struct App<T, B> {
data_factories: Vec<FnDataFactory>,
config: AppConfigInner,
external: Vec<ResourceDef>,
_t: PhantomData<(B)>,
_t: PhantomData<B>,
}
impl App<AppEntry, Body> {
@ -93,13 +93,11 @@ where
/// HttpResponse::Ok()
/// }
///
/// fn main() {
/// let app = App::new()
/// .data(MyData{ counter: Cell::new(0) })
/// .service(
/// web::resource("/index.html").route(
/// web::get().to(index)));
/// }
/// ```
pub fn data<U: 'static>(mut self, data: U) -> Self {
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
#[doc(hidden)]
#[allow(unused_parens)]
impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+)
{
type Error = Error;

View File

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

View File

@ -1,25 +1,27 @@
#![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
//! for Rust.
//!
//! ```rust
//! ```rust,no_run
//! use actix_web::{web, App, Responder, HttpServer};
//! # use std::thread;
//!
//! async fn index(info: web::Path<(String, u32)>) -> impl Responder {
//! format!("Hello {}! id:{}", info.0, info.1)
//! }
//!
//! fn main() -> std::io::Result<()> {
//! # thread::spawn(|| {
//! #[actix_rt::main]
//! async fn main() -> std::io::Result<()> {
//! HttpServer::new(|| App::new().service(
//! web::resource("/{name}/{id}/index.html").to(index))
//! )
//! .bind("127.0.0.1:8080")?
//! .run()
//! # });
//! # Ok(())
//! .start()
//! .await
//! }
//! ```
//!
@ -170,7 +172,6 @@ pub mod client {
//! An HTTP Client
//!
//! ```rust
//! use actix_rt::System;
//! use actix_web::client::Client;
//!
//! #[actix_rt::main]

View File

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

View File

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

View File

@ -6,7 +6,7 @@ use actix_http::http::header::{
};
use actix_http::{Error, HttpService, Response};
use actix_http_test::TestServer;
use brotli::write::{BrotliDecoder, BrotliEncoder};
use brotli::DecompressorWriter;
use bytes::Bytes;
use flate2::read::GzDecoder;
use flate2::write::{GzEncoder, ZlibDecoder, ZlibEncoder};
@ -322,9 +322,9 @@ async fn test_body_br_streaming() {
let bytes = response.body().await.unwrap();
// 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();
let dec = e.finish().unwrap();
let dec = e.into_inner().unwrap();
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();
// 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();
let dec = e.finish().unwrap();
let dec = e.into_inner().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
}