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 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::middleware::{self, RequestSession};
use futures::future::{FutureResult, result};
@ -100,7 +100,7 @@ fn main() {
let sys = actix::System::new("basic-example");
let addr = HttpServer::new(
|| Application::new()
|| App::new()
// enable logger
.middleware(middleware::Logger::default())
// cookie session middleware

View File

@ -18,7 +18,7 @@ extern crate env_logger;
use actix::prelude::*;
use actix_web::{http, middleware,
Application, HttpServer, HttpRequest, HttpResponse, Error, AsyncResponder};
App, HttpServer, HttpRequest, HttpResponse, Error, AsyncResponder};
use diesel::prelude::*;
use futures::future::Future;
@ -63,7 +63,7 @@ fn main() {
// Start http server
let _addr = HttpServer::new(move || {
Application::with_state(State{db: addr.clone()})
App::with_state(State{db: addr.clone()})
// enable logger
.middleware(middleware::Logger::default())
.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 env_logger;
use actix_web::{Application, HttpRequest, server, middleware};
use actix_web::{App, HttpRequest, server, middleware};
fn index(_req: HttpRequest) -> &'static str {
@ -15,7 +15,7 @@ fn main() {
let sys = actix::System::new("ws-example");
let _addr = server::new(
|| Application::new()
|| App::new()
// enable logger
.middleware(middleware::Logger::default())
.resource("/index.html", |r| r.f(|_| "Hello world!"))

View File

@ -5,7 +5,7 @@ extern crate env_logger;
use futures::{Future, Stream};
use actix_web::{client, server, middleware,
Application, AsyncResponder, Body,
App, AsyncResponder, Body,
HttpRequest, HttpResponse, HttpMessage, Error};
/// 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 _addr = server::new(
|| Application::new()
|| App::new()
.middleware(middleware::Logger::default())
.resource("/streaming", |r| r.f(streaming))
.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 json;
use actix_web::{middleware, http, error, server,
Application, AsyncResponder,
HttpRequest, HttpResponse, HttpMessage, Error, Json};
use actix_web::{
middleware, http, error, server,
App, AsyncResponder, HttpRequest, HttpResponse, HttpMessage, Error, Json};
use bytes::BytesMut;
use futures::{Future, Stream};
@ -90,7 +90,7 @@ fn main() {
let sys = actix::System::new("json-example");
let _ = server::new(|| {
Application::new()
App::new()
// enable logger
.middleware(middleware::Logger::default())
.resource("/extractor/{name}/{number}/",

View File

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

View File

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

View File

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

View File

@ -12,8 +12,7 @@ extern crate rusqlite;
use actix::prelude::*;
use actix_web::{
middleware, http, server,
Application, AsyncResponder, HttpRequest, HttpResponse, Error};
middleware, http, server, App, AsyncResponder, HttpRequest, HttpResponse, Error};
use futures::future::Future;
use r2d2_sqlite::SqliteConnectionManager;
@ -55,7 +54,7 @@ fn main() {
// Start http server
let _ = server::new(move || {
Application::with_state(State{db: addr.clone()})
App::with_state(State{db: addr.clone()})
// enable logger
.middleware(middleware::Logger::default())
.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_web::{
http, server, ws, middleware, Application, HttpRequest, HttpResponse};
http, server, ws, middleware, App, HttpRequest, HttpResponse};
/// Application state
struct AppState {
@ -59,7 +59,7 @@ fn main() {
let sys = actix::System::new("ws-example");
let _ = server::new(
|| Application::with_state(AppState{counter: Cell::new(0)})
|| App::with_state(AppState{counter: Cell::new(0)})
// enable logger
.middleware(middleware::Logger::default())
// websocket route

View File

@ -5,9 +5,7 @@ extern crate env_logger;
extern crate tera;
use actix_web::{
http, error, middleware, server,
Application, HttpRequest, HttpResponse, Error,
};
http, error, middleware, server, App, HttpRequest, HttpResponse, Error};
struct State {
@ -38,7 +36,7 @@ fn main() {
let _ = server::new(|| {
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
Application::with_state(State{template: tera})
App::with_state(State{template: tera})
// enable logger
.middleware(middleware::Logger::default())
.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 actix_web::{
http, middleware, server,
Application, HttpRequest, HttpResponse, Error};
http, middleware, server, App, HttpRequest, HttpResponse, Error};
/// simple handle
@ -31,7 +30,7 @@ fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap();
let _ = server::new(
|| Application::new()
|| App::new()
// enable logger
.middleware(middleware::Logger::default())
// register simple handler, handle all methods

View File

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

View File

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

View File

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

View File

@ -10,9 +10,7 @@ extern crate env_logger;
use actix::prelude::*;
use actix_web::{
http, middleware, server, fs, ws,
Application, HttpRequest, HttpResponse, Error,
};
http, middleware, server, fs, ws, App, HttpRequest, HttpResponse, Error};
/// do websocket handshake and start `MyWebSocket` actor
fn ws_index(r: HttpRequest) -> Result<HttpResponse, Error> {
@ -51,7 +49,7 @@ fn main() {
let sys = actix::System::new("ws-example");
server::new(
|| Application::new()
|| App::new()
// enable logger
.middleware(middleware::Logger::default())
// 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 actix_web;
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};
struct Headers; // <- Our middleware
@ -51,7 +51,7 @@ impl<S> Middleware<S> for Headers {
}
fn main() {
Application::new()
App::new()
.middleware(Headers) // <- Register middleware, this method can be called multiple times
.resource("/", |r| r.f(|_| HttpResponse::Ok()));
}
@ -79,14 +79,14 @@ Default `Logger` can be created with `default` method, it uses the default forma
```rust
# extern crate actix_web;
extern crate env_logger;
use actix_web::Application;
use actix_web::App;
use actix_web::middleware::Logger;
fn main() {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
Application::new()
App::new()
.middleware(Logger::default())
.middleware(Logger::new("%a %{User-Agent}i"))
.finish();
@ -135,10 +135,10 @@ the specified header.
```rust
# extern crate actix_web;
use actix_web::{http, middleware, Application, HttpResponse};
use actix_web::{http, middleware, App, HttpResponse};
fn main() {
let app = Application::new()
let app = App::new()
.middleware(
middleware::DefaultHeaders::build()
.header("X-Version", "0.2")
@ -198,7 +198,7 @@ fn index(mut req: HttpRequest) -> Result<&'static str> {
fn main() {
# let sys = actix::System::new("basic-example");
HttpServer::new(
|| Application::new()
|| App::new()
.middleware(SessionStorage::new( // <- create session middleware
CookieSessionBackend::build(&[0; 32]) // <- create cookie session backend
.secure(false)

View File

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

View File

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

View File

@ -87,7 +87,7 @@ fn main() {
// Start http server
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))})
.bind("127.0.0.1:8080").unwrap()
.start().unwrap();

View File

@ -48,7 +48,7 @@ request handler with the application's `resource` on a particular *HTTP method*
# "Hello world!"
# }
# fn main() {
Application::new()
App::new()
.resource("/", |r| r.f(index));
# }
```
@ -58,7 +58,7 @@ connections. The server accepts a function that should return an `HttpHandler` i
```rust,ignore
HttpServer::new(
|| Application::new()
|| App::new()
.resource("/", |r| r.f(index)))
.bind("127.0.0.1:8088")?
.run();
@ -72,7 +72,7 @@ Here is full source of main.rs file:
```rust
# use std::thread;
extern crate actix_web;
use actix_web::{Application, HttpRequest, HttpResponse, HttpServer};
use actix_web::{App, HttpRequest, HttpResponse, HttpServer};
fn index(req: HttpRequest) -> &'static str {
"Hello world!"
@ -84,7 +84,7 @@ fn main() {
# // call.
# thread::spawn(|| {
HttpServer::new(
|| Application::new()
|| App::new()
.resource("/", |r| r.f(index)))
.bind("127.0.0.1:8088").expect("Can not bind to 127.0.0.1:8088")
.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,
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 also stores application specific state that is shared across all handlers
within same application.
@ -24,7 +24,7 @@ but path `/application` would not match.
# "Hello world!"
# }
# fn main() {
let app = Application::new()
let app = App::new()
.prefix("/app")
.resource("/index.html", |r| r.method(Method::GET).f(index))
.finish()
@ -43,17 +43,17 @@ Multiple applications can be served with one server:
# extern crate tokio_core;
# use tokio_core::net::TcpStream;
# use std::net::SocketAddr;
use actix_web::{Application, HttpResponse, HttpServer};
use actix_web::{App, HttpResponse, HttpServer};
fn main() {
HttpServer::new(|| vec![
Application::new()
App::new()
.prefix("/app1")
.resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new()
App::new()
.prefix("/app2")
.resource("/", |r| r.f(|r| HttpResponse::Ok())),
Application::new()
App::new()
.resource("/", |r| r.f(|r| HttpResponse::Ok())),
]);
}
@ -81,7 +81,7 @@ in the state:
# extern crate actix_web;
#
use std::cell::Cell;
use actix_web::{Application, HttpRequest, http};
use actix_web::{App, HttpRequest, http};
// This struct represents state
struct AppState {
@ -96,7 +96,7 @@ fn index(req: HttpRequest<AppState>) -> String {
}
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))
.finish();
}

View File

@ -13,13 +13,13 @@ within a properly configured actix system:
# extern crate actix;
# extern crate actix_web;
use actix::*;
use actix_web::{server, Application, HttpResponse};
use actix_web::{server, App, HttpResponse};
fn main() {
let sys = actix::System::new("guide");
server::new(
|| Application::new()
|| App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.bind("127.0.0.1:59080").unwrap()
.start();
@ -49,7 +49,7 @@ address of the started http server. Actix http server accepts several messages:
use std::thread;
use std::sync::mpsc;
use actix::*;
use actix_web::{server, Application, HttpResponse, HttpServer};
use actix_web::{server, App, HttpResponse, HttpServer};
fn main() {
let (tx, rx) = mpsc::channel();
@ -57,7 +57,7 @@ fn main() {
thread::spawn(move || {
let sys = actix::System::new("http-server");
let addr = server::new(
|| Application::new()
|| App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.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
@ -81,11 +81,11 @@ can be overridden with the `HttpServer::threads()` method.
```rust
# extern crate actix_web;
# extern crate tokio_core;
use actix_web::{Application, HttpServer, HttpResponse};
use actix_web::{App, HttpServer, HttpResponse};
fn main() {
HttpServer::new(
|| Application::new()
|| App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.threads(4); // <- Start 4 workers
}
@ -116,7 +116,7 @@ fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(
|| Application::new()
|| App::new()
.resource("/index.html", |r| r.f(index)))
.bind("127.0.0.1:8080").unwrap()
.serve_ssl(builder).unwrap();
@ -143,21 +143,21 @@ connection behavior is defined by server settings.
```rust
# extern crate actix_web;
# extern crate tokio_core;
use actix_web::{server, Application, HttpResponse};
use actix_web::{server, App, HttpResponse};
fn main() {
server::new(||
Application::new()
App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(75); // <- Set keep-alive to 75 seconds
server::new(||
Application::new()
App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.keep_alive(server::KeepAlive::Tcp(75)); // <- Use `SO_KEEPALIVE` socket option.
server::new(||
Application::new()
App::new()
.resource("/", |r| r.f(|_| HttpResponse::Ok())))
.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
# extern crate actix_web;
use actix_web::{Application, HttpRequest, HttpResponse, dev::Handler};
use actix_web::{App, HttpRequest, HttpResponse, dev::Handler};
struct MyHandler(usize);
@ -75,7 +75,7 @@ number of requests processed per thread. A proper implementation would use `Arc`
```rust
# extern crate actix;
# 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::atomic::{AtomicUsize, Ordering};
@ -99,7 +99,7 @@ fn main() {
server::new(
move || {
let cloned = inc.clone();
Application::new()
App::new()
.resource("/", move |r| r.h(MyHandler(cloned)))
})
.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_json;
#[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)]
struct MyObj {
@ -158,7 +158,7 @@ fn main() {
let sys = actix::System::new("example");
HttpServer::new(
|| Application::new()
|| App::new()
.resource("/", |r| r.method(http::Method::GET).f(index)))
.bind("127.0.0.1:8088").unwrap()
.start();
@ -198,7 +198,7 @@ fn index2(req: HttpRequest) -> Box<Future<Item=&'static str, Error=Error>> {
}
fn main() {
Application::new()
App::new()
.resource("/async", |r| r.route().a(index))
.resource("/", |r| r.route().a(index2))
.finish();
@ -224,7 +224,7 @@ fn index(req: HttpRequest) -> HttpResponse {
}
fn main() {
Application::new()
App::new()
.resource("/async", |r| r.f(index))
.finish();
}
@ -257,7 +257,7 @@ fn index(req: HttpRequest) -> Result<Box<Future<Item=HttpResponse, Error=Error>>
#
# fn is_error() -> bool { true }
# fn main() {
# Application::new()
# App::new()
# .resource("/async", |r| r.route().f(index))
# .finish();
# }
@ -294,7 +294,7 @@ fn index(req: HttpRequest) -> RegisterResult {
}
# fn is_a_variant() -> bool { true }
# fn main() {
# Application::new()
# App::new()
# .resource("/register", |r| r.f(index))
# .finish();
# }

View File

@ -27,7 +27,7 @@ fn index(req: HttpRequest) -> io::Result<fs::NamedFile> {
}
#
# fn main() {
# Application::new()
# App::new()
# .resource(r"/a/index.html", |r| r.f(index))
# .finish();
# }
@ -58,7 +58,7 @@ fn index(req: HttpRequest) -> Result<&'static str, MyError> {
}
#
# fn main() {
# Application::new()
# App::new()
# .resource(r"/a/index.html", |r| r.f(index))
# .finish();
# }
@ -70,7 +70,7 @@ to return different responses for different types of errors.
```rust
# extern crate actix_web;
#[macro_use] extern crate failure;
use actix_web::{Application, HttpRequest, HttpResponse, http, error};
use actix_web::{App, HttpRequest, HttpResponse, http, error};
#[derive(Fail, Debug)]
enum MyError {
@ -100,7 +100,7 @@ fn index(req: HttpRequest) -> Result<&'static str, MyError> {
}
#
# fn main() {
# Application::new()
# App::new()
# .resource(r"/a/index.html", |r| r.f(index))
# .finish();
# }
@ -127,7 +127,7 @@ fn index(req: HttpRequest) -> Result<&'static str> {
Ok(result.map_err(|e| error::ErrorBadRequest(e))?)
}
# fn main() {
# Application::new()
# App::new()
# .resource(r"/a/index.html", |r| r.f(index))
# .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
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*
and a resource configuration function.
```rust
# 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 {
# unimplemented!()
# }
#
fn main() {
Application::new()
App::new()
.resource("/prefix", |r| r.f(index))
.resource("/user/{name}",
|r| r.method(Method::GET).f(|req| HttpResponse::Ok()))
@ -63,7 +63,7 @@ any number of *predicates* but only one handler.
# use actix_web::*;
fn main() {
Application::new()
App::new()
.resource("/path", |resource|
resource.route()
.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,
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 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.
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() {
Application::new()
App::new()
.resource(r"/a/{v1}/{v2}/", |r| r.f(index))
.finish();
}
@ -304,7 +304,7 @@ safe to interpolate within, or use as a suffix of, a path without additional che
```rust
# extern crate actix_web;
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> {
let path: PathBuf = req.match_info().query("tail")?;
@ -312,7 +312,7 @@ fn index(req: HttpRequest) -> Result<String> {
}
fn main() {
Application::new()
App::new()
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
.finish();
}
@ -333,7 +333,7 @@ has to implement *serde's *`Deserialize` trait.
# extern crate actix_web;
# extern crate futures;
#[macro_use] extern crate serde_derive;
use actix_web::{Application, Path, Result, http::Method};
use actix_web::{App, Path, Result, http::Method};
#[derive(Deserialize)]
struct Info {
@ -346,7 +346,7 @@ fn index(info: Path<Info>) -> Result<String> {
}
fn main() {
let app = Application::new()
let app = App::new()
.resource("/{username}/index.html", // <- define path parameters
|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
# 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 {
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() {
let app = Application::new()
let app = App::new()
.resource("/test/{a}/{b}/{c}", |r| {
r.name("foo"); // <- set resource name, then it could be used in `url_for`
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
# 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> {
let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
@ -403,7 +403,7 @@ fn index(mut req: HttpRequest) -> Result<HttpResponse, Error> {
}
fn main() {
let app = Application::new()
let app = App::new()
.resource("/index.html", |r| r.f(index))
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
.finish();
@ -440,7 +440,7 @@ use actix_web::http::NormalizePath;
# HttpResponse::Ok().into()
# }
fn main() {
let app = Application::new()
let app = App::new()
.resource("/resource/", |r| r.f(index))
.default_resource(|r| r.h(NormalizePath::default()))
.finish();
@ -459,13 +459,13 @@ It is possible to register path normalization only for *GET* requests only:
```rust
# extern crate actix_web;
# #[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 {
# "test"
# }
fn main() {
let app = Application::new()
let app = App::new()
.resource("/resource/", |r| r.f(index))
.default_resource(|r| r.method(Method::GET).h(NormalizePath::default()))
.finish();
@ -474,7 +474,7 @@ fn main() {
## 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
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
@ -491,7 +491,7 @@ fn show_users(req: HttpRequest) -> HttpResponse {
}
fn main() {
Application::new()
App::new()
.prefix("/users")
.resource("/show", |r| r.f(show_users))
.finish();
@ -517,7 +517,7 @@ Here is a simple predicate that check that a request contains a specific *header
```rust
# extern crate actix_web;
# use actix_web::*;
use actix_web::{http, pred::Predicate, Application, HttpRequest};
use actix_web::{http, pred::Predicate, App, HttpRequest};
struct ContentTypeHeader;
@ -529,7 +529,7 @@ impl<S: 'static> Predicate<S> for ContentTypeHeader {
}
fn main() {
Application::new()
App::new()
.resource("/index.html", |r|
r.route()
.filter(ContentTypeHeader)
@ -553,10 +553,10 @@ except "GET":
# extern crate actix_web;
# extern crate http;
# use actix_web::*;
use actix_web::{pred, Application, HttpResponse};
use actix_web::{pred, App, HttpResponse};
fn main() {
Application::new()
App::new()
.resource("/index.html", |r|
r.route()
.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
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
with `Application::resource()` method.
with `App::resource()` method.
```rust
# extern crate actix_web;
use actix_web::{Application, HttpResponse, http::Method, pred};
use actix_web::{App, HttpResponse, http::Method, pred};
fn main() {
Application::new()
App::new()
.default_resource(|r| {
r.method(Method::GET).f(|req| HttpResponse::NotFound());
r.route().filter(pred::Not(pred::Get()))

View File

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

View File

@ -75,15 +75,15 @@ function same way as you would for real http server configuration.
```rust
# 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 {
HttpResponse::Ok().into()
}
/// This function get called by http server.
fn create_app() -> Application {
Application::new()
fn create_app() -> App {
App::new()
.resource("/test", |r| r.h(index))
}

View File

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

View File

@ -13,6 +13,9 @@ use pipeline::{Pipeline, PipelineHandler};
use middleware::Middleware;
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
pub struct HttpApplication<S=()> {
state: Rc<S>,
@ -108,17 +111,17 @@ struct ApplicationParts<S> {
middlewares: Vec<Box<Middleware<S>>>,
}
/// Structure that follows the builder pattern for building `Application` structs.
pub struct Application<S=()> {
/// Structure that follows the builder pattern for building application instances.
pub struct App<S=()> {
parts: Option<ApplicationParts<S>>,
}
impl Application<()> {
impl App<()> {
/// Create application with empty state. Application can
/// be configured with builder-like pattern.
pub fn new() -> Application<()> {
Application {
pub fn new() -> App<()> {
App {
parts: Some(ApplicationParts {
state: (),
prefix: "/".to_owned(),
@ -134,21 +137,21 @@ impl Application<()> {
}
}
impl Default for Application<()> {
impl Default for App<()> {
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
/// configured with builder-like pattern.
///
/// State is shared with all resources within same application and could be
/// accessed with `HttpRequest::state()` method.
pub fn with_state(state: S) -> Application<S> {
Application {
pub fn with_state(state: S) -> App<S> {
App {
parts: Some(ApplicationParts {
state,
prefix: "/".to_owned(),
@ -178,10 +181,10 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{http, Application, HttpResponse};
/// use actix_web::{http, App, HttpResponse};
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .prefix("/app")
/// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
@ -190,7 +193,7 @@ impl<S> Application<S> where S: 'static {
/// .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 mut prefix = prefix.into();
@ -222,17 +225,17 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{http, Application, HttpResponse};
/// use actix_web::{http, App, HttpResponse};
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// 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
{
{
@ -249,7 +252,7 @@ impl<S> Application<S> where S: 'static {
}
/// 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
{
{
@ -260,7 +263,7 @@ impl<S> Application<S> where S: 'static {
}
/// 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");
@ -277,7 +280,7 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # 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> {
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
@ -286,13 +289,13 @@ impl<S> Application<S> where S: 'static {
/// }
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .resource("/index.html", |r| r.f(index))
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
/// .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>
{
{
@ -315,10 +318,10 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{http, Application, HttpRequest, HttpResponse};
/// use actix_web::{http, App, HttpRequest, HttpResponse};
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .handler("/app", |req: HttpRequest| {
/// match *req.method() {
/// 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();
@ -338,7 +341,7 @@ impl<S> Application<S> where S: 'static {
}
/// 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")
.middlewares.push(Box::new(mw));
self
@ -352,10 +355,10 @@ impl<S> Application<S> where S: 'static {
///
/// ```rust
/// # 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
/// fn config(app: Application) -> Application {
/// fn config(app: App) -> App {
/// app
/// .resource("/test", |r| {
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
@ -364,14 +367,14 @@ impl<S> Application<S> where S: 'static {
/// }
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .middleware(middleware::Logger::default())
/// .configure(config) // <- register resources
/// .handler("/static", fs::StaticFiles::new(".", true));
/// }
/// ```
pub fn configure<F>(self, cfg: F) -> Application<S>
where F: Fn(Application<S>) -> Application<S>
pub fn configure<F>(self, cfg: F) -> App<S>
where F: Fn(App<S>) -> App<S>
{
cfg(self)
}
@ -410,7 +413,7 @@ impl<S> Application<S> where S: 'static {
/// 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.
///
/// ```rust
@ -425,11 +428,11 @@ impl<S> Application<S> where S: 'static {
/// fn main() {
/// # thread::spawn(|| {
/// HttpServer::new(|| { vec![
/// Application::with_state(State1)
/// App::with_state(State1)
/// .prefix("/app1")
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
/// .boxed(),
/// Application::with_state(State2)
/// App::with_state(State2)
/// .prefix("/app2")
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
/// .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>;
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>;
fn into_handler(self, settings: ServerSettings) -> HttpApplication<S> {
@ -468,7 +471,7 @@ impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
}
#[doc(hidden)]
impl<S: 'static> Iterator for Application<S> {
impl<S: 'static> Iterator for App<S> {
type Item = HttpApplication<S>;
fn next(&mut self) -> Option<Self::Item> {
@ -491,7 +494,7 @@ mod tests {
#[test]
fn test_default_resource() {
let mut app = Application::new()
let mut app = App::new()
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
.finish();
@ -503,7 +506,7 @@ mod tests {
let resp = app.run(req);
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()))
.finish();
let req = TestRequest::with_uri("/blah").finish();
@ -513,7 +516,7 @@ mod tests {
#[test]
fn test_unhandled_prefix() {
let mut app = Application::new()
let mut app = App::new()
.prefix("/test")
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
.finish();
@ -522,7 +525,7 @@ mod tests {
#[test]
fn test_state() {
let mut app = Application::with_state(10)
let mut app = App::with_state(10)
.resource("/", |r| r.f(|_| HttpResponse::Ok()))
.finish();
let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone());
@ -532,7 +535,7 @@ mod tests {
#[test]
fn test_prefix() {
let mut app = Application::new()
let mut app = App::new()
.prefix("/test")
.resource("/blah", |r| r.f(|_| HttpResponse::Ok()))
.finish();
@ -555,7 +558,7 @@ mod tests {
#[test]
fn test_handler() {
let mut app = Application::new()
let mut app = App::new()
.handler("/test", |_| HttpResponse::Ok())
.finish();
@ -582,7 +585,7 @@ mod tests {
#[test]
fn test_handler_prefix() {
let mut app = Application::new()
let mut app = App::new()
.prefix("/app")
.handler("/test", |_| HttpResponse::Ok())
.finish();

View File

@ -19,7 +19,7 @@ use httprequest::HttpRequest;
/// # extern crate actix_web;
/// # extern crate futures;
/// #[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
/// /// {username} - deserializes to a String
@ -29,7 +29,7 @@ use httprequest::HttpRequest;
/// }
///
/// fn main() {
/// let app = Application::new().resource(
/// let app = App::new().resource(
/// "/{username}/{count}/?index.html", // <- define path parameters
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
/// }
@ -43,7 +43,7 @@ use httprequest::HttpRequest;
/// # extern crate actix_web;
/// # extern crate futures;
/// #[macro_use] extern crate serde_derive;
/// use actix_web::{Application, Path, Result, http};
/// use actix_web::{App, Path, Result, http};
///
/// #[derive(Deserialize)]
/// struct Info {
@ -56,7 +56,7 @@ use httprequest::HttpRequest;
/// }
///
/// fn main() {
/// let app = Application::new().resource(
/// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters
/// |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 futures;
/// #[macro_use] extern crate serde_derive;
/// use actix_web::{Application, Query, http};
/// use actix_web::{App, Query, http};
///
/// #[derive(Deserialize)]
/// struct Info {
@ -123,7 +123,7 @@ impl<T, S> FromRequest<S> for Path<T>
/// }
///
/// fn main() {
/// let app = Application::new().resource(
/// let app = App::new().resource(
/// "/index.html",
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
/// }

View File

@ -363,15 +363,15 @@ impl Responder for Directory {
/// 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.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{fs, Application};
/// use actix_web::{fs, App};
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .handler("/static", fs::StaticFiles::new(".", true))
/// .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.
///
@ -106,7 +106,7 @@ impl<A, B> Responder for Either<A, B>
/// # #[macro_use] extern crate serde_derive;
/// use futures::future::Future;
/// use actix_web::{
/// Application, HttpRequest, HttpResponse, HttpMessage, Error, AsyncResponder};
/// App, HttpRequest, HttpResponse, HttpMessage, Error, AsyncResponder};
///
/// #[derive(Deserialize, Debug)]
/// 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 futures;
/// #[macro_use] extern crate serde_derive;
/// use actix_web::{Application, Path, State, http};
/// use actix_web::{App, Path, State, http};
///
/// /// Application state
/// struct App {msg: &'static str}
/// struct MyApp {msg: &'static str}
///
/// #[derive(Deserialize)]
/// 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
/// fn index(state: State<App>, info: Path<Info>) -> String {
/// fn index(state: State<MyApp>, info: Path<Info>) -> String {
/// format!("{} {}!", state.msg, info.username)
/// }
///
/// 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
/// |r| r.method(http::Method::GET).with2(index)); // <- use `with` extractor
/// }

View File

@ -38,7 +38,7 @@ use httpresponse::HttpResponse;
/// # HttpResponse::Ok().into()
/// # }
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .resource("/test/", |r| r.f(index))
/// .default_resource(|r| r.h(NormalizePath::default()))
/// .finish();
@ -155,7 +155,7 @@ mod tests {
use super::*;
use http::{header, Method};
use test::TestRequest;
use application::Application;
use application::App;
fn index(_req: HttpRequest) -> HttpResponse {
HttpResponse::new(StatusCode::OK)
@ -163,7 +163,7 @@ mod tests {
#[test]
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("/resource2/", |r| r.method(Method::GET).f(index))
.default_resource(|r| r.h(NormalizePath::default()))
@ -196,7 +196,7 @@ mod tests {
#[test]
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("/resource2/", |r| r.method(Method::GET).f(index))
.default_resource(|r| r.h(
@ -223,7 +223,7 @@ mod tests {
#[test]
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/a/b", |r| r.method(Method::GET).f(index))
.default_resource(|r| r.h(NormalizePath::default()))
@ -263,7 +263,7 @@ mod tests {
#[test]
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("/resource2/", |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
/// # extern crate actix_web;
/// # use actix_web::{Application, HttpRequest, HttpResponse, http};
/// # use actix_web::{App, HttpRequest, HttpResponse, http};
/// #
/// fn index(req: HttpRequest) -> HttpResponse {
/// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
@ -287,7 +287,7 @@ impl<S> HttpRequest<S> {
/// }
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .resource("/test/{one}/{two}/{three}", |r| {
/// r.name("foo"); // <- set resource name, then it could be used in `url_for`
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());

View File

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

View File

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

View File

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

View File

@ -9,7 +9,7 @@
//! 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.
//!
//! 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
//! support *preflight* OPTIONS request.
//!
@ -18,7 +18,7 @@
//!
//! ```rust
//! # extern crate actix_web;
//! use actix_web::{http, Application, HttpRequest, HttpResponse};
//! use actix_web::{http, App, HttpRequest, HttpResponse};
//! use actix_web::middleware::cors;
//!
//! fn index(mut req: HttpRequest) -> &'static str {
@ -26,7 +26,7 @@
//! }
//!
//! fn main() {
//! let app = Application::new()
//! let app = App::new()
//! .resource("/index.html", |r| {
//! cors::Cors::build() // <- Construct CORS middleware
//! .allowed_origin("https://www.rust-lang.org/")

View File

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

View File

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

View File

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

View File

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

View File

@ -20,10 +20,10 @@ pub trait Predicate<S> {
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{pred, Application, HttpResponse};
/// use actix_web::{pred, App, HttpResponse};
///
/// fn main() {
/// Application::new()
/// App::new()
/// .resource("/index.html", |r| r.route()
/// .filter(pred::Any(pred::Get()).or(pred::Post()))
/// .f(|r| HttpResponse::MethodNotAllowed()));

View File

@ -24,10 +24,10 @@ use with::WithHandler;
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{Application, HttpResponse, http};
/// use actix_web::{App, HttpResponse, http};
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .resource(
/// "/", |r| r.method(http::Method::GET).f(|r| HttpResponse::Ok()))
/// .finish();
@ -79,7 +79,7 @@ impl<S: 'static> Resource<S> {
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::new()
/// let app = App::new()
/// .resource(
/// "/", |r| r.route()
/// .filter(pred::Any(pred::Get()).or(pred::Put()))
@ -149,7 +149,7 @@ impl<S: 'static> Resource<S> {
/// 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.
pub fn middleware<M: Middleware<S>>(&mut self, mw: M) {
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;
/// # use actix_web::*;
/// # fn main() {
/// Application::new()
/// App::new()
/// .resource("/path", |r|
/// r.route()
/// .filter(pred::Get())
@ -109,7 +109,7 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web;
/// # extern crate futures;
/// #[macro_use] extern crate serde_derive;
/// use actix_web::{Application, Path, Result, http};
/// use actix_web::{App, Path, Result, http};
///
/// #[derive(Deserialize)]
/// struct Info {
@ -122,7 +122,7 @@ impl<S: 'static> Route<S> {
/// }
///
/// fn main() {
/// let app = Application::new().resource(
/// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters
/// |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 futures;
/// #[macro_use] extern crate serde_derive;
/// use actix_web::{Application, Query, Path, Result, http};
/// use actix_web::{App, Query, Path, Result, http};
///
/// #[derive(Deserialize)]
/// struct PParam {
@ -159,7 +159,7 @@ impl<S: 'static> Route<S> {
/// }
///
/// fn main() {
/// let app = Application::new().resource(
/// let app = App::new().resource(
/// "/{username}/index.html", // <- define path parameters
/// |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_web;
/// use actix::*;
/// use actix_web::{server, Application, HttpResponse};
/// use actix_web::{server, App, HttpResponse};
///
/// fn main() {
/// let sys = actix::System::new("guide");
///
/// server::new(
/// || Application::new()
/// || App::new()
/// .resource("/", |r| r.f(|_| HttpResponse::Ok())))
/// .bind("127.0.0.1:59080").unwrap()
/// .start();

View File

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

View File

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

View File

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

View File

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