Merge branch 'master' into feature/h1_pending_timer

This commit is contained in:
fakeshadow 2021-03-25 07:51:11 -07:00 committed by GitHub
commit ab9ed4e2c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 137 additions and 144 deletions

View File

@ -19,7 +19,7 @@ use crate::{
/// ///
/// `Files` service must be registered with `App::service()` method. /// `Files` service must be registered with `App::service()` method.
/// ///
/// ```rust /// ```
/// use actix_web::App; /// use actix_web::App;
/// use actix_files::Files; /// use actix_files::Files;
/// ///

View File

@ -3,7 +3,7 @@
//! Provides a non-blocking service for serving static files from disk. //! Provides a non-blocking service for serving static files from disk.
//! //!
//! # Example //! # Example
//! ```rust //! ```
//! use actix_web::App; //! use actix_web::App;
//! use actix_files::Files; //! use actix_files::Files;
//! //!

View File

@ -60,7 +60,7 @@ impl NamedFile {
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```
/// use actix_files::NamedFile; /// use actix_files::NamedFile;
/// use std::io::{self, Write}; /// use std::io::{self, Write};
/// use std::env; /// use std::env;
@ -137,7 +137,7 @@ impl NamedFile {
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```
/// use actix_files::NamedFile; /// use actix_files::NamedFile;
/// ///
/// let file = NamedFile::open("foo.txt"); /// let file = NamedFile::open("foo.txt");
@ -156,7 +156,7 @@ impl NamedFile {
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```
/// # use std::io; /// # use std::io;
/// use actix_files::NamedFile; /// use actix_files::NamedFile;
/// ///

View File

@ -26,7 +26,7 @@ use socket2::{Domain, Protocol, Socket, Type};
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```
/// use actix_http::HttpService; /// use actix_http::HttpService;
/// use actix_http_test::TestServer; /// use actix_http_test::TestServer;
/// use actix_web::{web, App, HttpResponse, Error}; /// use actix_web::{web, App, HttpResponse, Error};

View File

@ -47,7 +47,7 @@ enum SslConnector {
/// The `Connector` type uses a builder-like combinator pattern for service /// The `Connector` type uses a builder-like combinator pattern for service
/// construction that finishes by calling the `.finish()` method. /// construction that finishes by calling the `.finish()` method.
/// ///
/// ```rust,ignore /// ```ignore
/// use std::time::Duration; /// use std::time::Duration;
/// use actix_http::client::Connector; /// use actix_http::client::Connector;
/// ///

View File

@ -483,7 +483,7 @@ where
/// response as opposite to *INTERNAL SERVER ERROR* which is defined by /// response as opposite to *INTERNAL SERVER ERROR* which is defined by
/// default. /// default.
/// ///
/// ```rust /// ```
/// # use std::io; /// # use std::io;
/// # use actix_http::*; /// # use actix_http::*;
/// ///

View File

@ -36,7 +36,7 @@ use crate::header::{
/// builder.insert_header(CacheControl(vec![CacheDirective::MaxAge(86400u32)])); /// builder.insert_header(CacheControl(vec![CacheDirective::MaxAge(86400u32)]));
/// ``` /// ```
/// ///
/// ```rust /// ```
/// use actix_http::Response; /// use actix_http::Response;
/// use actix_http::http::header::{CacheControl, CacheDirective}; /// use actix_http::http::header::{CacheControl, CacheDirective};
/// ///

View File

@ -357,7 +357,7 @@ impl ResponseBuilder {
/// Insert a header, replacing any that were set with an equivalent field name. /// Insert a header, replacing any that were set with an equivalent field name.
/// ///
/// ```rust /// ```
/// # use actix_http::Response; /// # use actix_http::Response;
/// use actix_http::http::header::ContentType; /// use actix_http::http::header::ContentType;
/// ///
@ -384,7 +384,7 @@ impl ResponseBuilder {
/// Append a header, keeping any that were set with an equivalent field name. /// Append a header, keeping any that were set with an equivalent field name.
/// ///
/// ```rust /// ```
/// # use actix_http::Response; /// # use actix_http::Response;
/// use actix_http::http::header::ContentType; /// use actix_http::http::header::ContentType;
/// ///
@ -525,7 +525,7 @@ impl ResponseBuilder {
/// Set a cookie /// Set a cookie
/// ///
/// ```rust /// ```
/// use actix_http::{http, Request, Response}; /// use actix_http::{http, Request, Response};
/// ///
/// fn index(req: Request) -> Response { /// fn index(req: Request) -> Response {
@ -555,7 +555,7 @@ impl ResponseBuilder {
/// Remove cookie /// Remove cookie
/// ///
/// ```rust /// ```
/// use actix_http::{http, Request, Response, HttpMessage}; /// use actix_http::{http, Request, Response, HttpMessage};
/// ///
/// fn index(req: Request) -> Response { /// fn index(req: Request) -> Response {

View File

@ -27,7 +27,7 @@ use crate::{
/// Test `Request` builder /// Test `Request` builder
/// ///
/// ```rust,ignore /// ```ignore
/// # use http::{header, StatusCode}; /// # use http::{header, StatusCode};
/// # use actix_web::*; /// # use actix_web::*;
/// use actix_web::test::TestRequest; /// use actix_web::test::TestRequest;

View File

@ -10,7 +10,7 @@ use crate::server::Multipart;
/// ///
/// ## Server example /// ## Server example
/// ///
/// ```rust /// ```
/// use futures_util::stream::{Stream, StreamExt}; /// use futures_util::stream::{Stream, StreamExt};
/// use actix_web::{web, HttpResponse, Error}; /// use actix_web::{web, HttpResponse, Error};
/// use actix_multipart as mp; /// use actix_multipart as mp;

View File

@ -82,7 +82,7 @@ mod route;
/// ///
/// # Example /// # Example
/// ///
/// ```rust /// ```
/// # use actix_web::HttpResponse; /// # use actix_web::HttpResponse;
/// # use actix_web_codegen::route; /// # use actix_web_codegen::route;
/// #[route("/test", method="GET", method="HEAD")] /// #[route("/test", method="GET", method="HEAD")]
@ -127,7 +127,7 @@ code, e.g `my_guard` or `my_module::my_guard`.
# Example # Example
```rust ```
# use actix_web::HttpResponse; # use actix_web::HttpResponse;
# use actix_web_codegen::"#, stringify!($method), "; # use actix_web_codegen::"#, stringify!($method), ";
#[", stringify!($method), r#"("/")] #[", stringify!($method), r#"("/")]
@ -162,7 +162,7 @@ method_macro! {
/// This macro can be applied with `#[actix_web::main]` when used in Actix Web applications. /// This macro can be applied with `#[actix_web::main]` when used in Actix Web applications.
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// #[actix_web_codegen::main] /// #[actix_web_codegen::main]
/// async fn main() { /// async fn main() {
/// async { println!("Hello world"); }.await /// async { println!("Hello world"); }.await

View File

@ -131,7 +131,7 @@ pub use self::sender::SendClientRequest;
/// ///
/// ## Examples /// ## Examples
/// ///
/// ```rust /// ```
/// use awc::Client; /// use awc::Client;
/// ///
/// #[actix_rt::main] /// #[actix_rt::main]

View File

@ -36,7 +36,7 @@ cfg_if::cfg_if! {
/// This type can be used to construct an instance of `ClientRequest` through a /// This type can be used to construct an instance of `ClientRequest` through a
/// builder-like pattern. /// builder-like pattern.
/// ///
/// ```rust /// ```
/// #[actix_rt::main] /// #[actix_rt::main]
/// async fn main() { /// async fn main() {
/// let response = awc::Client::new() /// let response = awc::Client::new()
@ -190,7 +190,7 @@ impl ClientRequest {
/// Append a header, keeping any that were set with an equivalent field name. /// Append a header, keeping any that were set with an equivalent field name.
/// ///
/// ```rust /// ```
/// # #[actix_rt::main] /// # #[actix_rt::main]
/// # async fn main() { /// # async fn main() {
/// # use awc::Client; /// # use awc::Client;
@ -271,7 +271,7 @@ impl ClientRequest {
/// Set a cookie /// Set a cookie
/// ///
/// ```rust /// ```
/// #[actix_rt::main] /// #[actix_rt::main]
/// async fn main() { /// async fn main() {
/// let resp = awc::Client::new().get("https://www.rust-lang.org") /// let resp = awc::Client::new().get("https://www.rust-lang.org")

View File

@ -228,12 +228,13 @@ impl<S> fmt::Debug for ClientResponse<S> {
} }
} }
const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
/// Future that resolves to a complete HTTP message body. /// Future that resolves to a complete HTTP message body.
pub struct MessageBody<S> { pub struct MessageBody<S> {
length: Option<usize>, length: Option<usize>,
err: Option<PayloadError>,
timeout: ResponseTimeout, timeout: ResponseTimeout,
fut: Option<ReadBody<S>>, body: Result<ReadBody<S>, Option<PayloadError>>,
} }
impl<S> MessageBody<S> impl<S> MessageBody<S>
@ -242,41 +243,38 @@ where
{ {
/// Create `MessageBody` for request. /// Create `MessageBody` for request.
pub fn new(res: &mut ClientResponse<S>) -> MessageBody<S> { pub fn new(res: &mut ClientResponse<S>) -> MessageBody<S> {
let mut len = None; let length = match res.headers().get(&header::CONTENT_LENGTH) {
if let Some(l) = res.headers().get(&header::CONTENT_LENGTH) { Some(value) => {
if let Ok(s) = l.to_str() { let len = value.to_str().ok().and_then(|s| s.parse::<usize>().ok());
if let Ok(l) = s.parse::<usize>() {
len = Some(l) match len {
} else { None => return Self::err(PayloadError::UnknownLength),
return Self::err(PayloadError::UnknownLength); len => len,
} }
} else {
return Self::err(PayloadError::UnknownLength);
} }
} None => None,
};
MessageBody { MessageBody {
length: len, length,
err: None,
timeout: std::mem::take(&mut res.timeout), timeout: std::mem::take(&mut res.timeout),
fut: Some(ReadBody::new(res.take_payload(), 262_144)), body: Ok(ReadBody::new(res.take_payload(), DEFAULT_BODY_LIMIT)),
} }
} }
/// Change max size of payload. By default max size is 256kB /// Change max size of payload. By default max size is 2048kB
pub fn limit(mut self, limit: usize) -> Self { pub fn limit(mut self, limit: usize) -> Self {
if let Some(ref mut fut) = self.fut { if let Ok(ref mut body) = self.body {
fut.limit = limit; body.limit = limit;
} }
self self
} }
fn err(e: PayloadError) -> Self { fn err(e: PayloadError) -> Self {
MessageBody { MessageBody {
fut: None,
err: Some(e),
length: None, length: None,
timeout: ResponseTimeout::default(), timeout: ResponseTimeout::default(),
body: Err(Some(e)),
} }
} }
} }
@ -290,19 +288,20 @@ where
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() { match this.body {
return Poll::Ready(Err(err)); Err(ref mut err) => Poll::Ready(Err(err.take().unwrap())),
} Ok(ref mut body) => {
if let Some(len) = this.length.take() {
if len > body.limit {
return Poll::Ready(Err(PayloadError::Overflow));
}
}
if let Some(len) = this.length.take() { this.timeout.poll_timeout(cx)?;
if len > this.fut.as_ref().unwrap().limit {
return Poll::Ready(Err(PayloadError::Overflow)); Pin::new(body).poll(cx)
} }
} }
this.timeout.poll_timeout(cx)?;
Pin::new(&mut this.fut.as_mut().unwrap()).poll(cx)
} }
} }
@ -415,7 +414,7 @@ impl<S> ReadBody<S> {
fn new(stream: Payload<S>, limit: usize) -> Self { fn new(stream: Payload<S>, limit: usize) -> Self {
Self { Self {
stream, stream,
buf: BytesMut::with_capacity(std::cmp::min(limit, 32768)), buf: BytesMut::new(),
limit, limit,
} }
} }
@ -430,20 +429,14 @@ where
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 { while let Some(chunk) = ready!(Pin::new(&mut this.stream).poll_next(cx)?) {
return match Pin::new(&mut this.stream).poll_next(cx)? { if (this.buf.len() + chunk.len()) > this.limit {
Poll::Ready(Some(chunk)) => { return Poll::Ready(Err(PayloadError::Overflow));
if (this.buf.len() + chunk.len()) > this.limit { }
Poll::Ready(Err(PayloadError::Overflow)) this.buf.extend_from_slice(&chunk);
} else {
this.buf.extend_from_slice(&chunk);
continue;
}
}
Poll::Ready(None) => Poll::Ready(Ok(this.buf.split().freeze())),
Poll::Pending => Poll::Pending,
};
} }
Poll::Ready(Ok(this.buf.split().freeze()))
} }
} }
@ -462,7 +455,7 @@ mod tests {
_ => unreachable!("error"), _ => unreachable!("error"),
} }
let mut req = TestResponse::with_header(header::CONTENT_LENGTH, "1000000").finish(); let mut req = TestResponse::with_header(header::CONTENT_LENGTH, "10000000").finish();
match req.body().await.err().unwrap() { match req.body().await.err().unwrap() {
PayloadError::Overflow => {} PayloadError::Overflow => {}
_ => unreachable!("error"), _ => unreachable!("error"),

View File

@ -9,7 +9,7 @@ use actix_web::test::{init_service, ok_service, TestRequest};
/// Criterion Benchmark for async Service /// Criterion Benchmark for async Service
/// Should be used from within criterion group: /// Should be used from within criterion group:
/// ```rust,ignore /// ```ignore
/// let mut criterion: ::criterion::Criterion<_> = /// let mut criterion: ::criterion::Criterion<_> =
/// ::criterion::Criterion::default().configure_from_args(); /// ::criterion::Criterion::default().configure_from_args();
/// bench_async_service(&mut criterion, ok_service(), "async_service_direct"); /// bench_async_service(&mut criterion, ok_service(), "async_service_direct");

View File

@ -79,7 +79,7 @@ where
/// uses `Arc` so data could be created outside of app factory and clones could /// uses `Arc` so data could be created outside of app factory and clones could
/// be stored via `App::app_data()` method. /// be stored via `App::app_data()` method.
/// ///
/// ```rust /// ```
/// use std::cell::Cell; /// use std::cell::Cell;
/// use actix_web::{web, App, HttpResponse, Responder}; /// use actix_web::{web, App, HttpResponse, Responder};
/// ///
@ -152,7 +152,7 @@ where
/// different module or even library. For example, /// different module or even library. For example,
/// some of the resource's configuration could be moved to different module. /// some of the resource's configuration could be moved to different module.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// // this function could be located in different module /// // this function could be located in different module
@ -185,7 +185,7 @@ where
/// This method can be used multiple times with same path, in that case /// This method can be used multiple times with same path, in that case
/// multiple resources with one route would be registered for same resource path. /// multiple resources with one route would be registered for same resource path.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// async fn index(data: web::Path<(String, String)>) -> &'static str { /// async fn index(data: web::Path<(String, String)>) -> &'static str {
@ -228,7 +228,7 @@ where
/// ///
/// It is possible to use services like `Resource`, `Route`. /// It is possible to use services like `Resource`, `Route`.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// async fn index() -> &'static str { /// async fn index() -> &'static str {
@ -246,7 +246,7 @@ where
/// ///
/// It is also possible to use static files as default service. /// It is also possible to use static files as default service.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -283,7 +283,7 @@ where
/// and are never considered for matching at request time. Calls to /// and are never considered for matching at request time. Calls to
/// `HttpRequest::url_for()` will work as expected. /// `HttpRequest::url_for()` will work as expected.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpRequest, HttpResponse, Result}; /// use actix_web::{web, App, HttpRequest, HttpResponse, Result};
/// ///
/// async fn index(req: HttpRequest) -> Result<HttpResponse> { /// async fn index(req: HttpRequest) -> Result<HttpResponse> {
@ -325,7 +325,7 @@ where
/// the builder chain. Consequently, the *first* middleware registered /// the builder chain. Consequently, the *first* middleware registered
/// in the builder chain is the *last* to execute during request processing. /// in the builder chain is the *last* to execute during request processing.
/// ///
/// ```rust /// ```
/// use actix_service::Service; /// use actix_service::Service;
/// use actix_web::{middleware, web, App}; /// use actix_web::{middleware, web, App};
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};
@ -382,7 +382,7 @@ where
/// ///
/// Use middleware when you need to read or modify *every* request or response in some way. /// Use middleware when you need to read or modify *every* request or response in some way.
/// ///
/// ```rust /// ```
/// use actix_service::Service; /// use actix_service::Service;
/// use actix_web::{web, App}; /// use actix_web::{web, App};
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};

View File

@ -37,7 +37,7 @@ pub(crate) type FnDataFactory =
/// If route data is not set for a handler, using `Data<T>` extractor would cause *Internal /// If route data is not set for a handler, using `Data<T>` extractor would cause *Internal
/// Server Error* response. /// Server Error* response.
/// ///
/// ```rust /// ```
/// use std::sync::Mutex; /// use std::sync::Mutex;
/// use actix_web::{web, App, HttpResponse, Responder}; /// use actix_web::{web, App, HttpResponse, Responder};
/// ///

View File

@ -51,7 +51,7 @@ pub trait FromRequest: Sized {
/// ///
/// ## Example /// ## Example
/// ///
/// ```rust /// ```
/// use actix_web::{web, dev, App, Error, HttpRequest, FromRequest}; /// use actix_web::{web, dev, App, Error, HttpRequest, FromRequest};
/// use actix_web::error::ErrorBadRequest; /// use actix_web::error::ErrorBadRequest;
/// use futures_util::future::{ok, err, Ready}; /// use futures_util::future::{ok, err, Ready};
@ -143,7 +143,7 @@ where
/// ///
/// ## Example /// ## Example
/// ///
/// ```rust /// ```
/// use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest}; /// use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest};
/// use actix_web::error::ErrorBadRequest; /// use actix_web::error::ErrorBadRequest;
/// use futures_util::future::{ok, err, Ready}; /// use futures_util::future::{ok, err, Ready};

View File

@ -12,7 +12,7 @@
//! to store extra attributes on a request by using the `Extensions` container. //! to store extra attributes on a request by using the `Extensions` container.
//! Extensions containers are available via the `RequestHead::extensions()` method. //! Extensions containers are available via the `RequestHead::extensions()` method.
//! //!
//! ```rust //! ```
//! use actix_web::{web, http, dev, guard, App, HttpResponse}; //! use actix_web::{web, http, dev, guard, App, HttpResponse};
//! //!
//! fn main() { //! fn main() {
@ -42,7 +42,7 @@ pub trait Guard {
/// Create guard object for supplied function. /// Create guard object for supplied function.
/// ///
/// ```rust /// ```
/// use actix_web::{guard, web, App, HttpResponse}; /// use actix_web::{guard, web, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -85,7 +85,7 @@ where
/// Return guard that matches if any of supplied guards. /// Return guard that matches if any of supplied guards.
/// ///
/// ```rust /// ```
/// use actix_web::{web, guard, App, HttpResponse}; /// use actix_web::{web, guard, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -124,7 +124,7 @@ impl Guard for AnyGuard {
/// Return guard that matches if all of the supplied guards. /// Return guard that matches if all of the supplied guards.
/// ///
/// ```rust /// ```
/// use actix_web::{guard, web, App, HttpResponse}; /// use actix_web::{guard, web, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -259,7 +259,7 @@ 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 /// ```
/// use actix_web::{web, guard::Host, App, HttpResponse}; /// use actix_web::{web, guard::Host, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {

View File

@ -2,7 +2,7 @@
//! //!
//! ## Example //! ## Example
//! //!
//! ```rust,no_run //! ```no_run
//! use actix_web::{get, web, App, HttpServer, Responder}; //! use actix_web::{get, web, App, HttpServer, Responder};
//! //!
//! #[get("/{id}/{name}/index.html")] //! #[get("/{id}/{name}/index.html")]

View File

@ -16,7 +16,7 @@ use crate::{error::Error, service::ServiceResponse};
/// [`Scope::wrap`](crate::Scope::wrap) and [`Condition`](super::Condition). /// [`Scope::wrap`](crate::Scope::wrap) and [`Condition`](super::Condition).
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// use actix_web::middleware::{Logger, Compat}; /// use actix_web::middleware::{Logger, Compat};
/// use actix_web::{App, web}; /// use actix_web::{App, web};
/// ///

View File

@ -31,7 +31,7 @@ use crate::{
/// encoding to `ContentEncoding::Identity`. /// encoding to `ContentEncoding::Identity`.
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// use actix_web::{web, middleware, App, HttpResponse}; /// use actix_web::{web, middleware, App, HttpResponse};
/// ///
/// let app = App::new() /// let app = App::new()

View File

@ -12,7 +12,7 @@ use futures_util::future::{Either, FutureExt, LocalBoxFuture};
/// middleware for a workaround. /// middleware for a workaround.
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// use actix_web::middleware::{Condition, NormalizePath}; /// use actix_web::middleware::{Condition, NormalizePath};
/// use actix_web::App; /// use actix_web::App;
/// ///

View File

@ -29,7 +29,7 @@ use crate::{
/// Headers with the same key that are already set in a response will *not* be overwritten. /// Headers with the same key that are already set in a response will *not* be overwritten.
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// use actix_web::{web, http, middleware, App, HttpResponse}; /// use actix_web::{web, http, middleware, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {

View File

@ -34,7 +34,7 @@ type ErrorHandler<B> = dyn Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse
/// for a given status code. Handlers can modify existing responses or create completely new ones. /// for a given status code. Handlers can modify existing responses or create completely new ones.
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// use actix_web::middleware::{ErrorHandlers, ErrorHandlerResponse}; /// use actix_web::middleware::{ErrorHandlers, ErrorHandlerResponse};
/// use actix_web::{web, http, dev, App, HttpRequest, HttpResponse, Result}; /// use actix_web::{web, http, dev, App, HttpRequest, HttpResponse, Result};
/// ///

View File

@ -43,7 +43,7 @@ use crate::{
/// ``` /// ```
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// use actix_web::{middleware::Logger, App}; /// use actix_web::{middleware::Logger, App};
/// ///
/// // access logs are printed with the INFO level so ensure it is enabled by default /// // access logs are printed with the INFO level so ensure it is enabled by default
@ -124,7 +124,7 @@ impl Logger {
/// It is convention to print "-" to indicate no output instead of an empty string. /// It is convention to print "-" to indicate no output instead of an empty string.
/// ///
/// # Example /// # Example
/// ```rust /// ```
/// # use actix_web::{http::HeaderValue, middleware::Logger}; /// # use actix_web::{http::HeaderValue, middleware::Logger};
/// # fn parse_jwt_id (_req: Option<&HeaderValue>) -> String { "jwt_uid".to_owned() } /// # fn parse_jwt_id (_req: Option<&HeaderValue>) -> String { "jwt_uid".to_owned() }
/// Logger::new("example %{JWT_ID}xi") /// Logger::new("example %{JWT_ID}xi")

View File

@ -54,7 +54,7 @@ impl Default for TrailingSlash {
/// `TrailingSlash::Always` behavior), as shown in the example tests below. /// `TrailingSlash::Always` behavior), as shown in the example tests below.
/// ///
/// # Examples /// # Examples
/// ```rust /// ```
/// use actix_web::{web, middleware, App}; /// use actix_web::{web, middleware, App};
/// ///
/// # actix_web::rt::System::new().block_on(async { /// # actix_web::rt::System::new().block_on(async {

View File

@ -159,7 +159,7 @@ impl HttpRequest {
/// Generate url for named resource /// Generate url for named resource
/// ///
/// ```rust /// ```
/// # use actix_web::{web, App, HttpRequest, HttpResponse}; /// # use actix_web::{web, App, HttpRequest, HttpResponse};
/// # /// #
/// fn index(req: HttpRequest) -> HttpResponse { /// fn index(req: HttpRequest) -> HttpResponse {
@ -231,7 +231,7 @@ impl HttpRequest {
/// ///
/// If `App::data` was used to store object, use `Data<T>`: /// If `App::data` was used to store object, use `Data<T>`:
/// ///
/// ```rust,ignore /// ```ignore
/// let opt_t = req.app_data::<Data<T>>(); /// let opt_t = req.app_data::<Data<T>>();
/// ``` /// ```
pub fn app_data<T: 'static>(&self) -> Option<&T> { pub fn app_data<T: 'static>(&self) -> Option<&T> {
@ -302,7 +302,7 @@ impl Drop for HttpRequest {
/// ///
/// ## Example /// ## Example
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpRequest}; /// use actix_web::{web, App, HttpRequest};
/// use serde_derive::Deserialize; /// use serde_derive::Deserialize;
/// ///

View File

@ -23,7 +23,7 @@ use crate::{dev::Payload, FromRequest, HttpRequest};
/// provided to make this potential foot-gun more obvious. /// provided to make this potential foot-gun more obvious.
/// ///
/// # Example /// # Example
/// ```rust,no_run /// ```no_run
/// # use actix_web::{web, HttpResponse, HttpRequest, Responder}; /// # use actix_web::{web, HttpResponse, HttpRequest, Responder};
/// ///
/// #[derive(Debug, Clone, PartialEq)] /// #[derive(Debug, Clone, PartialEq)]

View File

@ -35,7 +35,7 @@ type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Err
/// and check guards for specific route, if request matches all /// and check guards for specific route, if request matches all
/// guards, route considered matched and route handler get called. /// guards, route considered matched and route handler get called.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -97,7 +97,7 @@ where
/// Add match guard to a resource. /// Add match guard to a resource.
/// ///
/// ```rust /// ```
/// use actix_web::{web, guard, App, HttpResponse}; /// use actix_web::{web, guard, App, HttpResponse};
/// ///
/// async fn index(data: web::Path<(String, String)>) -> &'static str { /// async fn index(data: web::Path<(String, String)>) -> &'static str {
@ -130,7 +130,7 @@ where
/// Register a new route. /// Register a new route.
/// ///
/// ```rust /// ```
/// use actix_web::{web, guard, App, HttpResponse}; /// use actix_web::{web, guard, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -147,7 +147,7 @@ where
/// Multiple routes could be added to a resource. Resource object uses /// Multiple routes could be added to a resource. Resource object uses
/// match guards for route selection. /// match guards for route selection.
/// ///
/// ```rust /// ```
/// use actix_web::{web, guard, App}; /// use actix_web::{web, guard, App};
/// ///
/// fn main() { /// fn main() {
@ -172,7 +172,7 @@ where
/// Provided data is available for all routes registered for the current resource. /// Provided data is available for all routes registered for the current resource.
/// Resource data overrides data registered by `App::data()` method. /// Resource data overrides data registered by `App::data()` method.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, FromRequest}; /// use actix_web::{web, App, FromRequest};
/// ///
/// /// extract text data from request /// /// extract text data from request
@ -211,7 +211,7 @@ where
/// Register a new route and add handler. This route matches all requests. /// Register a new route and add handler. This route matches all requests.
/// ///
/// ```rust /// ```
/// use actix_web::*; /// use actix_web::*;
/// ///
/// fn index(req: HttpRequest) -> HttpResponse { /// fn index(req: HttpRequest) -> HttpResponse {
@ -223,7 +223,7 @@ where
/// ///
/// This is shortcut for: /// This is shortcut for:
/// ///
/// ```rust /// ```
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// # use actix_web::*;
/// # fn index(req: HttpRequest) -> HttpResponse { unimplemented!() } /// # fn index(req: HttpRequest) -> HttpResponse { unimplemented!() }
@ -289,7 +289,7 @@ where
/// Resource level middlewares are not allowed to change response /// Resource level middlewares are not allowed to change response
/// type (i.e modify response's body). /// type (i.e modify response's body).
/// ///
/// ```rust /// ```
/// use actix_service::Service; /// use actix_service::Service;
/// use actix_web::{web, App}; /// use actix_web::{web, App};
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};

View File

@ -18,7 +18,7 @@ pub trait Responder {
/// Override a status code for a Responder. /// Override a status code for a Responder.
/// ///
/// ```rust /// ```
/// use actix_web::{http::StatusCode, HttpRequest, Responder}; /// use actix_web::{http::StatusCode, HttpRequest, Responder};
/// ///
/// fn index(req: HttpRequest) -> impl Responder { /// fn index(req: HttpRequest) -> impl Responder {
@ -36,7 +36,7 @@ pub trait Responder {
/// ///
/// Overrides other headers with the same name. /// Overrides other headers with the same name.
/// ///
/// ```rust /// ```
/// use actix_web::{web, HttpRequest, Responder}; /// use actix_web::{web, HttpRequest, Responder};
/// use serde::Serialize; /// use serde::Serialize;
/// ///
@ -169,7 +169,7 @@ impl<T: Responder> CustomResponder<T> {
/// Override a status code for the Responder's response. /// Override a status code for the Responder's response.
/// ///
/// ```rust /// ```
/// use actix_web::{HttpRequest, Responder, http::StatusCode}; /// use actix_web::{HttpRequest, Responder, http::StatusCode};
/// ///
/// fn index(req: HttpRequest) -> impl Responder { /// fn index(req: HttpRequest) -> impl Responder {
@ -185,7 +185,7 @@ impl<T: Responder> CustomResponder<T> {
/// ///
/// Overrides other headers with the same name. /// Overrides other headers with the same name.
/// ///
/// ```rust /// ```
/// use actix_web::{web, HttpRequest, Responder}; /// use actix_web::{web, HttpRequest, Responder};
/// use serde::Serialize; /// use serde::Serialize;
/// ///

View File

@ -90,7 +90,7 @@ impl Service<ServiceRequest> for RouteService {
impl Route { impl Route {
/// Add method guard to the route. /// Add method guard to the route.
/// ///
/// ```rust /// ```
/// # use actix_web::*; /// # use actix_web::*;
/// # fn main() { /// # fn main() {
/// App::new().service(web::resource("/path").route( /// App::new().service(web::resource("/path").route(
@ -110,7 +110,7 @@ impl Route {
/// Add guard to the route. /// Add guard to the route.
/// ///
/// ```rust /// ```
/// # use actix_web::*; /// # use actix_web::*;
/// # fn main() { /// # fn main() {
/// App::new().service(web::resource("/path").route( /// App::new().service(web::resource("/path").route(
@ -128,7 +128,7 @@ impl Route {
/// Set handler function, use request extractors for parameters. /// Set handler function, use request extractors for parameters.
/// ///
/// ```rust /// ```
/// use actix_web::{web, http, App}; /// use actix_web::{web, http, App};
/// use serde_derive::Deserialize; /// use serde_derive::Deserialize;
/// ///
@ -152,7 +152,7 @@ impl Route {
/// ///
/// It is possible to use multiple extractors for one handler function. /// It is possible to use multiple extractors for one handler function.
/// ///
/// ```rust /// ```
/// # use std::collections::HashMap; /// # use std::collections::HashMap;
/// # use serde_derive::Deserialize; /// # use serde_derive::Deserialize;
/// use actix_web::{web, App}; /// use actix_web::{web, App};

View File

@ -40,7 +40,7 @@ type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Err
/// You can get variable path segments from `HttpRequest::match_info()`. /// You can get variable path segments from `HttpRequest::match_info()`.
/// `Path` extractor also is able to extract scope level variable segments. /// `Path` extractor also is able to extract scope level variable segments.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -97,7 +97,7 @@ where
{ {
/// Add match guard to a scope. /// Add match guard to a scope.
/// ///
/// ```rust /// ```
/// use actix_web::{web, guard, App, HttpRequest, HttpResponse}; /// use actix_web::{web, guard, App, HttpRequest, HttpResponse};
/// ///
/// async fn index(data: web::Path<(String, String)>) -> &'static str { /// async fn index(data: web::Path<(String, String)>) -> &'static str {
@ -123,7 +123,7 @@ where
/// Set or override application data. Application data could be accessed /// Set or override application data. Application data could be accessed
/// by using `Data<T>` extractor where `T` is data type. /// by using `Data<T>` extractor where `T` is data type.
/// ///
/// ```rust /// ```
/// use std::cell::Cell; /// use std::cell::Cell;
/// use actix_web::{web, App, HttpResponse, Responder}; /// use actix_web::{web, App, HttpResponse, Responder};
/// ///
@ -168,7 +168,7 @@ where
/// different module or even library. For example, /// different module or even library. For example,
/// some of the resource's configuration could be moved to different module. /// some of the resource's configuration could be moved to different module.
/// ///
/// ```rust /// ```
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{web, middleware, App, HttpResponse}; /// use actix_web::{web, middleware, App, HttpResponse};
/// ///
@ -215,7 +215,7 @@ where
/// * *Scope* is a set of resources with common root path. /// * *Scope* is a set of resources with common root path.
/// * "StaticFiles" is a service for static files support /// * "StaticFiles" is a service for static files support
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpRequest}; /// use actix_web::{web, App, HttpRequest};
/// ///
/// struct AppState; /// struct AppState;
@ -247,7 +247,7 @@ where
/// This method can be called multiple times, in that case /// This method can be called multiple times, in that case
/// multiple resources with one route would be registered for same resource path. /// multiple resources with one route would be registered for same resource path.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// async fn index(data: web::Path<(String, String)>) -> &'static str { /// async fn index(data: web::Path<(String, String)>) -> &'static str {
@ -341,7 +341,7 @@ where
/// to Route or Application level middleware, in that Scope-level middleware /// to Route or Application level middleware, in that Scope-level middleware
/// can not modify ServiceResponse. /// can not modify ServiceResponse.
/// ///
/// ```rust /// ```
/// use actix_service::Service; /// use actix_service::Service;
/// use actix_web::{web, App}; /// use actix_web::{web, App};
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};

View File

@ -35,7 +35,7 @@ struct Config {
/// ///
/// Create new HTTP server with application factory. /// Create new HTTP server with application factory.
/// ///
/// ```rust,no_run /// ```no_run
/// use actix_web::{web, App, HttpResponse, HttpServer}; /// use actix_web::{web, App, HttpResponse, HttpServer};
/// ///
/// #[actix_rt::main] /// #[actix_rt::main]
@ -588,7 +588,7 @@ where
/// This methods panics if no socket address can be bound or an `Actix` system is not yet /// This methods panics if no socket address can be bound or an `Actix` system is not yet
/// configured. /// configured.
/// ///
/// ```rust,no_run /// ```no_run
/// use std::io; /// use std::io;
/// use actix_web::{web, App, HttpResponse, HttpServer}; /// use actix_web::{web, App, HttpResponse, HttpServer};
/// ///

View File

@ -462,7 +462,7 @@ impl WebService {
/// Add match guard to a web service. /// Add match guard to a web service.
/// ///
/// ```rust /// ```
/// use actix_web::{web, guard, dev, App, Error, HttpResponse}; /// use actix_web::{web, guard, dev, App, Error, HttpResponse};
/// ///
/// async fn index(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> { /// async fn index(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> {

View File

@ -54,7 +54,7 @@ pub fn default_service(
/// This method accepts application builder instance, and constructs /// This method accepts application builder instance, and constructs
/// service. /// service.
/// ///
/// ```rust /// ```
/// use actix_service::Service; /// use actix_service::Service;
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode}; /// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
/// ///
@ -101,7 +101,7 @@ where
/// Calls service and waits for response future completion. /// Calls service and waits for response future completion.
/// ///
/// ```rust /// ```
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode}; /// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
/// ///
/// #[actix_rt::test] /// #[actix_rt::test]
@ -131,7 +131,7 @@ where
/// Helper function that returns a response body of a TestRequest /// Helper function that returns a response body of a TestRequest
/// ///
/// ```rust /// ```
/// use actix_web::{test, web, App, HttpResponse, http::header}; /// use actix_web::{test, web, App, HttpResponse, http::header};
/// use bytes::Bytes; /// use bytes::Bytes;
/// ///
@ -174,7 +174,7 @@ where
/// Helper function that returns a response body of a ServiceResponse. /// Helper function that returns a response body of a ServiceResponse.
/// ///
/// ```rust /// ```
/// use actix_web::{test, web, App, HttpResponse, http::header}; /// use actix_web::{test, web, App, HttpResponse, http::header};
/// use bytes::Bytes; /// use bytes::Bytes;
/// ///
@ -212,7 +212,7 @@ where
/// Helper function that returns a deserialized response body of a ServiceResponse. /// Helper function that returns a deserialized response body of a ServiceResponse.
/// ///
/// ```rust /// ```
/// use actix_web::{App, test, web, HttpResponse, http::header}; /// use actix_web::{App, test, web, HttpResponse, http::header};
/// use serde::{Serialize, Deserialize}; /// use serde::{Serialize, Deserialize};
/// ///
@ -271,7 +271,7 @@ where
/// Helper function that returns a deserialized response body of a TestRequest /// Helper function that returns a deserialized response body of a TestRequest
/// ///
/// ```rust /// ```
/// use actix_web::{App, test, web, HttpResponse, http::header}; /// use actix_web::{App, test, web, HttpResponse, http::header};
/// use serde::{Serialize, Deserialize}; /// use serde::{Serialize, Deserialize};
/// ///
@ -324,7 +324,7 @@ where
/// * `TestRequest::to_srv_response` creates `ServiceResponse` instance. /// * `TestRequest::to_srv_response` creates `ServiceResponse` instance.
/// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers. /// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
/// ///
/// ```rust /// ```
/// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage}; /// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage};
/// use actix_web::http::{header, StatusCode}; /// use actix_web::http::{header, StatusCode};
/// ///
@ -572,7 +572,7 @@ impl TestRequest {
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```
/// use actix_web::{web, test, App, HttpResponse, Error}; /// use actix_web::{web, test, App, HttpResponse, Error};
/// ///
/// async fn my_handler() -> Result<HttpResponse, Error> { /// async fn my_handler() -> Result<HttpResponse, Error> {
@ -612,7 +612,7 @@ where
/// ///
/// # Examples /// # Examples
/// ///
/// ```rust /// ```
/// use actix_web::{web, test, App, HttpResponse, Error}; /// use actix_web::{web, test, App, HttpResponse, Error};
/// ///
/// async fn my_handler() -> Result<HttpResponse, Error> { /// async fn my_handler() -> Result<HttpResponse, Error> {

View File

@ -42,7 +42,7 @@ pub use crate::types::*;
/// `/users/{userid}/{friend}` and store `userid` and `friend` in /// `/users/{userid}/{friend}` and store `userid` and `friend` in
/// the exposed `Params` object: /// the exposed `Params` object:
/// ///
/// ```rust /// ```
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
@ -61,7 +61,7 @@ pub fn resource<T: IntoPattern>(path: T) -> Resource {
/// Scopes collect multiple paths under a common path prefix. /// Scopes collect multiple paths under a common path prefix.
/// Scope path can contain variable path segments as resources. /// Scope path can contain variable path segments as resources.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -88,7 +88,7 @@ pub fn route() -> Route {
/// Create *route* with `GET` method guard. /// Create *route* with `GET` method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -106,7 +106,7 @@ pub fn get() -> Route {
/// Create *route* with `POST` method guard. /// Create *route* with `POST` method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -124,7 +124,7 @@ pub fn post() -> Route {
/// Create *route* with `PUT` method guard. /// Create *route* with `PUT` method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -142,7 +142,7 @@ pub fn put() -> Route {
/// Create *route* with `PATCH` method guard. /// Create *route* with `PATCH` method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -160,7 +160,7 @@ pub fn patch() -> Route {
/// Create *route* with `DELETE` method guard. /// Create *route* with `DELETE` method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -178,7 +178,7 @@ pub fn delete() -> Route {
/// Create *route* with `HEAD` method guard. /// Create *route* with `HEAD` method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -196,7 +196,7 @@ pub fn head() -> Route {
/// Create *route* with `TRACE` method guard. /// Create *route* with `TRACE` method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -214,7 +214,7 @@ pub fn trace() -> Route {
/// Create *route* and add method guard. /// Create *route* and add method guard.
/// ///
/// ```rust /// ```
/// use actix_web::{web, http, App, HttpResponse}; /// use actix_web::{web, http, App, HttpResponse};
/// ///
/// let app = App::new().service( /// let app = App::new().service(
@ -232,7 +232,7 @@ pub fn method(method: Method) -> Route {
/// Create a new route and add handler. /// Create a new route and add handler.
/// ///
/// ```rust /// ```
/// use actix_web::{web, App, HttpResponse, Responder}; /// use actix_web::{web, App, HttpResponse, Responder};
/// ///
/// async fn index() -> impl Responder { /// async fn index() -> impl Responder {
@ -256,7 +256,7 @@ where
/// Create raw service for a specific path. /// Create raw service for a specific path.
/// ///
/// ```rust /// ```
/// use actix_web::{dev, web, guard, App, Error, HttpResponse}; /// use actix_web::{dev, web, guard, App, Error, HttpResponse};
/// ///
/// async fn my_service(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> { /// async fn my_service(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> {