1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 07:53:00 +01:00

cargo fmt

This commit is contained in:
Nikolay Kim 2018-06-01 09:37:14 -07:00
parent 154cd3c5de
commit 3f5a39a5b7
21 changed files with 279 additions and 251 deletions

View File

@ -300,10 +300,12 @@ where
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new()
/// .route("/test", http::Method::GET, /// .route("/test", http::Method::GET, |_: HttpRequest| {
/// |_: HttpRequest| HttpResponse::Ok()) /// HttpResponse::Ok()
/// .route("/test", http::Method::POST, /// })
/// |_: HttpRequest| HttpResponse::MethodNotAllowed()); /// .route("/test", http::Method::POST, |_: HttpRequest| {
/// HttpResponse::MethodNotAllowed()
/// });
/// } /// }
/// ``` /// ```
pub fn route<T, F, R>(mut self, path: &str, method: Method, f: F) -> App<S> pub fn route<T, F, R>(mut self, path: &str, method: Method, f: F) -> App<S>
@ -345,9 +347,9 @@ where
/// use actix_web::{http, App, HttpRequest, HttpResponse}; /// use actix_web::{http, App, HttpRequest, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().scope("/{project_id}", |scope| {
/// .scope("/{project_id}", |scope| { /// scope
/// scope.resource("/path1", |r| r.f(|_| HttpResponse::Ok())) /// .resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
/// .resource("/path2", |r| r.f(|_| HttpResponse::Ok())) /// .resource("/path2", |r| r.f(|_| HttpResponse::Ok()))
/// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed())) /// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed()))
/// }); /// });
@ -402,8 +404,7 @@ where
/// use actix_web::{http, App, HttpResponse}; /// use actix_web::{http, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().resource("/users/{userid}/{friend}", |r| {
/// .resource("/users/{userid}/{friend}", |r| {
/// r.get().f(|_| HttpResponse::Ok()); /// r.get().f(|_| HttpResponse::Ok());
/// r.head().f(|_| HttpResponse::MethodNotAllowed()); /// r.head().f(|_| HttpResponse::MethodNotAllowed());
/// }); /// });
@ -514,13 +515,11 @@ where
/// use actix_web::{http, App, HttpRequest, HttpResponse}; /// use actix_web::{http, App, HttpRequest, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().handler("/app", |req: HttpRequest| match *req.method() {
/// .handler("/app", |req: HttpRequest| {
/// match *req.method() {
/// http::Method::GET => HttpResponse::Ok(), /// http::Method::GET => HttpResponse::Ok(),
/// http::Method::POST => HttpResponse::MethodNotAllowed(), /// http::Method::POST => HttpResponse::MethodNotAllowed(),
/// _ => HttpResponse::NotFound(), /// _ => HttpResponse::NotFound(),
/// }}); /// });
/// } /// }
/// ``` /// ```
pub fn handler<H: Handler<S>>(mut self, path: &str, handler: H) -> App<S> { pub fn handler<H: Handler<S>>(mut self, path: &str, handler: H) -> App<S> {
@ -561,12 +560,11 @@ where
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{App, HttpResponse, fs, middleware}; /// use actix_web::{fs, middleware, App, HttpResponse};
/// ///
/// // this function could be located in different module /// // this function could be located in different module
/// fn config(app: App) -> App { /// fn config(app: App) -> App {
/// app /// app.resource("/test", |r| {
/// .resource("/test", |r| {
/// r.get().f(|_| HttpResponse::Ok()); /// r.get().f(|_| HttpResponse::Ok());
/// r.head().f(|_| HttpResponse::MethodNotAllowed()); /// r.head().f(|_| HttpResponse::MethodNotAllowed());
/// }) /// })
@ -636,8 +634,9 @@ where
/// struct State2; /// struct State2;
/// ///
/// fn main() { /// fn main() {
/// # thread::spawn(|| { /// //#### # thread::spawn(|| {
/// server::new(|| { vec![ /// server::new(|| {
/// vec![
/// App::with_state(State1) /// App::with_state(State1)
/// .prefix("/app1") /// .prefix("/app1")
/// .resource("/", |r| r.f(|r| HttpResponse::Ok())) /// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
@ -645,10 +644,12 @@ where
/// App::with_state(State2) /// App::with_state(State2)
/// .prefix("/app2") /// .prefix("/app2")
/// .resource("/", |r| r.f(|r| HttpResponse::Ok())) /// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
/// .boxed() ]}) /// .boxed(),
/// .bind("127.0.0.1:8080").unwrap() /// ]
/// }).bind("127.0.0.1:8080")
/// .unwrap()
/// .run() /// .run()
/// # }); /// //#### # });
/// } /// }
/// ``` /// ```
pub fn boxed(mut self) -> Box<HttpHandler> { pub fn boxed(mut self) -> Box<HttpHandler> {

View File

@ -81,7 +81,8 @@ impl ResponseError for SendRequestError {
/// println!("Response: {:?}", response); /// println!("Response: {:?}", response);
/// # process::exit(0); /// # process::exit(0);
/// Ok(()) /// Ok(())
/// })); /// }),
/// );
/// } /// }
/// ``` /// ```
pub fn get<U: AsRef<str>>(uri: U) -> ClientRequestBuilder { pub fn get<U: AsRef<str>>(uri: U) -> ClientRequestBuilder {

View File

@ -43,7 +43,7 @@ use httprequest::HttpRequest;
/// println!("Response: {:?}", response); /// println!("Response: {:?}", response);
/// # process::exit(0); /// # process::exit(0);
/// Ok(()) /// Ok(())
/// }) /// }),
/// ); /// );
/// } /// }
/// ``` /// ```
@ -344,7 +344,8 @@ impl ClientRequestBuilder {
/// let req = client::ClientRequest::build() /// let req = client::ClientRequest::build()
/// .set(http::header::Date::now()) /// .set(http::header::Date::now())
/// .set(http::header::ContentType(mime::TEXT_HTML)) /// .set(http::header::ContentType(mime::TEXT_HTML))
/// .finish().unwrap(); /// .finish()
/// .unwrap();
/// } /// }
/// ``` /// ```
#[doc(hidden)] #[doc(hidden)]
@ -376,7 +377,8 @@ impl ClientRequestBuilder {
/// let req = ClientRequest::build() /// let req = ClientRequest::build()
/// .header("X-TEST", "value") /// .header("X-TEST", "value")
/// .header(header::CONTENT_TYPE, "application/json") /// .header(header::CONTENT_TYPE, "application/json")
/// .finish().unwrap(); /// .finish()
/// .unwrap();
/// } /// }
/// ``` /// ```
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
@ -486,8 +488,10 @@ impl ClientRequestBuilder {
/// .path("/") /// .path("/")
/// .secure(true) /// .secure(true)
/// .http_only(true) /// .http_only(true)
/// .finish()) /// .finish(),
/// .finish().unwrap(); /// )
/// .finish()
/// .unwrap();
/// } /// }
/// ``` /// ```
pub fn cookie<'c>(&mut self, cookie: Cookie<'c>) -> &mut Self { pub fn cookie<'c>(&mut self, cookie: Cookie<'c>) -> &mut Self {

View File

@ -24,7 +24,7 @@ use httprequest::HttpRequest;
/// # extern crate bytes; /// # extern crate bytes;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// use actix_web::{App, Path, Result, http}; /// use actix_web::{http, App, Path, Result};
/// ///
/// /// extract path info from "/{username}/{count}/index.html" url /// /// extract path info from "/{username}/{count}/index.html" url
/// /// {username} - deserializes to a String /// /// {username} - deserializes to a String
@ -36,7 +36,8 @@ use httprequest::HttpRequest;
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/{username}/{count}/index.html", // <- define path parameters /// "/{username}/{count}/index.html", // <- define path parameters
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index),
/// ); // <- use `with` extractor
/// } /// }
/// ``` /// ```
/// ///
@ -48,7 +49,7 @@ use httprequest::HttpRequest;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Path, Result, http}; /// use actix_web::{http, App, Path, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -63,7 +64,8 @@ use httprequest::HttpRequest;
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index),
/// ); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub struct Path<T> { pub struct Path<T> {
@ -118,13 +120,13 @@ where
/// ## Example /// ## Example
/// ///
/// ```rust /// ```rust
/// # extern crate bytes; /// //#### # extern crate bytes;
/// # extern crate actix_web; /// //#### # extern crate actix_web;
/// # extern crate futures; /// //#### # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// //#### #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Query, http}; /// use actix_web::{App, Query, http};
/// ///
/// #[derive(Deserialize)] /// //#### #[derive(Deserialize)]
/// struct Info { /// struct Info {
/// username: String, /// username: String,
/// } /// }
@ -255,7 +257,7 @@ where
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Form, Result, http}; /// use actix_web::{http, App, Form, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct FormData { /// struct FormData {
@ -270,10 +272,10 @@ where
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/index.html", |r| { /// "/index.html",
/// r.method(http::Method::GET) /// |r| {
/// .with(index) /// r.method(http::Method::GET).with(index).limit(4096);
/// .limit(4096);} // <- change form extractor configuration /// }, // <- change form extractor configuration
/// ); /// );
/// } /// }
/// ``` /// ```
@ -315,9 +317,8 @@ impl Default for FormConfig {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new()
/// "/index.html", |r| /// .resource("/index.html", |r| r.method(http::Method::GET).with(index));
/// r.method(http::Method::GET).with(index));
/// } /// }
/// ``` /// ```
impl<S: 'static> FromRequest<S> for Bytes { impl<S: 'static> FromRequest<S> for Bytes {
@ -354,8 +355,7 @@ impl<S: 'static> FromRequest<S> for Bytes {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource("/index.html", |r| {
/// "/index.html", |r| {
/// r.method(http::Method::GET) /// r.method(http::Method::GET)
/// .with(index) // <- register handler with extractor params /// .with(index) // <- register handler with extractor params
/// .limit(4096); // <- limit size of the payload /// .limit(4096); // <- limit size of the payload

View File

@ -61,22 +61,24 @@ pub trait FromRequest<S>: Sized {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # use futures::future::Future; /// # use futures::future::Future;
/// use actix_web::{AsyncResponder, Either, Error, HttpRequest, HttpResponse};
/// use futures::future::result; /// use futures::future::result;
/// use actix_web::{Either, Error, HttpRequest, HttpResponse, AsyncResponder};
///
/// type RegisterResult = Either<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
/// ///
/// type RegisterResult =
/// Either<HttpResponse, Box<Future<Item = HttpResponse, Error = Error>>>;
/// ///
/// fn index(req: HttpRequest) -> RegisterResult { /// fn index(req: HttpRequest) -> RegisterResult {
/// if is_a_variant() { // <- choose variant A /// if is_a_variant() {
/// Either::A( /// // <- choose variant A
/// HttpResponse::BadRequest().body("Bad data")) /// Either::A(HttpResponse::BadRequest().body("Bad data"))
/// } else { /// } else {
/// Either::B( // <- variant B /// Either::B(
/// // <- variant B
/// result(Ok(HttpResponse::Ok() /// result(Ok(HttpResponse::Ok()
/// .content_type("text/html") /// .content_type("text/html")
/// .body("Hello!"))) /// .body("Hello!")))
/// .responder()) /// .responder(),
/// )
/// } /// }
/// } /// }
/// # fn is_a_variant() -> bool { true } /// # fn is_a_variant() -> bool { true }
@ -138,9 +140,10 @@ where
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// use futures::future::Future;
/// use actix_web::{ /// use actix_web::{
/// App, HttpRequest, HttpResponse, HttpMessage, Error, AsyncResponder}; /// App, AsyncResponder, Error, HttpMessage, HttpRequest, HttpResponse,
/// };
/// use futures::future::Future;
/// ///
/// #[derive(Deserialize, Debug)] /// #[derive(Deserialize, Debug)]
/// struct MyObj { /// struct MyObj {
@ -479,10 +482,12 @@ where
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Path, State, http}; /// use actix_web::{http, App, Path, State};
/// ///
/// /// Application state /// /// Application state
/// struct MyApp {msg: &'static str} /// struct MyApp {
/// msg: &'static str,
/// }
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -498,7 +503,8 @@ where
/// fn main() { /// fn main() {
/// let app = App::with_state(MyApp { msg: "Welcome" }).resource( /// let app = App::with_state(MyApp { msg: "Welcome" }).resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index),
/// ); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub struct State<S>(HttpRequest<S>); pub struct State<S>(HttpRequest<S>);

View File

@ -283,9 +283,9 @@ impl<S> HttpRequest<S> {
/// Generate url for named resource /// Generate url for named resource
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// //#### # extern crate actix_web;
/// # use actix_web::{App, HttpRequest, HttpResponse, http}; /// //#### # use actix_web::{App, HttpRequest, HttpResponse, http};
/// # /// //#### #
/// fn index(req: HttpRequest) -> HttpResponse { /// fn index(req: HttpRequest) -> HttpResponse {
/// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource /// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
/// HttpResponse::Ok().into() /// HttpResponse::Ok().into()

View File

@ -297,11 +297,13 @@ impl HttpResponseBuilder {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{HttpRequest, HttpResponse, Result, http}; /// use actix_web::{http, HttpRequest, HttpResponse, Result};
/// ///
/// fn index(req: HttpRequest) -> Result<HttpResponse> { /// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HttpResponse::Ok() /// Ok(HttpResponse::Ok()
/// .set(http::header::IfModifiedSince("Sun, 07 Nov 1994 08:48:37 GMT".parse()?)) /// .set(http::header::IfModifiedSince(
/// "Sun, 07 Nov 1994 08:48:37 GMT".parse()?,
/// ))
/// .finish()) /// .finish())
/// } /// }
/// fn main() {} /// fn main() {}
@ -455,7 +457,8 @@ impl HttpResponseBuilder {
/// .path("/") /// .path("/")
/// .secure(true) /// .secure(true)
/// .http_only(true) /// .http_only(true)
/// .finish()) /// .finish(),
/// )
/// .finish() /// .finish()
/// } /// }
/// ``` /// ```

View File

@ -32,11 +32,11 @@ use httpresponse::HttpResponse;
/// ## Example /// ## Example
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// //#### # extern crate actix_web;
/// #[macro_use] extern crate serde_derive; /// //#### #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Json, Result, http}; /// use actix_web::{App, Json, Result, http};
/// ///
/// #[derive(Deserialize)] /// //#### #[derive(Deserialize)]
/// struct Info { /// struct Info {
/// username: String, /// username: String,
/// } /// }
@ -69,7 +69,9 @@ use httpresponse::HttpResponse;
/// } /// }
/// ///
/// fn index(req: HttpRequest) -> Result<Json<MyObj>> { /// fn index(req: HttpRequest) -> Result<Json<MyObj>> {
/// Ok(Json(MyObj{name: req.match_info().query("name")?})) /// Ok(Json(MyObj {
/// name: req.match_info().query("name")?,
/// }))
/// } /// }
/// # fn main() {} /// # fn main() {}
/// ``` /// ```
@ -154,7 +156,7 @@ where
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Json, HttpResponse, Result, http, error}; /// use actix_web::{error, http, App, HttpResponse, Json, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -167,8 +169,7 @@ where
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource("/index.html", |r| {
/// "/index.html", |r| {
/// r.method(http::Method::POST) /// r.method(http::Method::POST)
/// .with(index) /// .with(index)
/// .limit(4096) // <- change json extractor configuration /// .limit(4096) // <- change json extractor configuration
@ -223,8 +224,8 @@ impl<S> Default for JsonConfig<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// use actix_web::{AsyncResponder, Error, HttpMessage, HttpRequest, HttpResponse};
/// use futures::future::Future; /// use futures::future::Future;
/// use actix_web::{AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error};
/// ///
/// #[derive(Deserialize, Debug)] /// #[derive(Deserialize, Debug)]
/// struct MyObj { /// struct MyObj {

View File

@ -19,16 +19,16 @@
//! //!
//! ```rust //! ```rust
//! # extern crate actix_web; //! # extern crate actix_web;
//! use actix_web::{http, App, HttpRequest, HttpResponse};
//! use actix_web::middleware::cors::Cors; //! use actix_web::middleware::cors::Cors;
//! use actix_web::{http, App, HttpRequest, HttpResponse};
//! //!
//! fn index(mut req: HttpRequest) -> &'static str { //! fn index(mut req: HttpRequest) -> &'static str {
//! "Hello world" //! "Hello world"
//! } //! }
//! //!
//! fn main() { //! fn main() {
//! let app = App::new() //! let app = App::new().configure(|app| {
//! .configure(|app| Cors::for_app(app) // <- Construct CORS middleware builder //! Cors::for_app(app) // <- Construct CORS middleware builder
//! .allowed_origin("https://www.rust-lang.org/") //! .allowed_origin("https://www.rust-lang.org/")
//! .allowed_methods(vec!["GET", "POST"]) //! .allowed_methods(vec!["GET", "POST"])
//! .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT]) //! .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
@ -38,7 +38,8 @@
//! r.method(http::Method::GET).f(|_| HttpResponse::Ok()); //! r.method(http::Method::GET).f(|_| HttpResponse::Ok());
//! r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed()); //! r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
//! }) //! })
//! .register()); //! .register()
//! });
//! } //! }
//! ``` //! ```
//! In this example custom *CORS* middleware get registered for "/index.html" //! In this example custom *CORS* middleware get registered for "/index.html"
@ -232,17 +233,19 @@ impl Cors {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, App, HttpResponse};
/// use actix_web::middleware::cors::Cors; /// use actix_web::middleware::cors::Cors;
/// use actix_web::{http, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().configure(
/// .configure(|app| Cors::for_app(app) // <- Construct CORS builder /// |app| {
/// Cors::for_app(app) // <- Construct CORS builder
/// .allowed_origin("https://www.rust-lang.org/") /// .allowed_origin("https://www.rust-lang.org/")
/// .resource("/resource", |r| { // register resource /// .resource("/resource", |r| { // register resource
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok()); /// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// }) /// })
/// .register() // construct CORS and return application instance /// .register()
/// }, // construct CORS and return application instance
/// ); /// );
/// } /// }
/// ``` /// ```
@ -491,8 +494,8 @@ impl<S> Middleware<S> for Cors {
/// ```rust /// ```rust
/// # extern crate http; /// # extern crate http;
/// # extern crate actix_web; /// # extern crate actix_web;
/// use http::header;
/// use actix_web::middleware::cors; /// use actix_web::middleware::cors;
/// use http::header;
/// ///
/// # fn main() { /// # fn main() {
/// let cors = cors::Cors::build() /// let cors = cors::Cors::build()
@ -764,12 +767,13 @@ impl<S: 'static> CorsBuilder<S> {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, App, HttpResponse};
/// use actix_web::middleware::cors::Cors; /// use actix_web::middleware::cors::Cors;
/// use actix_web::{http, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().configure(
/// .configure(|app| Cors::for_app(app) // <- Construct CORS builder /// |app| {
/// Cors::for_app(app) // <- Construct CORS builder
/// .allowed_origin("https://www.rust-lang.org/") /// .allowed_origin("https://www.rust-lang.org/")
/// .allowed_methods(vec!["GET", "POST"]) /// .allowed_methods(vec!["GET", "POST"])
/// .allowed_header(http::header::CONTENT_TYPE) /// .allowed_header(http::header::CONTENT_TYPE)
@ -781,7 +785,8 @@ impl<S: 'static> CorsBuilder<S> {
/// r.method(http::Method::HEAD) /// r.method(http::Method::HEAD)
/// .f(|_| HttpResponse::MethodNotAllowed()); /// .f(|_| HttpResponse::MethodNotAllowed());
/// }) /// })
/// .register() // construct CORS and return application instance /// .register()
/// }, // construct CORS and return application instance
/// ); /// );
/// } /// }
/// ``` /// ```

View File

@ -22,8 +22,8 @@
//! //!
//! ``` //! ```
//! # extern crate actix_web; //! # extern crate actix_web;
//! use actix_web::{http, App, HttpRequest, HttpResponse};
//! use actix_web::middleware::csrf; //! use actix_web::middleware::csrf;
//! use actix_web::{http, App, HttpRequest, HttpResponse};
//! //!
//! fn handle_post(_: HttpRequest) -> &'static str { //! fn handle_post(_: HttpRequest) -> &'static str {
//! "This action should only be triggered with requests from the same site" //! "This action should only be triggered with requests from the same site"
@ -32,8 +32,8 @@
//! fn main() { //! fn main() {
//! let app = App::new() //! let app = App::new()
//! .middleware( //! .middleware(
//! csrf::CsrfFilter::new() //! csrf::CsrfFilter::new().allowed_origin("https://www.example.com"),
//! .allowed_origin("https://www.example.com")) //! )
//! .resource("/", |r| { //! .resource("/", |r| {
//! r.method(http::Method::GET).f(|_| HttpResponse::Ok()); //! r.method(http::Method::GET).f(|_| HttpResponse::Ok());
//! r.method(http::Method::POST).f(handle_post); //! r.method(http::Method::POST).f(handle_post);
@ -120,13 +120,12 @@ fn origin(headers: &HeaderMap) -> Option<Result<Cow<str>, CsrfError>> {
/// # Example /// # Example
/// ///
/// ``` /// ```
/// use actix_web::App;
/// use actix_web::middleware::csrf; /// use actix_web::middleware::csrf;
/// use actix_web::App;
/// ///
/// # fn main() { /// # fn main() {
/// let app = App::new().middleware( /// let app = App::new()
/// csrf::CsrfFilter::new() /// .middleware(csrf::CsrfFilter::new().allowed_origin("https://www.example.com"));
/// .allowed_origin("https://www.example.com"));
/// # } /// # }
/// ``` /// ```
#[derive(Default)] #[derive(Default)]

View File

@ -17,12 +17,11 @@ use middleware::{Middleware, Response};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new()
/// .middleware( /// .middleware(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
/// middleware::DefaultHeaders::new()
/// .header("X-Version", "0.2"))
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok()); /// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed()); /// r.method(http::Method::HEAD)
/// .f(|_| HttpResponse::MethodNotAllowed());
/// }) /// })
/// .finish(); /// .finish();
/// } /// }

View File

@ -18,8 +18,8 @@ type ErrorHandler<S> = Fn(&mut HttpRequest<S>, HttpResponse) -> Result<Response>
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::middleware::{ErrorHandlers, Response};
/// use actix_web::{http, App, HttpRequest, HttpResponse, Result}; /// use actix_web::{http, App, HttpRequest, HttpResponse, Result};
/// use actix_web::middleware::{Response, ErrorHandlers};
/// ///
/// fn render_500<S>(_: &mut HttpRequest<S>, resp: HttpResponse) -> Result<Response> { /// fn render_500<S>(_: &mut HttpRequest<S>, resp: HttpResponse) -> Result<Response> {
/// let mut builder = resp.into_builder(); /// let mut builder = resp.into_builder();
@ -31,10 +31,12 @@ type ErrorHandler<S> = Fn(&mut HttpRequest<S>, HttpResponse) -> Result<Response>
/// let app = App::new() /// let app = App::new()
/// .middleware( /// .middleware(
/// ErrorHandlers::new() /// ErrorHandlers::new()
/// .handler(http::StatusCode::INTERNAL_SERVER_ERROR, render_500)) /// .handler(http::StatusCode::INTERNAL_SERVER_ERROR, render_500),
/// )
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok()); /// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed()); /// r.method(http::Method::HEAD)
/// .f(|_| HttpResponse::MethodNotAllowed());
/// }) /// })
/// .finish(); /// .finish();
/// } /// }

View File

@ -62,8 +62,8 @@ use middleware::{Middleware, Response, Started};
/// The helper trait to obtain your identity from a request. /// The helper trait to obtain your identity from a request.
/// ///
/// ```rust /// ```rust
/// use actix_web::*;
/// use actix_web::middleware::identity::RequestIdentity; /// use actix_web::middleware::identity::RequestIdentity;
/// use actix_web::*;
/// ///
/// fn index(req: HttpRequest) -> Result<String> { /// fn index(req: HttpRequest) -> Result<String> {
/// // access request identity /// // access request identity
@ -144,16 +144,16 @@ pub trait IdentityPolicy<S>: Sized + 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
/// use actix_web::App; /// use actix_web::App;
/// use actix_web::middleware::identity::{IdentityService, CookieIdentityPolicy};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().middleware( /// let app = App::new().middleware(IdentityService::new(
/// IdentityService::new( // <- create identity middleware /// // <- create identity middleware
/// CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend /// CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend
/// .name("auth-cookie") /// .name("auth-cookie")
/// .secure(false)) /// .secure(false),
/// ); /// ));
/// } /// }
/// ``` /// ```
pub struct IdentityService<T> { pub struct IdentityService<T> {
@ -317,17 +317,18 @@ impl CookieIdentityInner {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
/// use actix_web::App; /// use actix_web::App;
/// use actix_web::middleware::identity::{IdentityService, CookieIdentityPolicy};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().middleware( /// let app = App::new().middleware(IdentityService::new(
/// IdentityService::new( // <- create identity middleware /// // <- create identity middleware
/// CookieIdentityPolicy::new(&[0; 32]) // <- construct cookie policy /// CookieIdentityPolicy::new(&[0; 32]) // <- construct cookie policy
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
/// .name("actix_auth") /// .name("actix_auth")
/// .path("/") /// .path("/")
/// .secure(true))); /// .secure(true),
/// ));
/// } /// }
/// ``` /// ```
pub struct CookieIdentityPolicy(Rc<CookieIdentityInner>); pub struct CookieIdentityPolicy(Rc<CookieIdentityInner>);

View File

@ -31,8 +31,8 @@ use middleware::{Finished, Middleware, Started};
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// extern crate env_logger; /// extern crate env_logger;
/// use actix_web::App;
/// use actix_web::middleware::Logger; /// use actix_web::middleware::Logger;
/// use actix_web::App;
/// ///
/// fn main() { /// fn main() {
/// std::env::set_var("RUST_LOG", "actix_web=info"); /// std::env::set_var("RUST_LOG", "actix_web=info");

View File

@ -22,10 +22,11 @@ pub trait Predicate<S> {
/// use actix_web::{pred, App, HttpResponse}; /// use actix_web::{pred, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// App::new() /// App::new().resource("/index.html", |r| {
/// .resource("/index.html", |r| r.route() /// r.route()
/// .filter(pred::Any(pred::Get()).or(pred::Post())) /// .filter(pred::Any(pred::Get()).or(pred::Post()))
/// .f(|r| HttpResponse::MethodNotAllowed())); /// .f(|r| HttpResponse::MethodNotAllowed())
/// });
/// } /// }
/// ``` /// ```
pub fn Any<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AnyPredicate<S> { pub fn Any<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AnyPredicate<S> {
@ -61,11 +62,14 @@ impl<S: 'static> Predicate<S> for AnyPredicate<S> {
/// use actix_web::{pred, App, HttpResponse}; /// use actix_web::{pred, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// App::new() /// App::new().resource("/index.html", |r| {
/// .resource("/index.html", |r| r.route() /// r.route()
/// .filter(pred::All(pred::Get()) /// .filter(
/// .and(pred::Header("content-type", "plain/text"))) /// pred::All(pred::Get())
/// .f(|_| HttpResponse::MethodNotAllowed())); /// .and(pred::Header("content-type", "plain/text")),
/// )
/// .f(|_| HttpResponse::MethodNotAllowed())
/// });
/// } /// }
/// ``` /// ```
pub fn All<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AllPredicate<S> { pub fn All<S: 'static, P: Predicate<S> + 'static>(pred: P) -> AllPredicate<S> {

View File

@ -24,7 +24,7 @@ use route::Route;
/// predicates route route considered matched and route handler get called. /// predicates route route considered matched and route handler get called.
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// //#### # extern crate actix_web;
/// use actix_web::{App, HttpResponse, http}; /// use actix_web::{App, HttpResponse, http};
/// ///
/// fn main() { /// fn main() {
@ -82,11 +82,12 @@ impl<S: 'static> ResourceHandler<S> {
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new()
/// .resource( /// .resource("/", |r| {
/// "/", |r| r.route() /// r.route()
/// .filter(pred::Any(pred::Get()).or(pred::Put())) /// .filter(pred::Any(pred::Get()).or(pred::Put()))
/// .filter(pred::Header("Content-Type", "text/plain")) /// .filter(pred::Header("Content-Type", "text/plain"))
/// .f(|r| HttpResponse::Ok())) /// .f(|r| HttpResponse::Ok())
/// })
/// .finish(); /// .finish();
/// } /// }
/// ``` /// ```

View File

@ -66,13 +66,12 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// # use actix_web::*;
/// # fn main() { /// # fn main() {
/// App::new() /// App::new().resource("/path", |r| {
/// .resource("/path", |r|
/// r.route() /// r.route()
/// .filter(pred::Get()) /// .filter(pred::Get())
/// .filter(pred::Header("content-type", "text/plain")) /// .filter(pred::Header("content-type", "text/plain"))
/// .f(|req| HttpResponse::Ok()) /// .f(|req| HttpResponse::Ok())
/// ) /// })
/// # .finish(); /// # .finish();
/// # } /// # }
/// ``` /// ```
@ -115,7 +114,7 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Path, Result, http}; /// use actix_web::{http, App, Path, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -130,7 +129,8 @@ impl<S: 'static> Route<S> {
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index),
/// ); // <- use `with` extractor
/// } /// }
/// ``` /// ```
/// ///
@ -143,7 +143,7 @@ impl<S: 'static> Route<S> {
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// # use std::collections::HashMap; /// # use std::collections::HashMap;
/// use actix_web::{http, App, Query, Path, Result, Json}; /// use actix_web::{http, App, Json, Path, Query, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -151,14 +151,17 @@ impl<S: 'static> Route<S> {
/// } /// }
/// ///
/// /// extract path info using serde /// /// extract path info using serde
/// fn index(info: (Path<Info>, Query<HashMap<String, String>>, Json<Info>)) -> Result<String> { /// fn index(
/// info: (Path<Info>, Query<HashMap<String, String>>, Json<Info>),
/// ) -> Result<String> {
/// Ok(format!("Welcome {}!", info.0.username)) /// Ok(format!("Welcome {}!", info.0.username))
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index),
/// ); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub fn with<T, F, R>(&mut self, handler: F) -> ExtractorConfig<S, T> pub fn with<T, F, R>(&mut self, handler: F) -> ExtractorConfig<S, T>
@ -181,7 +184,7 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Path, Error, http}; /// use actix_web::{http, App, Error, Path};
/// use futures::Future; /// use futures::Future;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
@ -197,8 +200,8 @@ impl<S: 'static> Route<S> {
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(http::Method::GET) /// |r| r.method(http::Method::GET).with_async(index),
/// .with_async(index)); // <- use `with` extractor /// ); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub fn with_async<T, F, R, I, E>(&mut self, handler: F) -> ExtractorConfig<S, T> pub fn with_async<T, F, R, I, E>(&mut self, handler: F) -> ExtractorConfig<S, T>
@ -222,7 +225,7 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Query, Path, Result, http}; /// use actix_web::{http, App, Path, Query, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct PParam { /// struct PParam {
@ -242,7 +245,8 @@ impl<S: 'static> Route<S> {
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(http::Method::GET).with2(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with2(index),
/// ); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub fn with2<T1, T2, F, R>( pub fn with2<T1, T2, F, R>(

View File

@ -38,9 +38,9 @@ type NestedInfo<S> = (Resource, Route<S>, Vec<Box<Predicate<S>>>);
/// use actix_web::{http, App, HttpRequest, HttpResponse}; /// use actix_web::{http, App, HttpRequest, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().scope("/{project_id}/", |scope| {
/// .scope("/{project_id}/", |scope| { /// scope
/// scope.resource("/path1", |r| r.f(|_| HttpResponse::Ok())) /// .resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
/// .resource("/path2", |r| r.f(|_| HttpResponse::Ok())) /// .resource("/path2", |r| r.f(|_| HttpResponse::Ok()))
/// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed())) /// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed()))
/// }); /// });
@ -89,12 +89,13 @@ impl<S: 'static> Scope<S> {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().scope("/app", |scope| {
/// .scope("/app", |scope| { /// scope
/// scope.filter(pred::Header("content-type", "text/plain")) /// .filter(pred::Header("content-type", "text/plain"))
/// .route("/test1", http::Method::GET, index) /// .route("/test1", http::Method::GET, index)
/// .route("/test2", http::Method::POST, /// .route("/test2", http::Method::POST, |_: HttpRequest| {
/// |_: HttpRequest| HttpResponse::MethodNotAllowed()) /// HttpResponse::MethodNotAllowed()
/// })
/// }); /// });
/// } /// }
/// ``` /// ```
@ -116,8 +117,7 @@ impl<S: 'static> Scope<S> {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().scope("/app", |scope| {
/// .scope("/app", |scope| {
/// scope.with_state("/state2", AppState, |scope| { /// scope.with_state("/state2", AppState, |scope| {
/// scope.resource("/test1", |r| r.f(index)) /// scope.resource("/test1", |r| r.f(index))
/// }) /// })
@ -162,11 +162,8 @@ impl<S: 'static> Scope<S> {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::with_state(AppState) /// let app = App::with_state(AppState).scope("/app", |scope| {
/// .scope("/app", |scope| { /// scope.nested("/v1", |scope| scope.resource("/test1", |r| r.f(index)))
/// scope.nested("/v1", |scope| {
/// scope.resource("/test1", |r| r.f(index))
/// })
/// }); /// });
/// } /// }
/// ``` /// ```
@ -211,11 +208,12 @@ impl<S: 'static> Scope<S> {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().scope("/app", |scope| {
/// .scope("/app", |scope| { /// scope.route("/test1", http::Method::GET, index).route(
/// scope.route("/test1", http::Method::GET, index) /// "/test2",
/// .route("/test2", http::Method::POST, /// http::Method::POST,
/// |_: HttpRequest| HttpResponse::MethodNotAllowed()) /// |_: HttpRequest| HttpResponse::MethodNotAllowed(),
/// )
/// }); /// });
/// } /// }
/// ``` /// ```
@ -261,8 +259,7 @@ impl<S: 'static> Scope<S> {
/// use actix_web::*; /// use actix_web::*;
/// ///
/// fn main() { /// fn main() {
/// let app = App::new() /// let app = App::new().scope("/api", |scope| {
/// .scope("/api", |scope| {
/// scope.resource("/users/{userid}/{friend}", |r| { /// scope.resource("/users/{userid}/{friend}", |r| {
/// r.get().f(|_| HttpResponse::Ok()); /// r.get().f(|_| HttpResponse::Ok());
/// r.head().f(|_| HttpResponse::MethodNotAllowed()); /// r.head().f(|_| HttpResponse::MethodNotAllowed());

View File

@ -19,7 +19,7 @@ use httpresponse::HttpResponse;
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Form, Result, http}; /// use actix_web::{http, App, Form, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct FormData { /// struct FormData {
@ -32,10 +32,10 @@ use httpresponse::HttpResponse;
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/index.html", |r| { /// "/index.html",
/// r.method(http::Method::GET) /// |r| {
/// .with(index) /// r.method(http::Method::GET).with(index).limit(4096);
/// .limit(4096);} // <- change form extractor configuration /// }, // <- change form extractor configuration
/// ); /// );
/// } /// }
/// ``` /// ```
@ -45,7 +45,7 @@ use httpresponse::HttpResponse;
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::{App, Form, Path, Result, http}; /// use actix_web::{http, App, Form, Path, Result};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct FormData { /// struct FormData {
@ -58,10 +58,10 @@ use httpresponse::HttpResponse;
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource( /// let app = App::new().resource(
/// "/index.html", |r| { /// "/index.html",
/// r.method(http::Method::GET) /// |r| {
/// .with(index) /// r.method(http::Method::GET).with(index).1.limit(4096);
/// .1.limit(4096);} // <- change form extractor configuration /// }, // <- change form extractor configuration
/// ); /// );
/// } /// }
/// ``` /// ```