1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 01:32:57 +01:00

rename Application

This commit is contained in:
Nikolay Kim 2018-03-31 00:16:55 -07:00
parent 7a743fa6b5
commit 3ee228005d
51 changed files with 237 additions and 238 deletions

View File

@ -9,7 +9,7 @@ use futures::Stream;
use std::{io, env}; use std::{io, env};
use actix_web::{error, fs, pred, use actix_web::{error, fs, pred,
Application, HttpRequest, HttpResponse, HttpServer, Result, Error}; App, HttpRequest, HttpResponse, HttpServer, Result, Error};
use actix_web::http::{Method, StatusCode}; use actix_web::http::{Method, StatusCode};
use actix_web::middleware::{self, RequestSession}; use actix_web::middleware::{self, RequestSession};
use futures::future::{FutureResult, result}; use futures::future::{FutureResult, result};
@ -100,7 +100,7 @@ fn main() {
let sys = actix::System::new("basic-example"); let sys = actix::System::new("basic-example");
let addr = HttpServer::new( let addr = HttpServer::new(
|| Application::new() || App::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// cookie session middleware // cookie session middleware

View File

@ -18,7 +18,7 @@ extern crate env_logger;
use actix::prelude::*; use actix::prelude::*;
use actix_web::{http, middleware, use actix_web::{http, middleware,
Application, HttpServer, HttpRequest, HttpResponse, Error, AsyncResponder}; App, HttpServer, HttpRequest, HttpResponse, Error, AsyncResponder};
use diesel::prelude::*; use diesel::prelude::*;
use futures::future::Future; use futures::future::Future;
@ -63,7 +63,7 @@ fn main() {
// Start http server // Start http server
let _addr = HttpServer::new(move || { let _addr = HttpServer::new(move || {
Application::with_state(State{db: addr.clone()}) App::with_state(State{db: addr.clone()})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/{name}", |r| r.method(http::Method::GET).a(index))}) .resource("/{name}", |r| r.method(http::Method::GET).a(index))})

View File

@ -2,7 +2,7 @@ extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use actix_web::{Application, HttpRequest, server, middleware}; use actix_web::{App, HttpRequest, server, middleware};
fn index(_req: HttpRequest) -> &'static str { fn index(_req: HttpRequest) -> &'static str {
@ -15,7 +15,7 @@ fn main() {
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
let _addr = server::new( let _addr = server::new(
|| Application::new() || App::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/index.html", |r| r.f(|_| "Hello world!")) .resource("/index.html", |r| r.f(|_| "Hello world!"))

View File

@ -5,7 +5,7 @@ extern crate env_logger;
use futures::{Future, Stream}; use futures::{Future, Stream};
use actix_web::{client, server, middleware, use actix_web::{client, server, middleware,
Application, AsyncResponder, Body, App, AsyncResponder, Body,
HttpRequest, HttpResponse, HttpMessage, Error}; HttpRequest, HttpResponse, HttpMessage, Error};
/// Stream client request response and then send body to a server response /// Stream client request response and then send body to a server response
@ -45,7 +45,7 @@ fn main() {
let sys = actix::System::new("http-proxy"); let sys = actix::System::new("http-proxy");
let _addr = server::new( let _addr = server::new(
|| Application::new() || App::new()
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/streaming", |r| r.f(streaming)) .resource("/streaming", |r| r.f(streaming))
.resource("/", |r| r.f(index))) .resource("/", |r| r.f(index)))

View File

@ -7,9 +7,9 @@ extern crate serde_json;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
#[macro_use] extern crate json; #[macro_use] extern crate json;
use actix_web::{middleware, http, error, server, use actix_web::{
Application, AsyncResponder, middleware, http, error, server,
HttpRequest, HttpResponse, HttpMessage, Error, Json}; App, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error, Json};
use bytes::BytesMut; use bytes::BytesMut;
use futures::{Future, Stream}; use futures::{Future, Stream};
@ -90,7 +90,7 @@ fn main() {
let sys = actix::System::new("json-example"); let sys = actix::System::new("json-example");
let _ = server::new(|| { let _ = server::new(|| {
Application::new() App::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/extractor/{name}/{number}/", .resource("/extractor/{name}/{number}/",

View File

@ -13,9 +13,9 @@ extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use actix::prelude::*; use actix::prelude::*;
use actix_web::{middleware, http, server, use actix_web::{
Application, AsyncResponder, middleware, http, server,
HttpRequest, HttpResponse, HttpMessage, Error}; App, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error};
use juniper::http::graphiql::graphiql_source; use juniper::http::graphiql::graphiql_source;
use juniper::http::GraphQLRequest; use juniper::http::GraphQLRequest;
@ -99,7 +99,7 @@ fn main() {
// Start http server // Start http server
let _ = server::new(move || { let _ = server::new(move || {
Application::with_state(State{executor: addr.clone()}) App::with_state(State{executor: addr.clone()})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/graphql", |r| r.method(http::Method::POST).h(graphql)) .resource("/graphql", |r| r.method(http::Method::POST).h(graphql))

View File

@ -7,7 +7,7 @@ extern crate futures;
use actix::*; use actix::*;
use actix_web::{ use actix_web::{
http, middleware, multipart, server, http, middleware, multipart, server,
Application, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error}; App, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error};
use futures::{Future, Stream}; use futures::{Future, Stream};
use futures::future::{result, Either}; use futures::future::{result, Either};
@ -50,7 +50,7 @@ fn main() {
let sys = actix::System::new("multipart-example"); let sys = actix::System::new("multipart-example");
let _ = server::new( let _ = server::new(
|| Application::new() || App::new()
.middleware(middleware::Logger::default()) // <- logger .middleware(middleware::Logger::default()) // <- logger
.resource("/multipart", |r| r.method(http::Method::POST).a(index))) .resource("/multipart", |r| r.method(http::Method::POST).a(index)))
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()

View File

@ -12,7 +12,7 @@ extern crate prost_derive;
use futures::Future; use futures::Future;
use actix_web::{ use actix_web::{
http, middleware, server, http, middleware, server,
Application, AsyncResponder, HttpRequest, HttpResponse, Error}; App, AsyncResponder, HttpRequest, HttpResponse, Error};
mod protobuf; mod protobuf;
use protobuf::ProtoBufResponseBuilder; use protobuf::ProtoBufResponseBuilder;
@ -45,7 +45,7 @@ fn main() {
let sys = actix::System::new("protobuf-example"); let sys = actix::System::new("protobuf-example");
let _ = server::new(|| { let _ = server::new(|| {
Application::new() App::new()
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/", |r| r.method(http::Method::POST).f(index))}) .resource("/", |r| r.method(http::Method::POST).f(index))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()

View File

@ -12,8 +12,7 @@ extern crate rusqlite;
use actix::prelude::*; use actix::prelude::*;
use actix_web::{ use actix_web::{
middleware, http, server, middleware, http, server, App, AsyncResponder, HttpRequest, HttpResponse, Error};
Application, AsyncResponder, HttpRequest, HttpResponse, Error};
use futures::future::Future; use futures::future::Future;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
@ -55,7 +54,7 @@ fn main() {
// Start http server // Start http server
let _ = server::new(move || { let _ = server::new(move || {
Application::with_state(State{db: addr.clone()}) App::with_state(State{db: addr.clone()})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/{name}", |r| r.method(http::Method::GET).a(index))}) .resource("/{name}", |r| r.method(http::Method::GET).a(index))})

View File

@ -11,7 +11,7 @@ use std::cell::Cell;
use actix::prelude::*; use actix::prelude::*;
use actix_web::{ use actix_web::{
http, server, ws, middleware, Application, HttpRequest, HttpResponse}; http, server, ws, middleware, App, HttpRequest, HttpResponse};
/// Application state /// Application state
struct AppState { struct AppState {
@ -59,7 +59,7 @@ fn main() {
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
let _ = server::new( let _ = server::new(
|| Application::with_state(AppState{counter: Cell::new(0)}) || App::with_state(AppState{counter: Cell::new(0)})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// websocket route // websocket route

View File

@ -5,9 +5,7 @@ extern crate env_logger;
extern crate tera; extern crate tera;
use actix_web::{ use actix_web::{
http, error, middleware, server, http, error, middleware, server, App, HttpRequest, HttpResponse, Error};
Application, HttpRequest, HttpResponse, Error,
};
struct State { struct State {
@ -38,7 +36,7 @@ fn main() {
let _ = server::new(|| { let _ = server::new(|| {
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")); let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
Application::with_state(State{template: tera}) App::with_state(State{template: tera})
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/", |r| r.method(http::Method::GET).f(index))}) .resource("/", |r| r.method(http::Method::GET).f(index))})

View File

@ -6,8 +6,7 @@ extern crate openssl;
use openssl::ssl::{SslMethod, SslAcceptor, SslFiletype}; use openssl::ssl::{SslMethod, SslAcceptor, SslFiletype};
use actix_web::{ use actix_web::{
http, middleware, server, http, middleware, server, App, HttpRequest, HttpResponse, Error};
Application, HttpRequest, HttpResponse, Error};
/// simple handle /// simple handle
@ -31,7 +30,7 @@ fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap(); builder.set_certificate_chain_file("cert.pem").unwrap();
let _ = server::new( let _ = server::new(
|| Application::new() || App::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// register simple handler, handle all methods // register simple handler, handle all methods

View File

@ -14,12 +14,13 @@ fn index(_req: HttpRequest) -> &'static str {
fn main() { fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info"); ::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init(); env_logger::init();
let sys = actix::System::new("unix-socket"); let sys = actix::System::new("unix-socket");
let listener = UnixListener::bind("/tmp/actix-uds.socket", Arbiter::handle()).expect("bind failed"); let listener = UnixListener::bind(
let _addr = HttpServer::new( "/tmp/actix-uds.socket", Arbiter::handle()).expect("bind failed");
|| Application::new() HttpServer::new(
|| App::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/index.html", |r| r.f(|_| "Hello world!")) .resource("/index.html", |r| r.f(|_| "Hello world!"))

View File

@ -7,7 +7,7 @@ extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use std::env; use std::env;
use actix_web::{http, middleware, server, Application}; use actix_web::{http, middleware, server, App};
mod user; mod user;
use user::info; use user::info;
@ -20,7 +20,7 @@ fn main() {
let sys = actix::System::new("Actix-web-CORS"); let sys = actix::System::new("Actix-web-CORS");
server::new( server::new(
|| Application::new() || App::new()
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/user/info", |r| { .resource("/user/info", |r| {
middleware::cors::Cors::build() middleware::cors::Cors::build()

View File

@ -17,9 +17,7 @@ extern crate actix_web;
use std::time::Instant; use std::time::Instant;
use actix::*; use actix::*;
use actix_web::{ use actix_web::{http, fs, ws, App, HttpRequest, HttpResponse, HttpServer, Error};
http, fs, ws,
Application, HttpRequest, HttpResponse, HttpServer, Error};
mod codec; mod codec;
mod server; mod server;
@ -190,7 +188,7 @@ fn main() {
// Websocket sessions state // Websocket sessions state
let state = WsChatSessionState { addr: server.clone() }; let state = WsChatSessionState { addr: server.clone() };
Application::with_state(state) App::with_state(state)
// redirect to websocket.html // redirect to websocket.html
.resource("/", |r| r.method(http::Method::GET).f(|_| { .resource("/", |r| r.method(http::Method::GET).f(|_| {
HttpResponse::Found() HttpResponse::Found()

View File

@ -10,9 +10,7 @@ extern crate env_logger;
use actix::prelude::*; use actix::prelude::*;
use actix_web::{ use actix_web::{
http, middleware, server, fs, ws, http, middleware, server, fs, ws, App, HttpRequest, HttpResponse, Error};
Application, HttpRequest, HttpResponse, Error,
};
/// do websocket handshake and start `MyWebSocket` actor /// do websocket handshake and start `MyWebSocket` actor
fn ws_index(r: HttpRequest) -> Result<HttpResponse, Error> { fn ws_index(r: HttpRequest) -> Result<HttpResponse, Error> {
@ -51,7 +49,7 @@ fn main() {
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
server::new( server::new(
|| Application::new() || App::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// websocket route // websocket route

View File

@ -23,7 +23,7 @@ Here is an example of a simple middleware that adds request and response headers
# extern crate http; # extern crate http;
# extern crate actix_web; # extern crate actix_web;
use http::{header, HttpTryFrom}; use http::{header, HttpTryFrom};
use actix_web::{Application, HttpRequest, HttpResponse, Result}; use actix_web::{App, HttpRequest, HttpResponse, Result};
use actix_web::middleware::{Middleware, Started, Response}; use actix_web::middleware::{Middleware, Started, Response};
struct Headers; // <- Our middleware struct Headers; // <- Our middleware
@ -51,7 +51,7 @@ impl<S> Middleware<S> for Headers {
} }
fn main() { fn main() {
Application::new() App::new()
.middleware(Headers) // <- Register middleware, this method can be called multiple times .middleware(Headers) // <- Register middleware, this method can be called multiple times
.resource("/", |r| r.f(|_| HttpResponse::Ok())); .resource("/", |r| r.f(|_| HttpResponse::Ok()));
} }
@ -79,14 +79,14 @@ Default `Logger` can be created with `default` method, it uses the default forma
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use actix_web::Application; use actix_web::App;
use actix_web::middleware::Logger; use actix_web::middleware::Logger;
fn main() { fn main() {
std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();
Application::new() App::new()
.middleware(Logger::default()) .middleware(Logger::default())
.middleware(Logger::new("%a %{User-Agent}i")) .middleware(Logger::new("%a %{User-Agent}i"))
.finish(); .finish();
@ -135,10 +135,10 @@ the specified header.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{http, middleware, Application, HttpResponse}; use actix_web::{http, middleware, App, HttpResponse};
fn main() { fn main() {
let app = Application::new() let app = App::new()
.middleware( .middleware(
middleware::DefaultHeaders::build() middleware::DefaultHeaders::build()
.header("X-Version", "0.2") .header("X-Version", "0.2")
@ -198,7 +198,7 @@ fn index(mut req: HttpRequest) -> Result<&'static str> {
fn main() { fn main() {
# let sys = actix::System::new("basic-example"); # let sys = actix::System::new("basic-example");
HttpServer::new( HttpServer::new(
|| Application::new() || App::new()
.middleware(SessionStorage::new( // <- create session middleware .middleware(SessionStorage::new( // <- create session middleware
CookieSessionBackend::build(&[0; 32]) // <- create cookie session backend CookieSessionBackend::build(&[0; 32]) // <- create cookie session backend
.secure(false) .secure(false)

View File

@ -8,7 +8,7 @@ match path tail we can use `[.*]` regex.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use std::path::PathBuf; use std::path::PathBuf;
use actix_web::{Application, HttpRequest, Result, http::Method, fs::NamedFile}; use actix_web::{App, HttpRequest, Result, http::Method, fs::NamedFile};
fn index(req: HttpRequest) -> Result<NamedFile> { fn index(req: HttpRequest) -> Result<NamedFile> {
let path: PathBuf = req.match_info().query("tail")?; let path: PathBuf = req.match_info().query("tail")?;
@ -16,7 +16,7 @@ fn index(req: HttpRequest) -> Result<NamedFile> {
} }
fn main() { fn main() {
Application::new() App::new()
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index)) .resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
.finish(); .finish();
} }
@ -25,7 +25,7 @@ fn main() {
## Directory ## Directory
To serve files from specific directory and sub-directories `StaticFiles` could be used. To serve files from specific directory and sub-directories `StaticFiles` could be used.
`StaticFiles` must be registered with `Application::handler()` method otherwise `StaticFiles` must be registered with `App::handler()` method otherwise
it won't be able to serve sub-paths. it won't be able to serve sub-paths.
```rust ```rust
@ -33,7 +33,7 @@ it won't be able to serve sub-paths.
use actix_web::*; use actix_web::*;
fn main() { fn main() {
Application::new() App::new()
.handler("/static", fs::StaticFiles::new(".", true)) .handler("/static", fs::StaticFiles::new(".", true))
.finish(); .finish();
} }

View File

@ -28,7 +28,7 @@ fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap(); builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new( HttpServer::new(
|| Application::new() || App::new()
.resource("/index.html", |r| r.f(index))) .resource("/index.html", |r| r.f(index)))
.bind("127.0.0.1:8080").unwrap(); .bind("127.0.0.1:8080").unwrap();
.serve_ssl(builder).unwrap(); .serve_ssl(builder).unwrap();

View File

@ -87,7 +87,7 @@ fn main() {
// Start http server // Start http server
HttpServer::new(move || { HttpServer::new(move || {
Application::with_state(State{db: addr.clone()}) App::with_state(State{db: addr.clone()})
.resource("/{name}", |r| r.method(Method::GET).a(index))}) .resource("/{name}", |r| r.method(Method::GET).a(index))})
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.start().unwrap(); .start().unwrap();

View File

@ -48,7 +48,7 @@ request handler with the application's `resource` on a particular *HTTP method*
# "Hello world!" # "Hello world!"
# } # }
# fn main() { # fn main() {
Application::new() App::new()
.resource("/", |r| r.f(index)); .resource("/", |r| r.f(index));
# } # }
``` ```
@ -58,7 +58,7 @@ connections. The server accepts a function that should return an `HttpHandler` i
```rust,ignore ```rust,ignore
HttpServer::new( HttpServer::new(
|| Application::new() || App::new()
.resource("/", |r| r.f(index))) .resource("/", |r| r.f(index)))
.bind("127.0.0.1:8088")? .bind("127.0.0.1:8088")?
.run(); .run();
@ -72,7 +72,7 @@ Here is full source of main.rs file:
```rust ```rust
# use std::thread; # use std::thread;
extern crate actix_web; extern crate actix_web;
use actix_web::{Application, HttpRequest, HttpResponse, HttpServer}; use actix_web::{App, HttpRequest, HttpResponse, HttpServer};
fn index(req: HttpRequest) -> &'static str { fn index(req: HttpRequest) -> &'static str {
"Hello world!" "Hello world!"
@ -84,7 +84,7 @@ fn main() {
# // call. # // call.
# thread::spawn(|| { # thread::spawn(|| {
HttpServer::new( HttpServer::new(
|| Application::new() || App::new()
.resource("/", |r| r.f(index))) .resource("/", |r| r.f(index)))
.bind("127.0.0.1:8088").expect("Can not bind to 127.0.0.1:8088") .bind("127.0.0.1:8088").expect("Can not bind to 127.0.0.1:8088")
.run(); .run();

View File

@ -4,7 +4,7 @@ Actix web provides some primitives to build web servers and applications with Ru
It provides routing, middlewares, pre-processing of requests, and post-processing of responses, It provides routing, middlewares, pre-processing of requests, and post-processing of responses,
websocket protocol handling, multipart streams, etc. websocket protocol handling, multipart streams, etc.
All actix web servers are built around the `Application` instance. All actix web servers are built around the `App` instance.
It is used for registering routes for resources, and middlewares. It is used for registering routes for resources, and middlewares.
It also stores application specific state that is shared across all handlers It also stores application specific state that is shared across all handlers
within same application. within same application.
@ -24,7 +24,7 @@ but path `/application` would not match.
# "Hello world!" # "Hello world!"
# } # }
# fn main() { # fn main() {
let app = Application::new() let app = App::new()
.prefix("/app") .prefix("/app")
.resource("/index.html", |r| r.method(Method::GET).f(index)) .resource("/index.html", |r| r.method(Method::GET).f(index))
.finish() .finish()
@ -43,17 +43,17 @@ Multiple applications can be served with one server:
# extern crate tokio_core; # extern crate tokio_core;
# use tokio_core::net::TcpStream; # use tokio_core::net::TcpStream;
# use std::net::SocketAddr; # use std::net::SocketAddr;
use actix_web::{Application, HttpResponse, HttpServer}; use actix_web::{App, HttpResponse, HttpServer};
fn main() { fn main() {
HttpServer::new(|| vec![ HttpServer::new(|| vec![
Application::new() App::new()
.prefix("/app1") .prefix("/app1")
.resource("/", |r| r.f(|r| HttpResponse::Ok())), .resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new() App::new()
.prefix("/app2") .prefix("/app2")
.resource("/", |r| r.f(|r| HttpResponse::Ok())), .resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new() App::new()
.resource("/", |r| r.f(|r| HttpResponse::Ok())), .resource("/", |r| r.f(|r| HttpResponse::Ok())),
]); ]);
} }
@ -81,7 +81,7 @@ in the state:
# extern crate actix_web; # extern crate actix_web;
# #
use std::cell::Cell; use std::cell::Cell;
use actix_web::{Application, HttpRequest, http}; use actix_web::{App, HttpRequest, http};
// This struct represents state // This struct represents state
struct AppState { struct AppState {
@ -96,7 +96,7 @@ fn index(req: HttpRequest<AppState>) -> String {
} }
fn main() { fn main() {
Application::with_state(AppState{counter: Cell::new(0)}) App::with_state(AppState{counter: Cell::new(0)})
.resource("/", |r| r.method(http::Method::GET).f(index)) .resource("/", |r| r.method(http::Method::GET).f(index))
.finish(); .finish();
} }

View File

@ -13,13 +13,13 @@ within a properly configured actix system:
# extern crate actix; # extern crate actix;
# extern crate actix_web; # extern crate actix_web;
use actix::*; use actix::*;
use actix_web::{server, Application, HttpResponse}; use actix_web::{server, App, HttpResponse};
fn main() { fn main() {
let sys = actix::System::new("guide"); let sys = actix::System::new("guide");
server::new( server::new(
|| Application::new() || App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok()))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.bind("127.0.0.1:59080").unwrap() .bind("127.0.0.1:59080").unwrap()
.start(); .start();
@ -49,7 +49,7 @@ address of the started http server. Actix http server accepts several messages:
use std::thread; use std::thread;
use std::sync::mpsc; use std::sync::mpsc;
use actix::*; use actix::*;
use actix_web::{server, Application, HttpResponse, HttpServer}; use actix_web::{server, App, HttpResponse, HttpServer};
fn main() { fn main() {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
@ -57,7 +57,7 @@ fn main() {
thread::spawn(move || { thread::spawn(move || {
let sys = actix::System::new("http-server"); let sys = actix::System::new("http-server");
let addr = server::new( let addr = server::new(
|| Application::new() || App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok()))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0") .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
.shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds .shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds
@ -81,11 +81,11 @@ can be overridden with the `HttpServer::threads()` method.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# extern crate tokio_core; # extern crate tokio_core;
use actix_web::{Application, HttpServer, HttpResponse}; use actix_web::{App, HttpServer, HttpResponse};
fn main() { fn main() {
HttpServer::new( HttpServer::new(
|| Application::new() || App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok()))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.threads(4); // <- Start 4 workers .threads(4); // <- Start 4 workers
} }
@ -116,7 +116,7 @@ fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap(); builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new( HttpServer::new(
|| Application::new() || App::new()
.resource("/index.html", |r| r.f(index))) .resource("/index.html", |r| r.f(index)))
.bind("127.0.0.1:8080").unwrap() .bind("127.0.0.1:8080").unwrap()
.serve_ssl(builder).unwrap(); .serve_ssl(builder).unwrap();
@ -143,21 +143,21 @@ connection behavior is defined by server settings.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# extern crate tokio_core; # extern crate tokio_core;
use actix_web::{server, Application, HttpResponse}; use actix_web::{server, App, HttpResponse};
fn main() { fn main() {
server::new(|| server::new(||
Application::new() App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok()))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(75); // <- Set keep-alive to 75 seconds .keep_alive(75); // <- Set keep-alive to 75 seconds
server::new(|| server::new(||
Application::new() App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok()))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(server::KeepAlive::Tcp(75)); // <- Use `SO_KEEPALIVE` socket option. .keep_alive(server::KeepAlive::Tcp(75)); // <- Use `SO_KEEPALIVE` socket option.
server::new(|| server::new(||
Application::new() App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok()))) .resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(None); // <- Disable keep-alive .keep_alive(None); // <- Disable keep-alive
} }

View File

@ -53,7 +53,7 @@ Here is an example of a handler that stores the number of processed requests:
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{Application, HttpRequest, HttpResponse, dev::Handler}; use actix_web::{App, HttpRequest, HttpResponse, dev::Handler};
struct MyHandler(usize); struct MyHandler(usize);
@ -75,7 +75,7 @@ number of requests processed per thread. A proper implementation would use `Arc`
```rust ```rust
# extern crate actix; # extern crate actix;
# extern crate actix_web; # extern crate actix_web;
use actix_web::{server, Application, HttpRequest, HttpResponse, dev::Handler}; use actix_web::{server, App, HttpRequest, HttpResponse, dev::Handler};
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
@ -99,7 +99,7 @@ fn main() {
server::new( server::new(
move || { move || {
let cloned = inc.clone(); let cloned = inc.clone();
Application::new() App::new()
.resource("/", move |r| r.h(MyHandler(cloned))) .resource("/", move |r| r.h(MyHandler(cloned)))
}) })
.bind("127.0.0.1:8088").unwrap() .bind("127.0.0.1:8088").unwrap()
@ -127,7 +127,7 @@ Let's create a response for a custom type that serializes to an `application/jso
extern crate serde; extern crate serde;
extern crate serde_json; extern crate serde_json;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
use actix_web::{Application, HttpServer, HttpRequest, HttpResponse, Error, Responder, http}; use actix_web::{App, HttpServer, HttpRequest, HttpResponse, Error, Responder, http};
#[derive(Serialize)] #[derive(Serialize)]
struct MyObj { struct MyObj {
@ -158,7 +158,7 @@ fn main() {
let sys = actix::System::new("example"); let sys = actix::System::new("example");
HttpServer::new( HttpServer::new(
|| Application::new() || App::new()
.resource("/", |r| r.method(http::Method::GET).f(index))) .resource("/", |r| r.method(http::Method::GET).f(index)))
.bind("127.0.0.1:8088").unwrap() .bind("127.0.0.1:8088").unwrap()
.start(); .start();
@ -198,7 +198,7 @@ fn index2(req: HttpRequest) -> Box<Future<Item=&'static str, Error=Error>> {
} }
fn main() { fn main() {
Application::new() App::new()
.resource("/async", |r| r.route().a(index)) .resource("/async", |r| r.route().a(index))
.resource("/", |r| r.route().a(index2)) .resource("/", |r| r.route().a(index2))
.finish(); .finish();
@ -224,7 +224,7 @@ fn index(req: HttpRequest) -> HttpResponse {
} }
fn main() { fn main() {
Application::new() App::new()
.resource("/async", |r| r.f(index)) .resource("/async", |r| r.f(index))
.finish(); .finish();
} }
@ -257,7 +257,7 @@ fn index(req: HttpRequest) -> Result<Box<Future<Item=HttpResponse, Error=Error>>
# #
# fn is_error() -> bool { true } # fn is_error() -> bool { true }
# fn main() { # fn main() {
# Application::new() # App::new()
# .resource("/async", |r| r.route().f(index)) # .resource("/async", |r| r.route().f(index))
# .finish(); # .finish();
# } # }
@ -294,7 +294,7 @@ fn index(req: HttpRequest) -> RegisterResult {
} }
# fn is_a_variant() -> bool { true } # fn is_a_variant() -> bool { true }
# fn main() { # fn main() {
# Application::new() # App::new()
# .resource("/register", |r| r.f(index)) # .resource("/register", |r| r.f(index))
# .finish(); # .finish();
# } # }

View File

@ -27,7 +27,7 @@ fn index(req: HttpRequest) -> io::Result<fs::NamedFile> {
} }
# #
# fn main() { # fn main() {
# Application::new() # App::new()
# .resource(r"/a/index.html", |r| r.f(index)) # .resource(r"/a/index.html", |r| r.f(index))
# .finish(); # .finish();
# } # }
@ -58,7 +58,7 @@ fn index(req: HttpRequest) -> Result<&'static str, MyError> {
} }
# #
# fn main() { # fn main() {
# Application::new() # App::new()
# .resource(r"/a/index.html", |r| r.f(index)) # .resource(r"/a/index.html", |r| r.f(index))
# .finish(); # .finish();
# } # }
@ -70,7 +70,7 @@ to return different responses for different types of errors.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
#[macro_use] extern crate failure; #[macro_use] extern crate failure;
use actix_web::{Application, HttpRequest, HttpResponse, http, error}; use actix_web::{App, HttpRequest, HttpResponse, http, error};
#[derive(Fail, Debug)] #[derive(Fail, Debug)]
enum MyError { enum MyError {
@ -100,7 +100,7 @@ fn index(req: HttpRequest) -> Result<&'static str, MyError> {
} }
# #
# fn main() { # fn main() {
# Application::new() # App::new()
# .resource(r"/a/index.html", |r| r.f(index)) # .resource(r"/a/index.html", |r| r.f(index))
# .finish(); # .finish();
# } # }
@ -127,7 +127,7 @@ fn index(req: HttpRequest) -> Result<&'static str> {
Ok(result.map_err(|e| error::ErrorBadRequest(e))?) Ok(result.map_err(|e| error::ErrorBadRequest(e))?)
} }
# fn main() { # fn main() {
# Application::new() # App::new()
# .resource(r"/a/index.html", |r| r.f(index)) # .resource(r"/a/index.html", |r| r.f(index))
# .finish(); # .finish();
# } # }

View File

@ -15,20 +15,20 @@ A resource also has a pattern, meant to match against the *PATH* portion of a *U
it does not match against the *QUERY* portion (the portion following the scheme and it does not match against the *QUERY* portion (the portion following the scheme and
port, e.g., */foo/bar* in the *URL* *http://localhost:8080/foo/bar?q=value*). port, e.g., */foo/bar* in the *URL* *http://localhost:8080/foo/bar?q=value*).
The [Application::resource](../actix_web/struct.Application.html#method.resource) methods The [App::resource](../actix_web/struct.App.html#method.resource) methods
add a single resource to application routing table. This method accepts a *path pattern* add a single resource to application routing table. This method accepts a *path pattern*
and a resource configuration function. and a resource configuration function.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method}; # use actix_web::{App, HttpRequest, HttpResponse, http::Method};
# #
# fn index(req: HttpRequest) -> HttpResponse { # fn index(req: HttpRequest) -> HttpResponse {
# unimplemented!() # unimplemented!()
# } # }
# #
fn main() { fn main() {
Application::new() App::new()
.resource("/prefix", |r| r.f(index)) .resource("/prefix", |r| r.f(index))
.resource("/user/{name}", .resource("/user/{name}",
|r| r.method(Method::GET).f(|req| HttpResponse::Ok())) |r| r.method(Method::GET).f(|req| HttpResponse::Ok()))
@ -63,7 +63,7 @@ any number of *predicates* but only one handler.
# use actix_web::*; # use actix_web::*;
fn main() { fn main() {
Application::new() App::new()
.resource("/path", |resource| .resource("/path", |resource|
resource.route() resource.route()
.filter(pred::Get()) .filter(pred::Get())
@ -108,7 +108,7 @@ against a URL path pattern. `path` represents the path portion of the URL that w
The way that *actix* does this is very simple. When a request enters the system, The way that *actix* does this is very simple. When a request enters the system,
for each resource configuration declaration present in the system, actix checks for each resource configuration declaration present in the system, actix checks
the request's path against the pattern declared. This checking happens in the order that the request's path against the pattern declared. This checking happens in the order that
the routes were declared via `Application::resource()` method. If resource can not be found, the routes were declared via `App::resource()` method. If resource can not be found,
the *default resource* is used as the matched resource. the *default resource* is used as the matched resource.
When a route configuration is declared, it may contain route predicate arguments. All route When a route configuration is declared, it may contain route predicate arguments. All route
@ -277,7 +277,7 @@ fn index(req: HttpRequest) -> Result<String> {
} }
fn main() { fn main() {
Application::new() App::new()
.resource(r"/a/{v1}/{v2}/", |r| r.f(index)) .resource(r"/a/{v1}/{v2}/", |r| r.f(index))
.finish(); .finish();
} }
@ -304,7 +304,7 @@ safe to interpolate within, or use as a suffix of, a path without additional che
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use std::path::PathBuf; use std::path::PathBuf;
use actix_web::{Application, HttpRequest, Result, http::Method}; use actix_web::{App, HttpRequest, Result, http::Method};
fn index(req: HttpRequest) -> Result<String> { fn index(req: HttpRequest) -> Result<String> {
let path: PathBuf = req.match_info().query("tail")?; let path: PathBuf = req.match_info().query("tail")?;
@ -312,7 +312,7 @@ fn index(req: HttpRequest) -> Result<String> {
} }
fn main() { fn main() {
Application::new() App::new()
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index)) .resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
.finish(); .finish();
} }
@ -333,7 +333,7 @@ has to implement *serde's *`Deserialize` trait.
# 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::{Application, Path, Result, http::Method}; use actix_web::{App, Path, Result, http::Method};
#[derive(Deserialize)] #[derive(Deserialize)]
struct Info { struct Info {
@ -346,7 +346,7 @@ fn index(info: Path<Info>) -> Result<String> {
} }
fn main() { fn main() {
let app = Application::new() let app = App::new()
.resource("/{username}/index.html", // <- define path parameters .resource("/{username}/index.html", // <- define path parameters
|r| r.method(Method::GET).with(index)); |r| r.method(Method::GET).with(index));
} }
@ -364,7 +364,7 @@ resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this:
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method}; # use actix_web::{App, HttpRequest, HttpResponse, http::Method};
# #
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
@ -372,7 +372,7 @@ fn index(req: HttpRequest) -> HttpResponse {
} }
fn main() { fn main() {
let app = Application::new() let app = App::new()
.resource("/test/{a}/{b}/{c}", |r| { .resource("/test/{a}/{b}/{c}", |r| {
r.name("foo"); // <- set resource name, then it could be used in `url_for` r.name("foo"); // <- set resource name, then it could be used in `url_for`
r.method(Method::GET).f(|_| HttpResponse::Ok()); r.method(Method::GET).f(|_| HttpResponse::Ok());
@ -394,7 +394,7 @@ for URL generation purposes only and are never considered for matching at reques
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{Application, HttpRequest, HttpResponse, Error}; use actix_web::{App, HttpRequest, HttpResponse, Error};
fn index(mut req: HttpRequest) -> Result<HttpResponse, Error> { fn index(mut req: HttpRequest) -> Result<HttpResponse, Error> {
let url = req.url_for("youtube", &["oHg5SJYRHA0"])?; let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
@ -403,7 +403,7 @@ fn index(mut req: HttpRequest) -> Result<HttpResponse, Error> {
} }
fn main() { fn main() {
let app = Application::new() let app = App::new()
.resource("/index.html", |r| r.f(index)) .resource("/index.html", |r| r.f(index))
.external_resource("youtube", "https://youtube.com/watch/{video_id}") .external_resource("youtube", "https://youtube.com/watch/{video_id}")
.finish(); .finish();
@ -440,7 +440,7 @@ use actix_web::http::NormalizePath;
# HttpResponse::Ok().into() # HttpResponse::Ok().into()
# } # }
fn main() { fn main() {
let app = Application::new() let app = App::new()
.resource("/resource/", |r| r.f(index)) .resource("/resource/", |r| r.f(index))
.default_resource(|r| r.h(NormalizePath::default())) .default_resource(|r| r.h(NormalizePath::default()))
.finish(); .finish();
@ -459,13 +459,13 @@ It is possible to register path normalization only for *GET* requests only:
```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::{Application, HttpRequest, http::Method, http::NormalizePath}; use actix_web::{App, HttpRequest, http::Method, http::NormalizePath};
# #
# fn index(req: HttpRequest) -> &'static str { # fn index(req: HttpRequest) -> &'static str {
# "test" # "test"
# } # }
fn main() { fn main() {
let app = Application::new() let app = App::new()
.resource("/resource/", |r| r.f(index)) .resource("/resource/", |r| r.f(index))
.default_resource(|r| r.method(Method::GET).h(NormalizePath::default())) .default_resource(|r| r.method(Method::GET).h(NormalizePath::default()))
.finish(); .finish();
@ -474,7 +474,7 @@ fn main() {
## Using an Application Prefix to Compose Applications ## Using an Application Prefix to Compose Applications
The `Application::prefix()`" method allows to set a specific application prefix. The `App::prefix()`" method allows to set a specific application prefix.
This prefix represents a resource prefix that will be prepended to all resource patterns added This prefix represents a resource prefix that will be prepended to all resource patterns added
by the resource configuration. This can be used to help mount a set of routes at a different by the resource configuration. This can be used to help mount a set of routes at a different
location than the included callable's author intended while still maintaining the same location than the included callable's author intended while still maintaining the same
@ -491,7 +491,7 @@ fn show_users(req: HttpRequest) -> HttpResponse {
} }
fn main() { fn main() {
Application::new() App::new()
.prefix("/users") .prefix("/users")
.resource("/show", |r| r.f(show_users)) .resource("/show", |r| r.f(show_users))
.finish(); .finish();
@ -517,7 +517,7 @@ Here is a simple predicate that check that a request contains a specific *header
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::*; # use actix_web::*;
use actix_web::{http, pred::Predicate, Application, HttpRequest}; use actix_web::{http, pred::Predicate, App, HttpRequest};
struct ContentTypeHeader; struct ContentTypeHeader;
@ -529,7 +529,7 @@ impl<S: 'static> Predicate<S> for ContentTypeHeader {
} }
fn main() { fn main() {
Application::new() App::new()
.resource("/index.html", |r| .resource("/index.html", |r|
r.route() r.route()
.filter(ContentTypeHeader) .filter(ContentTypeHeader)
@ -553,10 +553,10 @@ except "GET":
# extern crate actix_web; # extern crate actix_web;
# extern crate http; # extern crate http;
# use actix_web::*; # use actix_web::*;
use actix_web::{pred, Application, HttpResponse}; use actix_web::{pred, App, HttpResponse};
fn main() { fn main() {
Application::new() App::new()
.resource("/index.html", |r| .resource("/index.html", |r|
r.route() r.route()
.filter(pred::Not(pred::Get())) .filter(pred::Not(pred::Get()))
@ -583,16 +583,16 @@ predicates match. i.e:
If the path pattern can not be found in the routing table or a resource can not find matching If the path pattern can not be found in the routing table or a resource can not find matching
route, the default resource is used. The default response is *NOT FOUND*. route, the default resource is used. The default response is *NOT FOUND*.
It is possible to override the *NOT FOUND* response with `Application::default_resource()`. It is possible to override the *NOT FOUND* response with `App::default_resource()`.
This method accepts a *configuration function* same as normal resource configuration This method accepts a *configuration function* same as normal resource configuration
with `Application::resource()` method. with `App::resource()` method.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{Application, HttpResponse, http::Method, pred}; use actix_web::{App, HttpResponse, http::Method, pred};
fn main() { fn main() {
Application::new() App::new()
.default_resource(|r| { .default_resource(|r| {
r.method(Method::GET).f(|req| HttpResponse::NotFound()); r.method(Method::GET).f(|req| HttpResponse::NotFound());
r.route().filter(pred::Not(pred::Get())) r.route().filter(pred::Not(pred::Get()))

View File

@ -135,7 +135,7 @@ type `T` must implement the `Serialize` trait from *serde*.
```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::{Application, HttpRequest, Json, Result, http::Method}; use actix_web::{App, HttpRequest, Json, Result, http::Method};
#[derive(Serialize)] #[derive(Serialize)]
struct MyObj { struct MyObj {
@ -147,7 +147,7 @@ fn index(req: HttpRequest) -> Result<Json<MyObj>> {
} }
fn main() { fn main() {
Application::new() App::new()
.resource(r"/a/{name}", |r| r.method(Method::GET).f(index)) .resource(r"/a/{name}", |r| r.method(Method::GET).f(index))
.finish(); .finish();
} }

View File

@ -75,15 +75,15 @@ function same way as you would for real http server configuration.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{http, test, Application, HttpRequest, HttpResponse}; use actix_web::{http, test, App, HttpRequest, HttpResponse};
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok().into() HttpResponse::Ok().into()
} }
/// This function get called by http server. /// This function get called by http server.
fn create_app() -> Application { fn create_app() -> App {
Application::new() App::new()
.resource("/test", |r| r.h(index)) .resource("/test", |r| r.h(index))
} }

View File

@ -35,7 +35,7 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {
} }
fn main() { fn main() {
Application::new() App::new()
.resource("/ws/", |r| r.f(|req| ws::start(req, Ws))) // <- register websocket route .resource("/ws/", |r| r.f(|req| ws::start(req, Ws))) // <- register websocket route
.finish(); .finish();
} }

View File

@ -13,6 +13,9 @@ use pipeline::{Pipeline, PipelineHandler};
use middleware::Middleware; use middleware::Middleware;
use server::{HttpHandler, IntoHttpHandler, HttpHandlerTask, ServerSettings}; use server::{HttpHandler, IntoHttpHandler, HttpHandlerTask, ServerSettings};
#[deprecated(since="0.5.0", note="please use `actix_web::App` instead")]
pub type Application<S> = App<S>;
/// Application /// Application
pub struct HttpApplication<S=()> { pub struct HttpApplication<S=()> {
state: Rc<S>, state: Rc<S>,
@ -108,17 +111,17 @@ struct ApplicationParts<S> {
middlewares: Vec<Box<Middleware<S>>>, middlewares: Vec<Box<Middleware<S>>>,
} }
/// Structure that follows the builder pattern for building `Application` structs. /// Structure that follows the builder pattern for building application instances.
pub struct Application<S=()> { pub struct App<S=()> {
parts: Option<ApplicationParts<S>>, parts: Option<ApplicationParts<S>>,
} }
impl Application<()> { impl App<()> {
/// Create application with empty state. Application can /// Create application with empty state. Application can
/// be configured with builder-like pattern. /// be configured with builder-like pattern.
pub fn new() -> Application<()> { pub fn new() -> App<()> {
Application { App {
parts: Some(ApplicationParts { parts: Some(ApplicationParts {
state: (), state: (),
prefix: "/".to_owned(), prefix: "/".to_owned(),
@ -134,21 +137,21 @@ impl Application<()> {
} }
} }
impl Default for Application<()> { impl Default for App<()> {
fn default() -> Self { fn default() -> Self {
Application::new() App::new()
} }
} }
impl<S> Application<S> where S: 'static { impl<S> App<S> where S: 'static {
/// Create application with specific state. Application can be /// Create application with specific state. Application can be
/// configured with builder-like pattern. /// configured with builder-like pattern.
/// ///
/// State is shared with all resources within same application and could be /// State is shared with all resources within same application and could be
/// accessed with `HttpRequest::state()` method. /// accessed with `HttpRequest::state()` method.
pub fn with_state(state: S) -> Application<S> { pub fn with_state(state: S) -> App<S> {
Application { App {
parts: Some(ApplicationParts { parts: Some(ApplicationParts {
state, state,
prefix: "/".to_owned(), prefix: "/".to_owned(),
@ -178,10 +181,10 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, Application, HttpResponse}; /// use actix_web::{http, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .prefix("/app") /// .prefix("/app")
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok()); /// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
@ -190,7 +193,7 @@ impl<S> Application<S> where S: 'static {
/// .finish(); /// .finish();
/// } /// }
/// ``` /// ```
pub fn prefix<P: Into<String>>(mut self, prefix: P) -> Application<S> { pub fn prefix<P: Into<String>>(mut self, prefix: P) -> App<S> {
{ {
let parts = self.parts.as_mut().expect("Use after finish"); let parts = self.parts.as_mut().expect("Use after finish");
let mut prefix = prefix.into(); let mut prefix = prefix.into();
@ -222,17 +225,17 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, Application, HttpResponse}; /// use actix_web::{http, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .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());
/// }); /// });
/// } /// }
/// ``` /// ```
pub fn resource<F>(mut self, path: &str, f: F) -> Application<S> pub fn resource<F>(mut self, path: &str, f: F) -> App<S>
where F: FnOnce(&mut Resource<S>) + 'static where F: FnOnce(&mut Resource<S>) + 'static
{ {
{ {
@ -249,7 +252,7 @@ impl<S> Application<S> where S: 'static {
} }
/// Default resource is used if no matched route could be found. /// Default resource is used if no matched route could be found.
pub fn default_resource<F>(mut self, f: F) -> Application<S> pub fn default_resource<F>(mut self, f: F) -> App<S>
where F: FnOnce(&mut Resource<S>) + 'static where F: FnOnce(&mut Resource<S>) + 'static
{ {
{ {
@ -260,7 +263,7 @@ impl<S> Application<S> where S: 'static {
} }
/// Set default content encoding. `ContentEncoding::Auto` is set by default. /// Set default content encoding. `ContentEncoding::Auto` is set by default.
pub fn default_encoding<F>(mut self, encoding: ContentEncoding) -> Application<S> pub fn default_encoding<F>(mut self, encoding: ContentEncoding) -> App<S>
{ {
{ {
let parts = self.parts.as_mut().expect("Use after finish"); let parts = self.parts.as_mut().expect("Use after finish");
@ -277,7 +280,7 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{Application, HttpRequest, HttpResponse, Result}; /// use actix_web::{App, HttpRequest, HttpResponse, Result};
/// ///
/// fn index(mut req: HttpRequest) -> Result<HttpResponse> { /// fn index(mut req: HttpRequest) -> Result<HttpResponse> {
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?; /// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
@ -286,13 +289,13 @@ impl<S> Application<S> where S: 'static {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .resource("/index.html", |r| r.f(index)) /// .resource("/index.html", |r| r.f(index))
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}") /// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
/// .finish(); /// .finish();
/// } /// }
/// ``` /// ```
pub fn external_resource<T, U>(mut self, name: T, url: U) -> Application<S> pub fn external_resource<T, U>(mut self, name: T, url: U) -> App<S>
where T: AsRef<str>, U: AsRef<str> where T: AsRef<str>, U: AsRef<str>
{ {
{ {
@ -315,10 +318,10 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, Application, HttpRequest, HttpResponse}; /// use actix_web::{http, App, HttpRequest, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .handler("/app", |req: HttpRequest| { /// .handler("/app", |req: HttpRequest| {
/// match *req.method() { /// match *req.method() {
/// http::Method::GET => HttpResponse::Ok(), /// http::Method::GET => HttpResponse::Ok(),
@ -327,7 +330,7 @@ impl<S> Application<S> where S: 'static {
/// }}); /// }});
/// } /// }
/// ``` /// ```
pub fn handler<H: Handler<S>>(mut self, path: &str, handler: H) -> Application<S> pub fn handler<H: Handler<S>>(mut self, path: &str, handler: H) -> App<S>
{ {
{ {
let path = path.trim().trim_right_matches('/').to_owned(); let path = path.trim().trim_right_matches('/').to_owned();
@ -338,7 +341,7 @@ impl<S> Application<S> where S: 'static {
} }
/// Register a middleware /// Register a middleware
pub fn middleware<M: Middleware<S>>(mut self, mw: M) -> Application<S> { pub fn middleware<M: Middleware<S>>(mut self, mw: M) -> App<S> {
self.parts.as_mut().expect("Use after finish") self.parts.as_mut().expect("Use after finish")
.middlewares.push(Box::new(mw)); .middlewares.push(Box::new(mw));
self self
@ -352,10 +355,10 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{Application, HttpResponse, http, fs, middleware}; /// use actix_web::{App, HttpResponse, http, fs, middleware};
/// ///
/// // this function could be located in different module /// // this function could be located in different module
/// fn config(app: Application) -> Application { /// fn config(app: App) -> App {
/// app /// app
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok()); /// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
@ -364,14 +367,14 @@ impl<S> Application<S> where S: 'static {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .middleware(middleware::Logger::default()) /// .middleware(middleware::Logger::default())
/// .configure(config) // <- register resources /// .configure(config) // <- register resources
/// .handler("/static", fs::StaticFiles::new(".", true)); /// .handler("/static", fs::StaticFiles::new(".", true));
/// } /// }
/// ``` /// ```
pub fn configure<F>(self, cfg: F) -> Application<S> pub fn configure<F>(self, cfg: F) -> App<S>
where F: Fn(Application<S>) -> Application<S> where F: Fn(App<S>) -> App<S>
{ {
cfg(self) cfg(self)
} }
@ -410,7 +413,7 @@ impl<S> Application<S> where S: 'static {
/// Convenience method for creating `Box<HttpHandler>` instance. /// Convenience method for creating `Box<HttpHandler>` instance.
/// ///
/// This method is useful if you need to register several application instances /// This method is useful if you need to register multiple application instances
/// with different state. /// with different state.
/// ///
/// ```rust /// ```rust
@ -425,11 +428,11 @@ impl<S> Application<S> where S: 'static {
/// fn main() { /// fn main() {
/// # thread::spawn(|| { /// # thread::spawn(|| {
/// HttpServer::new(|| { vec![ /// HttpServer::new(|| { vec![
/// Application::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()))
/// .boxed(), /// .boxed(),
/// Application::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() ]})
@ -443,7 +446,7 @@ impl<S> Application<S> where S: 'static {
} }
} }
impl<S: 'static> IntoHttpHandler for Application<S> { impl<S: 'static> IntoHttpHandler for App<S> {
type Handler = HttpApplication<S>; type Handler = HttpApplication<S>;
fn into_handler(mut self, settings: ServerSettings) -> HttpApplication<S> { fn into_handler(mut self, settings: ServerSettings) -> HttpApplication<S> {
@ -455,7 +458,7 @@ impl<S: 'static> IntoHttpHandler for Application<S> {
} }
} }
impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> { impl<'a, S: 'static> IntoHttpHandler for &'a mut App<S> {
type Handler = HttpApplication<S>; type Handler = HttpApplication<S>;
fn into_handler(self, settings: ServerSettings) -> HttpApplication<S> { fn into_handler(self, settings: ServerSettings) -> HttpApplication<S> {
@ -468,7 +471,7 @@ impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
} }
#[doc(hidden)] #[doc(hidden)]
impl<S: 'static> Iterator for Application<S> { impl<S: 'static> Iterator for App<S> {
type Item = HttpApplication<S>; type Item = HttpApplication<S>;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
@ -491,7 +494,7 @@ mod tests {
#[test] #[test]
fn test_default_resource() { fn test_default_resource() {
let mut app = Application::new() let mut app = App::new()
.resource("/test", |r| r.f(|_| HttpResponse::Ok())) .resource("/test", |r| r.f(|_| HttpResponse::Ok()))
.finish(); .finish();
@ -503,7 +506,7 @@ mod tests {
let resp = app.run(req); let resp = app.run(req);
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND); assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
let mut app = Application::new() let mut app = App::new()
.default_resource(|r| r.f(|_| HttpResponse::MethodNotAllowed())) .default_resource(|r| r.f(|_| HttpResponse::MethodNotAllowed()))
.finish(); .finish();
let req = TestRequest::with_uri("/blah").finish(); let req = TestRequest::with_uri("/blah").finish();
@ -513,7 +516,7 @@ mod tests {
#[test] #[test]
fn test_unhandled_prefix() { fn test_unhandled_prefix() {
let mut app = Application::new() let mut app = App::new()
.prefix("/test") .prefix("/test")
.resource("/test", |r| r.f(|_| HttpResponse::Ok())) .resource("/test", |r| r.f(|_| HttpResponse::Ok()))
.finish(); .finish();
@ -522,7 +525,7 @@ mod tests {
#[test] #[test]
fn test_state() { fn test_state() {
let mut app = Application::with_state(10) let mut app = App::with_state(10)
.resource("/", |r| r.f(|_| HttpResponse::Ok())) .resource("/", |r| r.f(|_| HttpResponse::Ok()))
.finish(); .finish();
let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone()); let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone());
@ -532,7 +535,7 @@ mod tests {
#[test] #[test]
fn test_prefix() { fn test_prefix() {
let mut app = Application::new() let mut app = App::new()
.prefix("/test") .prefix("/test")
.resource("/blah", |r| r.f(|_| HttpResponse::Ok())) .resource("/blah", |r| r.f(|_| HttpResponse::Ok()))
.finish(); .finish();
@ -555,7 +558,7 @@ mod tests {
#[test] #[test]
fn test_handler() { fn test_handler() {
let mut app = Application::new() let mut app = App::new()
.handler("/test", |_| HttpResponse::Ok()) .handler("/test", |_| HttpResponse::Ok())
.finish(); .finish();
@ -582,7 +585,7 @@ mod tests {
#[test] #[test]
fn test_handler_prefix() { fn test_handler_prefix() {
let mut app = Application::new() let mut app = App::new()
.prefix("/app") .prefix("/app")
.handler("/test", |_| HttpResponse::Ok()) .handler("/test", |_| HttpResponse::Ok())
.finish(); .finish();

View File

@ -19,7 +19,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::{Application, Path, Result, http}; /// use actix_web::{App, Path, Result, http};
/// ///
/// /// 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
@ -29,7 +29,7 @@ use httprequest::HttpRequest;
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::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
/// } /// }
@ -43,7 +43,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::{Application, Path, Result, http}; /// use actix_web::{App, Path, Result, http};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -56,7 +56,7 @@ use httprequest::HttpRequest;
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::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
/// } /// }
@ -109,7 +109,7 @@ impl<T, S> FromRequest<S> for Path<T>
/// # 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::{Application, Query, http}; /// use actix_web::{App, Query, http};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -123,7 +123,7 @@ impl<T, S> FromRequest<S> for Path<T>
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = App::new().resource(
/// "/index.html", /// "/index.html",
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
/// } /// }

View File

@ -363,15 +363,15 @@ impl Responder for Directory {
/// Static files handling /// Static files handling
/// ///
/// `StaticFile` handler must be registered with `Application::handler()` method, /// `StaticFile` handler must be registered with `App::handler()` method,
/// because `StaticFile` handler requires access sub-path information. /// because `StaticFile` handler requires access sub-path information.
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{fs, Application}; /// use actix_web::{fs, App};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .handler("/static", fs::StaticFiles::new(".", true)) /// .handler("/static", fs::StaticFiles::new(".", true))
/// .finish(); /// .finish();
/// } /// }

View File

@ -96,7 +96,7 @@ impl<A, B> Responder for Either<A, B>
} }
} }
/// Convenience trait that convert `Future` object into `Boxed` future /// Convenience trait that converts `Future` object to a `Boxed` future
/// ///
/// For example loading json from request's body is async operation. /// For example loading json from request's body is async operation.
/// ///
@ -106,7 +106,7 @@ impl<A, B> Responder for Either<A, B>
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// use futures::future::Future; /// use futures::future::Future;
/// use actix_web::{ /// use actix_web::{
/// Application, HttpRequest, HttpResponse, HttpMessage, Error, AsyncResponder}; /// App, HttpRequest, HttpResponse, HttpMessage, Error, AsyncResponder};
/// ///
/// #[derive(Deserialize, Debug)] /// #[derive(Deserialize, Debug)]
/// struct MyObj { /// struct MyObj {
@ -384,10 +384,10 @@ impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
/// # 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::{Application, Path, State, http}; /// use actix_web::{App, Path, State, http};
/// ///
/// /// Application state /// /// Application state
/// struct App {msg: &'static str} /// struct MyApp {msg: &'static str}
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -395,12 +395,12 @@ impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
/// } /// }
/// ///
/// /// extract path info using serde /// /// extract path info using serde
/// fn index(state: State<App>, info: Path<Info>) -> String { /// fn index(state: State<MyApp>, info: Path<Info>) -> String {
/// format!("{} {}!", state.msg, info.username) /// format!("{} {}!", state.msg, info.username)
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::with_state(App{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).with2(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with2(index)); // <- use `with` extractor
/// } /// }

View File

@ -38,7 +38,7 @@ use httpresponse::HttpResponse;
/// # HttpResponse::Ok().into() /// # HttpResponse::Ok().into()
/// # } /// # }
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .resource("/test/", |r| r.f(index)) /// .resource("/test/", |r| r.f(index))
/// .default_resource(|r| r.h(NormalizePath::default())) /// .default_resource(|r| r.h(NormalizePath::default()))
/// .finish(); /// .finish();
@ -155,7 +155,7 @@ mod tests {
use super::*; use super::*;
use http::{header, Method}; use http::{header, Method};
use test::TestRequest; use test::TestRequest;
use application::Application; use application::App;
fn index(_req: HttpRequest) -> HttpResponse { fn index(_req: HttpRequest) -> HttpResponse {
HttpResponse::new(StatusCode::OK) HttpResponse::new(StatusCode::OK)
@ -163,7 +163,7 @@ mod tests {
#[test] #[test]
fn test_normalize_path_trailing_slashes() { fn test_normalize_path_trailing_slashes() {
let mut app = Application::new() let mut app = App::new()
.resource("/resource1", |r| r.method(Method::GET).f(index)) .resource("/resource1", |r| r.method(Method::GET).f(index))
.resource("/resource2/", |r| r.method(Method::GET).f(index)) .resource("/resource2/", |r| r.method(Method::GET).f(index))
.default_resource(|r| r.h(NormalizePath::default())) .default_resource(|r| r.h(NormalizePath::default()))
@ -196,7 +196,7 @@ mod tests {
#[test] #[test]
fn test_normalize_path_trailing_slashes_disabled() { fn test_normalize_path_trailing_slashes_disabled() {
let mut app = Application::new() let mut app = App::new()
.resource("/resource1", |r| r.method(Method::GET).f(index)) .resource("/resource1", |r| r.method(Method::GET).f(index))
.resource("/resource2/", |r| r.method(Method::GET).f(index)) .resource("/resource2/", |r| r.method(Method::GET).f(index))
.default_resource(|r| r.h( .default_resource(|r| r.h(
@ -223,7 +223,7 @@ mod tests {
#[test] #[test]
fn test_normalize_path_merge_slashes() { fn test_normalize_path_merge_slashes() {
let mut app = Application::new() let mut app = App::new()
.resource("/resource1", |r| r.method(Method::GET).f(index)) .resource("/resource1", |r| r.method(Method::GET).f(index))
.resource("/resource1/a/b", |r| r.method(Method::GET).f(index)) .resource("/resource1/a/b", |r| r.method(Method::GET).f(index))
.default_resource(|r| r.h(NormalizePath::default())) .default_resource(|r| r.h(NormalizePath::default()))
@ -263,7 +263,7 @@ mod tests {
#[test] #[test]
fn test_normalize_path_merge_and_append_slashes() { fn test_normalize_path_merge_and_append_slashes() {
let mut app = Application::new() let mut app = App::new()
.resource("/resource1", |r| r.method(Method::GET).f(index)) .resource("/resource1", |r| r.method(Method::GET).f(index))
.resource("/resource2/", |r| r.method(Method::GET).f(index)) .resource("/resource2/", |r| r.method(Method::GET).f(index))
.resource("/resource1/a/b", |r| r.method(Method::GET).f(index)) .resource("/resource1/a/b", |r| r.method(Method::GET).f(index))

View File

@ -279,7 +279,7 @@ impl<S> HttpRequest<S> {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::{Application, 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
@ -287,7 +287,7 @@ impl<S> HttpRequest<S> {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .resource("/test/{one}/{two}/{three}", |r| { /// .resource("/test/{one}/{two}/{three}", |r| {
/// r.name("foo"); // <- set resource name, then it could be used in `url_for` /// r.name("foo"); // <- set resource name, then it could be used in `url_for`
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok()); /// r.method(http::Method::GET).f(|_| HttpResponse::Ok());

View File

@ -314,7 +314,7 @@ impl HttpResponseBuilder {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, Application, HttpRequest, HttpResponse}; /// use actix_web::{http, HttpRequest, HttpResponse};
/// ///
/// fn index(req: HttpRequest) -> HttpResponse { /// fn index(req: HttpRequest) -> HttpResponse {
/// HttpResponse::Ok() /// HttpResponse::Ok()

View File

@ -51,7 +51,7 @@ use httpresponse::HttpResponse;
/// # 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::{Application, Json, Result, http}; /// use actix_web::{App, Json, Result, http};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -64,7 +64,7 @@ use httpresponse::HttpResponse;
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = App::new().resource(
/// "/index.html", /// "/index.html",
/// |r| r.method(http::Method::POST).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::POST).with(index)); // <- use `with` extractor
/// } /// }
@ -139,8 +139,7 @@ impl<T, S> FromRequest<S> for Json<T>
/// # extern crate futures; /// # extern crate futures;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// use futures::future::Future; /// use futures::future::Future;
/// use actix_web::{Application, AsyncResponder, /// use actix_web::{AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error};
/// HttpRequest, HttpResponse, HttpMessage, Error};
/// ///
/// #[derive(Deserialize, Debug)] /// #[derive(Deserialize, Debug)]
/// struct MyObj { /// struct MyObj {

View File

@ -1,7 +1,7 @@
//! Actix web is a small, pragmatic, extremely fast, web framework for Rust. //! Actix web is a small, pragmatic, extremely fast, web framework for Rust.
//! //!
//! ```rust //! ```rust
//! use actix_web::{Application, HttpServer, Path}; //! use actix_web::{App, HttpServer, Path};
//! # use std::thread; //! # use std::thread;
//! //!
//! fn index(info: Path<(String, u32)>) -> String { //! fn index(info: Path<(String, u32)>) -> String {
@ -11,7 +11,7 @@
//! fn main() { //! fn main() {
//! # thread::spawn(|| { //! # thread::spawn(|| {
//! HttpServer::new( //! HttpServer::new(
//! || Application::new() //! || App::new()
//! .resource("/{name}/{id}/index.html", |r| r.with(index))) //! .resource("/{name}/{id}/index.html", |r| r.with(index)))
//! .bind("127.0.0.1:8080").unwrap() //! .bind("127.0.0.1:8080").unwrap()
//! .run(); //! .run();
@ -136,7 +136,7 @@ pub use error::{Error, Result, ResponseError};
pub use body::{Body, Binary}; pub use body::{Body, Binary};
pub use json::Json; pub use json::Json;
pub use de::{Path, Query}; pub use de::{Path, Query};
pub use application::Application; pub use application::App;
pub use httpmessage::HttpMessage; pub use httpmessage::HttpMessage;
pub use httprequest::HttpRequest; pub use httprequest::HttpRequest;
pub use httpresponse::HttpResponse; pub use httpresponse::HttpResponse;
@ -147,6 +147,10 @@ pub use server::HttpServer;
#[doc(hidden)] #[doc(hidden)]
pub mod httpcodes; pub mod httpcodes;
#[doc(hidden)]
#[allow(deprecated)]
pub use application::Application;
#[cfg(feature="openssl")] #[cfg(feature="openssl")]
pub(crate) const HAS_OPENSSL: bool = true; pub(crate) const HAS_OPENSSL: bool = true;
#[cfg(not(feature="openssl"))] #[cfg(not(feature="openssl"))]

View File

@ -9,7 +9,7 @@
//! 2. Use any of the builder methods to set fields in the backend. //! 2. Use any of the builder methods to set fields in the backend.
//! 3. Call [finish](struct.Cors.html#method.finish) to retrieve the constructed backend. //! 3. Call [finish](struct.Cors.html#method.finish) to retrieve the constructed backend.
//! //!
//! Cors middleware could be used as parameter for `Application::middleware()` or //! Cors middleware could be used as parameter for `App::middleware()` or
//! `Resource::middleware()` methods. But you have to use `Cors::register()` method to //! `Resource::middleware()` methods. But you have to use `Cors::register()` method to
//! support *preflight* OPTIONS request. //! support *preflight* OPTIONS request.
//! //!
@ -18,7 +18,7 @@
//! //!
//! ```rust //! ```rust
//! # extern crate actix_web; //! # extern crate actix_web;
//! use actix_web::{http, Application, HttpRequest, HttpResponse}; //! use actix_web::{http, App, HttpRequest, HttpResponse};
//! use actix_web::middleware::cors; //! use actix_web::middleware::cors;
//! //!
//! fn index(mut req: HttpRequest) -> &'static str { //! fn index(mut req: HttpRequest) -> &'static str {
@ -26,7 +26,7 @@
//! } //! }
//! //!
//! fn main() { //! fn main() {
//! let app = Application::new() //! let app = App::new()
//! .resource("/index.html", |r| { //! .resource("/index.html", |r| {
//! cors::Cors::build() // <- Construct CORS middleware //! cors::Cors::build() // <- Construct CORS middleware
//! .allowed_origin("https://www.rust-lang.org/") //! .allowed_origin("https://www.rust-lang.org/")

View File

@ -22,7 +22,7 @@
//! //!
//! ``` //! ```
//! # extern crate actix_web; //! # extern crate actix_web;
//! use actix_web::{http, Application, HttpRequest, HttpResponse}; //! use actix_web::{http, App, HttpRequest, HttpResponse};
//! use actix_web::middleware::csrf; //! use actix_web::middleware::csrf;
//! //!
//! fn handle_post(_: HttpRequest) -> &'static str { //! fn handle_post(_: HttpRequest) -> &'static str {
@ -30,7 +30,7 @@
//! } //! }
//! //!
//! fn main() { //! fn main() {
//! let app = Application::new() //! let app = App::new()
//! .middleware( //! .middleware(
//! csrf::CsrfFilter::build() //! csrf::CsrfFilter::build()
//! .allowed_origin("https://www.example.com") //! .allowed_origin("https://www.example.com")

View File

@ -13,10 +13,10 @@ use middleware::{Response, Middleware};
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, middleware, Application, HttpResponse}; /// use actix_web::{http, middleware, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .middleware( /// .middleware(
/// middleware::DefaultHeaders::build() /// middleware::DefaultHeaders::build()
/// .header("X-Version", "0.2") /// .header("X-Version", "0.2")

View File

@ -29,14 +29,14 @@ use middleware::{Middleware, Started, Finished};
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// extern crate env_logger; /// extern crate env_logger;
/// use actix_web::Application; /// use actix_web::App;
/// use actix_web::middleware::Logger; /// use actix_web::middleware::Logger;
/// ///
/// fn main() { /// fn main() {
/// std::env::set_var("RUST_LOG", "actix_web=info"); /// std::env::set_var("RUST_LOG", "actix_web=info");
/// env_logger::init(); /// env_logger::init();
/// ///
/// let app = Application::new() /// let app = App::new()
/// .middleware(Logger::default()) /// .middleware(Logger::default())
/// .middleware(Logger::new("%a %{User-Agent}i")) /// .middleware(Logger::new("%a %{User-Agent}i"))
/// .finish(); /// .finish();

View File

@ -114,11 +114,11 @@ unsafe impl Sync for SessionImplBox {}
/// ```rust /// ```rust
/// # extern crate actix; /// # extern crate actix;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::middleware::{SessionStorage, CookieSessionBackend}; /// use actix_web::App;
/// use actix_web::*; /// use actix_web::middleware::{SessionStorage, CookieSessionBackend};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new().middleware( /// let app = App::new().middleware(
/// SessionStorage::new( // <- create session middleware /// SessionStorage::new( // <- create session middleware
/// CookieSessionBackend::build(&[0; 32]) // <- create cookie session backend /// CookieSessionBackend::build(&[0; 32]) // <- create cookie session backend
/// .secure(false) /// .secure(false)

View File

@ -20,10 +20,10 @@ pub trait Predicate<S> {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{pred, Application, HttpResponse}; /// use actix_web::{pred, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// Application::new() /// App::new()
/// .resource("/index.html", |r| r.route() /// .resource("/index.html", |r| 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()));

View File

@ -24,10 +24,10 @@ use with::WithHandler;
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{Application, HttpResponse, http}; /// use actix_web::{App, HttpResponse, http};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .resource( /// .resource(
/// "/", |r| r.method(http::Method::GET).f(|r| HttpResponse::Ok())) /// "/", |r| r.method(http::Method::GET).f(|r| HttpResponse::Ok()))
/// .finish(); /// .finish();
@ -79,7 +79,7 @@ impl<S: 'static> Resource<S> {
/// use actix_web::*; /// use actix_web::*;
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = App::new()
/// .resource( /// .resource(
/// "/", |r| r.route() /// "/", |r| r.route()
/// .filter(pred::Any(pred::Get()).or(pred::Put())) /// .filter(pred::Any(pred::Get()).or(pred::Put()))
@ -149,7 +149,7 @@ impl<S: 'static> Resource<S> {
/// Register a middleware /// Register a middleware
/// ///
/// This is similar to `Application's` middlewares, but /// This is similar to `App's` middlewares, but
/// middlewares get invoked on resource level. /// middlewares get invoked on resource level.
pub fn middleware<M: Middleware<S>>(&mut self, mw: M) { pub fn middleware<M: Middleware<S>>(&mut self, mw: M) {
Rc::get_mut(&mut self.middlewares).unwrap().push(Box::new(mw)); Rc::get_mut(&mut self.middlewares).unwrap().push(Box::new(mw));

View File

@ -62,7 +62,7 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// # use actix_web::*;
/// # fn main() { /// # fn main() {
/// Application::new() /// App::new()
/// .resource("/path", |r| /// .resource("/path", |r|
/// r.route() /// r.route()
/// .filter(pred::Get()) /// .filter(pred::Get())
@ -109,7 +109,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::{Application, Path, Result, http}; /// use actix_web::{App, Path, Result, http};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -122,7 +122,7 @@ impl<S: 'static> Route<S> {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::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
/// } /// }
@ -141,7 +141,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::{Application, Query, Path, Result, http}; /// use actix_web::{App, Query, Path, Result, http};
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct PParam { /// struct PParam {
@ -159,7 +159,7 @@ impl<S: 'static> Route<S> {
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::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
/// } /// }

View File

@ -38,13 +38,13 @@ pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536;
/// # extern crate actix; /// # extern crate actix;
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix::*; /// use actix::*;
/// use actix_web::{server, Application, HttpResponse}; /// use actix_web::{server, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let sys = actix::System::new("guide"); /// let sys = actix::System::new("guide");
/// ///
/// server::new( /// server::new(
/// || Application::new() /// || App::new()
/// .resource("/", |r| r.f(|_| HttpResponse::Ok()))) /// .resource("/", |r| r.f(|_| HttpResponse::Ok())))
/// .bind("127.0.0.1:59080").unwrap() /// .bind("127.0.0.1:59080").unwrap()
/// .start(); /// .start();

View File

@ -268,7 +268,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
/// let sys = actix::System::new("example"); // <- create Actix system /// let sys = actix::System::new("example"); // <- create Actix system
/// ///
/// HttpServer::new( /// HttpServer::new(
/// || Application::new() /// || App::new()
/// .resource("/", |r| r.h(|_| HttpResponse::Ok()))) /// .resource("/", |r| r.h(|_| HttpResponse::Ok())))
/// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0") /// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
/// .start(); /// .start();
@ -326,7 +326,7 @@ impl<H: IntoHttpHandler> HttpServer<H>
/// ///
/// fn main() { /// fn main() {
/// HttpServer::new( /// HttpServer::new(
/// || Application::new() /// || App::new()
/// .resource("/", |r| r.h(|_| HttpResponse::Ok()))) /// .resource("/", |r| r.h(|_| HttpResponse::Ok())))
/// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0") /// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
/// .run(); /// .run();

View File

@ -23,7 +23,7 @@ use error::Error;
use header::{Header, IntoHeaderValue}; use header::{Header, IntoHeaderValue};
use handler::{Handler, Responder, ReplyItem}; use handler::{Handler, Responder, ReplyItem};
use middleware::Middleware; use middleware::Middleware;
use application::{Application, HttpApplication}; use application::{App, HttpApplication};
use param::Params; use param::Params;
use router::Router; use router::Router;
use payload::Payload; use payload::Payload;
@ -327,12 +327,12 @@ impl<S: 'static> TestServerBuilder<S> {
/// Test application helper for testing request handlers. /// Test application helper for testing request handlers.
pub struct TestApp<S=()> { pub struct TestApp<S=()> {
app: Option<Application<S>>, app: Option<App<S>>,
} }
impl<S: 'static> TestApp<S> { impl<S: 'static> TestApp<S> {
fn new(state: S) -> TestApp<S> { fn new(state: S) -> TestApp<S> {
let app = Application::with_state(state); let app = App::with_state(state);
TestApp{app: Some(app)} TestApp{app: Some(app)}
} }
@ -350,7 +350,7 @@ impl<S: 'static> TestApp<S> {
} }
/// Register resource. This method is similar /// Register resource. This method is similar
/// to `Application::resource()` method. /// to `App::resource()` method.
pub fn resource<F>(&mut self, path: &str, f: F) -> &mut TestApp<S> pub fn resource<F>(&mut self, path: &str, f: F) -> &mut TestApp<S>
where F: FnOnce(&mut Resource<S>) + 'static where F: FnOnce(&mut Resource<S>) + 'static
{ {

View File

@ -37,7 +37,7 @@
//! } //! }
//! # //! #
//! # fn main() { //! # fn main() {
//! # Application::new() //! # App::new()
//! # .resource("/ws/", |r| r.f(ws_index)) // <- register websocket route //! # .resource("/ws/", |r| r.f(ws_index)) // <- register websocket route
//! # .finish(); //! # .finish();
//! # } //! # }

View File

@ -64,7 +64,7 @@ fn test_start() {
thread::spawn(move || { thread::spawn(move || {
let sys = System::new("test"); let sys = System::new("test");
let srv = HttpServer::new( let srv = HttpServer::new(
|| vec![Application::new() || vec![App::new()
.resource( .resource(
"/", |r| r.method(http::Method::GET) "/", |r| r.method(http::Method::GET)
.f(|_|HttpResponse::Ok()))]); .f(|_|HttpResponse::Ok()))]);
@ -109,7 +109,7 @@ fn test_shutdown() {
thread::spawn(move || { thread::spawn(move || {
let sys = System::new("test"); let sys = System::new("test");
let srv = HttpServer::new( let srv = HttpServer::new(
|| vec![Application::new() || vec![App::new()
.resource( .resource(
"/", |r| r.method(http::Method::GET).f(|_| HttpResponse::Ok()))]); "/", |r| r.method(http::Method::GET).f(|_| HttpResponse::Ok()))]);
@ -749,7 +749,7 @@ fn test_h2() {
#[test] #[test]
fn test_application() { fn test_application() {
let mut srv = test::TestServer::with_factory( let mut srv = test::TestServer::with_factory(
|| Application::new().resource("/", |r| r.f(|_| HttpResponse::Ok()))); || App::new().resource("/", |r| r.f(|_| HttpResponse::Ok())));
let request = srv.get().finish().unwrap(); let request = srv.get().finish().unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();