mirror of
https://github.com/fafhrd91/actix-web
synced 2024-11-24 00:21:08 +01:00
simplify application creation
This commit is contained in:
parent
87c7441f7d
commit
c63f058647
@ -3,7 +3,6 @@
|
|||||||
Actix web is a small, fast, down-to-earth, open source rust web framework.
|
Actix web is a small, fast, down-to-earth, open source rust web framework.
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
extern crate actix_web;
|
|
||||||
use actix_web::*;
|
use actix_web::*;
|
||||||
|
|
||||||
fn index(req: HttpRequest) -> String {
|
fn index(req: HttpRequest) -> String {
|
||||||
@ -12,7 +11,7 @@ fn index(req: HttpRequest) -> String {
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/{name}", |r| r.method(Method::GET).f(index)))
|
.resource("/{name}", |r| r.method(Method::GET).f(index)))
|
||||||
.serve::<_, ()>("127.0.0.1:8080");
|
.serve::<_, ()>("127.0.0.1:8080");
|
||||||
}
|
}
|
||||||
|
@ -57,7 +57,7 @@ fn main() {
|
|||||||
let sys = actix::System::new("ws-example");
|
let sys = actix::System::new("ws-example");
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
// enable logger
|
// enable logger
|
||||||
.middleware(middlewares::Logger::default())
|
.middleware(middlewares::Logger::default())
|
||||||
// cookie session middleware
|
// cookie session middleware
|
||||||
|
@ -60,13 +60,13 @@ fn main() {
|
|||||||
let sys = actix::System::new("ws-example");
|
let sys = actix::System::new("ws-example");
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::build("/", AppState{counter: Cell::new(0)})
|
Application::with_state("/", AppState{counter: Cell::new(0)})
|
||||||
// enable logger
|
// enable logger
|
||||||
.middleware(middlewares::Logger::default())
|
.middleware(middlewares::Logger::default())
|
||||||
// websocket route
|
// websocket route
|
||||||
.resource(
|
.resource(
|
||||||
"/ws/", |r| r.method(Method::GET)
|
"/ws/", |r|
|
||||||
.f(|req| ws::start(req, MyWebSocket{counter: 0})))
|
r.method(Method::GET).f(|req| ws::start(req, MyWebSocket{counter: 0})))
|
||||||
// register simple handler, handle all methods
|
// register simple handler, handle all methods
|
||||||
.resource("/", |r| r.f(index)))
|
.resource("/", |r| r.f(index)))
|
||||||
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
||||||
|
@ -61,7 +61,7 @@ fn main() {
|
|||||||
let sys = actix::System::new("ws-example");
|
let sys = actix::System::new("ws-example");
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
// enable logger
|
// enable logger
|
||||||
.middleware(middlewares::Logger::default())
|
.middleware(middlewares::Logger::default())
|
||||||
// websocket route
|
// websocket route
|
||||||
|
@ -15,12 +15,12 @@ Default `Logger` could be created with `default` method, it uses the default for
|
|||||||
%a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T
|
%a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T
|
||||||
```
|
```
|
||||||
```rust
|
```rust
|
||||||
extern crate actix_web;
|
# extern crate actix_web;
|
||||||
use actix_web::Application;
|
use actix_web::Application;
|
||||||
use actix_web::middlewares::Logger;
|
use actix_web::middlewares::Logger;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.middleware(Logger::default())
|
.middleware(Logger::default())
|
||||||
.middleware(Logger::new("%a %{User-Agent}i"))
|
.middleware(Logger::new("%a %{User-Agent}i"))
|
||||||
.finish();
|
.finish();
|
||||||
@ -67,11 +67,11 @@ Tto set default response headers `DefaultHeaders` middleware could be used.
|
|||||||
*DefaultHeaders* middleware does not set header if response headers already contains it.
|
*DefaultHeaders* middleware does not set header if response headers already contains it.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
extern crate actix_web;
|
# extern crate actix_web;
|
||||||
use actix_web::*;
|
use actix_web::*;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let app = Application::default("/")
|
let app = Application::new("/")
|
||||||
.middleware(
|
.middleware(
|
||||||
middlewares::DefaultHeaders::build()
|
middlewares::DefaultHeaders::build()
|
||||||
.header("X-Version", "0.2")
|
.header("X-Version", "0.2")
|
||||||
|
@ -16,7 +16,7 @@ fn index(req: HttpRequest) -> Result<fs::NamedFile> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::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();
|
||||||
}
|
}
|
||||||
@ -32,7 +32,7 @@ To serve files from specific directory and sub-directories `StaticFiles` could b
|
|||||||
use actix_web::*;
|
use actix_web::*;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/static", |r| r.h(fs::StaticFiles::new(".", true)))
|
.resource("/static", |r| r.h(fs::StaticFiles::new(".", true)))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
|
@ -26,8 +26,8 @@ fn main() {
|
|||||||
let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap();
|
let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap();
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.route("/index.html", |r| r.f(index))
|
.resource("/index.html", |r| r.f(index))
|
||||||
.serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap();
|
.serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -48,7 +48,7 @@ request handler with the application's `resource` on a particular *HTTP method*
|
|||||||
# "Hello world!"
|
# "Hello world!"
|
||||||
# }
|
# }
|
||||||
# fn main() {
|
# fn main() {
|
||||||
let app = Application::default("/")
|
let app = Application::new("/")
|
||||||
.resource("/", |r| r.method(Method::GET).f(index))
|
.resource("/", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
# }
|
# }
|
||||||
@ -79,7 +79,7 @@ fn main() {
|
|||||||
let sys = actix::System::new("example");
|
let sys = actix::System::new("example");
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/", |r| r.f(index)))
|
.resource("/", |r| r.f(index)))
|
||||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||||
|
|
||||||
|
@ -20,7 +20,7 @@ has same url path prefix:
|
|||||||
# "Hello world!"
|
# "Hello world!"
|
||||||
# }
|
# }
|
||||||
# fn main() {
|
# fn main() {
|
||||||
let app = Application::default("/prefix")
|
let app = Application::new("/prefix")
|
||||||
.resource("/index.html", |r| r.method(Method::GET).f(index))
|
.resource("/index.html", |r| r.method(Method::GET).f(index))
|
||||||
.finish()
|
.finish()
|
||||||
# }
|
# }
|
||||||
@ -40,15 +40,12 @@ use tokio_core::net::TcpStream;
|
|||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
||||||
Application::default("/app1")
|
Application::new("/app1")
|
||||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk))
|
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
||||||
.finish(),
|
Application::new("/app2")
|
||||||
Application::default("/app2")
|
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
||||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk))
|
Application::new("/")
|
||||||
.finish(),
|
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
||||||
Application::default("/")
|
|
||||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk))
|
|
||||||
.finish(),
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -46,8 +46,8 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
|||||||
Let's create response for custom type that serializes to `application/json` response:
|
Let's create response for custom type that serializes to `application/json` response:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
extern crate actix;
|
# extern crate actix;
|
||||||
extern crate actix_web;
|
# extern crate actix_web;
|
||||||
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;
|
||||||
@ -77,7 +77,7 @@ fn main() {
|
|||||||
let sys = actix::System::new("example");
|
let sys = actix::System::new("example");
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/", |r| r.method(
|
.resource("/", |r| r.method(
|
||||||
Method::GET).f(|req| {MyObj{name: "user".to_owned()}})))
|
Method::GET).f(|req| {MyObj{name: "user".to_owned()}})))
|
||||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||||
@ -113,7 +113,7 @@ fn index(req: HttpRequest) -> FutureResult<HttpResponse, Error> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/async", |r| r.route().a(index))
|
.resource("/async", |r| r.route().a(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -138,7 +138,7 @@ fn index(req: HttpRequest) -> HttpResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/async", |r| r.f(index))
|
.resource("/async", |r| r.f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@ fn index(req: HttpRequest) -> HttpResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/prefix", |r| r.f(index))
|
.resource("/prefix", |r| r.f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -36,7 +36,7 @@ fn index(req: HttpRequest) -> HttpResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/app")
|
Application::new("/app")
|
||||||
.resource("/prefix", |r| r.f(index))
|
.resource("/prefix", |r| r.f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -53,7 +53,7 @@ if no route could be matched default response `HTTPMethodNotAllowed` get resturn
|
|||||||
# use actix_web::*;
|
# use actix_web::*;
|
||||||
#
|
#
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/prefix", |r| {
|
.resource("/prefix", |r| {
|
||||||
r.method(Method::GET).h(httpcodes::HTTPOk);
|
r.method(Method::GET).h(httpcodes::HTTPOk);
|
||||||
r.method(Method::POST).h(httpcodes::HTTPForbidden);
|
r.method(Method::POST).h(httpcodes::HTTPForbidden);
|
||||||
@ -86,7 +86,7 @@ fn index(req: HttpRequest) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource("/{name}", |r| r.method(Method::GET).f(index))
|
.resource("/{name}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -104,7 +104,7 @@ You can also specify a custom regex in the form `{identifier:regex}`:
|
|||||||
# }
|
# }
|
||||||
#
|
#
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource(r"{name:\d+}", |r| r.method(Method::GET).f(index))
|
.resource(r"{name:\d+}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -125,7 +125,7 @@ fn index(req: HttpRequest) -> Result<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource(r"/a/{v1}/{v2}/", |r| r.f(index))
|
.resource(r"/a/{v1}/{v2}/", |r| r.f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -143,7 +143,7 @@ It is possible to match path tail with custom `.*` regex.
|
|||||||
# unimplemented!()
|
# unimplemented!()
|
||||||
# }
|
# }
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::new("/")
|
||||||
.resource(r"/test/{tail:.*}", |r| r.method(Method::GET).f(index))
|
.resource(r"/test/{tail:.*}", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
@ -179,7 +179,7 @@ fn index(req: HttpRequest) -> Result<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::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();
|
||||||
}
|
}
|
||||||
|
@ -30,7 +30,7 @@ fn index(req: HttpRequest<AppState>) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::build("/", AppState{counter: Cell::new(0)})
|
Application::with_state("/", AppState{counter: Cell::new(0)})
|
||||||
.resource("/", |r| r.method(Method::GET).f(index))
|
.resource("/", |r| r.method(Method::GET).f(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
|
@ -75,7 +75,7 @@ fn index(req: HttpRequest) -> Result<Json<MyObj>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::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();
|
||||||
}
|
}
|
||||||
|
@ -3,11 +3,10 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
use error::UriGenerationError;
|
use error::UriGenerationError;
|
||||||
use handler::{Reply, RouteHandler};
|
use handler::{Reply, RouteHandler};
|
||||||
use route::Route;
|
|
||||||
use resource::Resource;
|
use resource::Resource;
|
||||||
use recognizer::{RouteRecognizer, check_pattern, PatternElement};
|
use recognizer::{RouteRecognizer, check_pattern, PatternElement};
|
||||||
use httprequest::HttpRequest;
|
use httprequest::HttpRequest;
|
||||||
use channel::HttpHandler;
|
use channel::{HttpHandler, IntoHttpHandler};
|
||||||
use pipeline::Pipeline;
|
use pipeline::Pipeline;
|
||||||
use middlewares::Middleware;
|
use middlewares::Middleware;
|
||||||
|
|
||||||
@ -56,16 +55,15 @@ impl<S: 'static> Router<S> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Application
|
/// Application
|
||||||
pub struct Application<S> {
|
pub struct HttpApplication<S> {
|
||||||
state: Rc<S>,
|
state: Rc<S>,
|
||||||
prefix: String,
|
prefix: String,
|
||||||
default: Resource<S>,
|
default: Resource<S>,
|
||||||
routes: Vec<(String, Route<S>)>,
|
|
||||||
router: Router<S>,
|
router: Router<S>,
|
||||||
middlewares: Rc<Vec<Box<Middleware>>>,
|
middlewares: Rc<Vec<Box<Middleware>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: 'static> Application<S> {
|
impl<S: 'static> HttpApplication<S> {
|
||||||
|
|
||||||
fn run(&self, req: HttpRequest) -> Reply {
|
fn run(&self, req: HttpRequest) -> Reply {
|
||||||
let mut req = req.with_state(Rc::clone(&self.state));
|
let mut req = req.with_state(Rc::clone(&self.state));
|
||||||
@ -73,21 +71,16 @@ impl<S: 'static> Application<S> {
|
|||||||
if let Some((params, h)) = self.router.0.recognize(req.path()) {
|
if let Some((params, h)) = self.router.0.recognize(req.path()) {
|
||||||
if let Some(params) = params {
|
if let Some(params) = params {
|
||||||
req.set_match_info(params);
|
req.set_match_info(params);
|
||||||
|
req.set_prefix(self.router.0.prefix());
|
||||||
}
|
}
|
||||||
h.handle(req)
|
h.handle(req)
|
||||||
} else {
|
} else {
|
||||||
for route in &self.routes {
|
|
||||||
if req.path().starts_with(&route.0) && route.1.check(&mut req) {
|
|
||||||
req.set_prefix(route.0.len());
|
|
||||||
return route.1.handle(req)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.default.handle(req)
|
self.default.handle(req)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: 'static> HttpHandler for Application<S> {
|
impl<S: 'static> HttpHandler for HttpApplication<S> {
|
||||||
|
|
||||||
fn handle(&self, req: HttpRequest) -> Result<Pipeline, HttpRequest> {
|
fn handle(&self, req: HttpRequest) -> Result<Pipeline, HttpRequest> {
|
||||||
if req.path().starts_with(&self.prefix) {
|
if req.path().starts_with(&self.prefix) {
|
||||||
@ -99,16 +92,31 @@ impl<S: 'static> HttpHandler for Application<S> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ApplicationParts<S> {
|
||||||
|
state: S,
|
||||||
|
prefix: String,
|
||||||
|
default: Resource<S>,
|
||||||
|
resources: HashMap<String, Resource<S>>,
|
||||||
|
middlewares: Vec<Box<Middleware>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Structure that follows the builder pattern for building `Application` structs.
|
||||||
|
pub struct Application<S=()> {
|
||||||
|
parts: Option<ApplicationParts<S>>,
|
||||||
|
}
|
||||||
|
|
||||||
impl Application<()> {
|
impl Application<()> {
|
||||||
|
|
||||||
/// Create default `ApplicationBuilder` with no state
|
/// Create application with empty state. Application can
|
||||||
pub fn default<T: Into<String>>(prefix: T) -> ApplicationBuilder<()> {
|
/// be configured with builder-like pattern.
|
||||||
ApplicationBuilder {
|
///
|
||||||
parts: Some(ApplicationBuilderParts {
|
/// This method accepts path prefix for which it should serve requests.
|
||||||
|
pub fn new<T: Into<String>>(prefix: T) -> Application<()> {
|
||||||
|
Application {
|
||||||
|
parts: Some(ApplicationParts {
|
||||||
state: (),
|
state: (),
|
||||||
prefix: prefix.into(),
|
prefix: prefix.into(),
|
||||||
default: Resource::default_not_found(),
|
default: Resource::default_not_found(),
|
||||||
routes: Vec::new(),
|
|
||||||
resources: HashMap::new(),
|
resources: HashMap::new(),
|
||||||
middlewares: Vec::new(),
|
middlewares: Vec::new(),
|
||||||
})
|
})
|
||||||
@ -118,38 +126,22 @@ impl Application<()> {
|
|||||||
|
|
||||||
impl<S> Application<S> where S: 'static {
|
impl<S> Application<S> where S: 'static {
|
||||||
|
|
||||||
/// Create application builder with specific state. State is shared with all
|
/// Create application with specific state. Application can be
|
||||||
/// routes within same application and could be
|
/// configured with builder-like pattern.
|
||||||
/// accessed with `HttpContext::state()` method.
|
///
|
||||||
pub fn build<T: Into<String>>(prefix: T, state: S) -> ApplicationBuilder<S> {
|
/// State is shared with all reousrces within same application and could be
|
||||||
ApplicationBuilder {
|
/// accessed with `HttpRequest::state()` method.
|
||||||
parts: Some(ApplicationBuilderParts {
|
pub fn with_state<T: Into<String>>(prefix: T, state: S) -> Application<S> {
|
||||||
|
Application {
|
||||||
|
parts: Some(ApplicationParts {
|
||||||
state: state,
|
state: state,
|
||||||
prefix: prefix.into(),
|
prefix: prefix.into(),
|
||||||
default: Resource::default_not_found(),
|
default: Resource::default_not_found(),
|
||||||
routes: Vec::new(),
|
|
||||||
resources: HashMap::new(),
|
resources: HashMap::new(),
|
||||||
middlewares: Vec::new(),
|
middlewares: Vec::new(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
struct ApplicationBuilderParts<S> {
|
|
||||||
state: S,
|
|
||||||
prefix: String,
|
|
||||||
default: Resource<S>,
|
|
||||||
routes: Vec<(String, Route<S>)>,
|
|
||||||
resources: HashMap<String, Resource<S>>,
|
|
||||||
middlewares: Vec<Box<Middleware>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Structure that follows the builder pattern for building `Application` structs.
|
|
||||||
pub struct ApplicationBuilder<S=()> {
|
|
||||||
parts: Option<ApplicationBuilderParts<S>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S> ApplicationBuilder<S> where S: 'static {
|
|
||||||
|
|
||||||
/// Configure resource for specific path.
|
/// Configure resource for specific path.
|
||||||
///
|
///
|
||||||
@ -170,11 +162,11 @@ impl<S> ApplicationBuilder<S> where S: 'static {
|
|||||||
/// store userid and friend in the exposed Params object:
|
/// store userid and friend in the exposed Params object:
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate actix_web;
|
/// # extern crate actix_web;
|
||||||
/// use actix_web::*;
|
/// use actix_web::*;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::new("/")
|
||||||
/// .resource("/test", |r| {
|
/// .resource("/test", |r| {
|
||||||
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
|
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
|
||||||
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
|
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
|
||||||
@ -219,39 +211,43 @@ impl<S> ApplicationBuilder<S> where S: 'static {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Construct application
|
/// Finish application configuration and create HttpHandler object
|
||||||
pub fn finish(&mut self) -> Application<S> {
|
pub fn finish(&mut self) -> HttpApplication<S> {
|
||||||
let parts = self.parts.take().expect("Use after finish");
|
let parts = self.parts.take().expect("Use after finish");
|
||||||
|
|
||||||
let prefix = if parts.prefix.ends_with('/') {
|
let prefix = if parts.prefix.ends_with('/') {
|
||||||
parts.prefix
|
parts.prefix
|
||||||
} else {
|
} else {
|
||||||
parts.prefix + "/"
|
parts.prefix + "/"
|
||||||
};
|
};
|
||||||
|
HttpApplication {
|
||||||
let mut routes = Vec::new();
|
|
||||||
for (path, route) in parts.routes {
|
|
||||||
routes.push((prefix.clone() + path.trim_left_matches('/'), route));
|
|
||||||
}
|
|
||||||
Application {
|
|
||||||
state: Rc::new(parts.state),
|
state: Rc::new(parts.state),
|
||||||
prefix: prefix.clone(),
|
prefix: prefix.clone(),
|
||||||
default: parts.default,
|
default: parts.default,
|
||||||
routes: routes,
|
|
||||||
router: Router::new(prefix, parts.resources),
|
router: Router::new(prefix, parts.resources),
|
||||||
middlewares: Rc::new(parts.middlewares),
|
middlewares: Rc::new(parts.middlewares),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: 'static> From<ApplicationBuilder<S>> for Application<S> {
|
impl<S: 'static> IntoHttpHandler for Application<S> {
|
||||||
fn from(mut builder: ApplicationBuilder<S>) -> Application<S> {
|
type Handler = HttpApplication<S>;
|
||||||
builder.finish()
|
|
||||||
|
fn into_handler(mut self) -> HttpApplication<S> {
|
||||||
|
self.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: 'static> Iterator for ApplicationBuilder<S> {
|
impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
|
||||||
type Item = Application<S>;
|
type Handler = HttpApplication<S>;
|
||||||
|
|
||||||
|
fn into_handler(self) -> HttpApplication<S> {
|
||||||
|
self.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
impl<S: 'static> Iterator for Application<S> {
|
||||||
|
type Item = HttpApplication<S>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
if self.parts.is_some() {
|
if self.parts.is_some() {
|
||||||
|
@ -17,6 +17,23 @@ pub trait HttpHandler: 'static {
|
|||||||
fn handle(&self, req: HttpRequest) -> Result<Pipeline, HttpRequest>;
|
fn handle(&self, req: HttpRequest) -> Result<Pipeline, HttpRequest>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Conversion helper trait
|
||||||
|
pub trait IntoHttpHandler {
|
||||||
|
/// The associated type which is result of conversion.
|
||||||
|
type Handler: HttpHandler;
|
||||||
|
|
||||||
|
/// Convert into `HttpHandler` object.
|
||||||
|
fn into_handler(self) -> Self::Handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: HttpHandler> IntoHttpHandler for T {
|
||||||
|
type Handler = T;
|
||||||
|
|
||||||
|
fn into_handler(self) -> Self::Handler {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
enum HttpProtocol<T, H>
|
enum HttpProtocol<T, H>
|
||||||
where T: AsyncRead + AsyncWrite + 'static, H: 'static
|
where T: AsyncRead + AsyncWrite + 'static, H: 'static
|
||||||
{
|
{
|
||||||
|
@ -12,9 +12,8 @@
|
|||||||
pub use info::ConnectionInfo;
|
pub use info::ConnectionInfo;
|
||||||
pub use handler::Handler;
|
pub use handler::Handler;
|
||||||
pub use pipeline::Pipeline;
|
pub use pipeline::Pipeline;
|
||||||
pub use channel::{HttpChannel, HttpHandler};
|
pub use channel::{HttpChannel, HttpHandler, IntoHttpHandler};
|
||||||
pub use recognizer::{FromParam, RouteRecognizer, Pattern, PatternElement};
|
pub use recognizer::{FromParam, RouteRecognizer, Pattern, PatternElement};
|
||||||
|
|
||||||
pub use cookie::CookieBuilder;
|
pub use cookie::CookieBuilder;
|
||||||
pub use application::ApplicationBuilder;
|
|
||||||
pub use httpresponse::HttpResponseBuilder;
|
pub use httpresponse::HttpResponseBuilder;
|
||||||
|
@ -227,7 +227,7 @@ pub enum HttpRangeError {
|
|||||||
InvalidRange,
|
InvalidRange,
|
||||||
/// Returned if first-byte-pos of all of the byte-range-spec
|
/// Returned if first-byte-pos of all of the byte-range-spec
|
||||||
/// values is greater than the content size.
|
/// values is greater than the content size.
|
||||||
/// See https://github.com/golang/go/commit/aa9b3d7
|
/// See `https://github.com/golang/go/commit/aa9b3d7`
|
||||||
#[fail(display="First-byte-pos of all of the byte-range-spec values is greater than the content size")]
|
#[fail(display="First-byte-pos of all of the byte-range-spec values is greater than the content size")]
|
||||||
NoOverlap,
|
NoOverlap,
|
||||||
}
|
}
|
||||||
|
@ -194,11 +194,12 @@ impl FromRequest for FilesystemElement {
|
|||||||
/// Can be registered with `Application::route_handler()`.
|
/// Can be registered with `Application::route_handler()`.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate actix_web;
|
/// # extern crate actix_web;
|
||||||
|
/// use actix_web::{fs, Application};
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = actix_web::Application::default("/")
|
/// let app = Application::new("/")
|
||||||
/// .resource("/static", |r| r.h(actix_web::fs::StaticFiles::new(".", true)))
|
/// .resource("/static", |r| r.h(fs::StaticFiles::new(".", true)))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
//! Web framework for [Actix](https://github.com/actix/actix)
|
//! Actix web is a small, fast, down-to-earth, open source rust web framework.
|
||||||
|
|
||||||
#![cfg_attr(actix_nightly, feature(
|
#![cfg_attr(actix_nightly, feature(
|
||||||
specialization, // for impl ErrorResponse for std::error::Error
|
specialization, // for impl ErrorResponse for std::error::Error
|
||||||
|
@ -11,11 +11,11 @@ use middlewares::{Response, Middleware};
|
|||||||
/// This middleware does not set header if response headers already contains it.
|
/// This middleware does not set header if response headers already contains it.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate actix_web;
|
/// # extern crate actix_web;
|
||||||
/// use actix_web::*;
|
/// use actix_web::*;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::new("/")
|
||||||
/// .middleware(
|
/// .middleware(
|
||||||
/// middlewares::DefaultHeaders::build()
|
/// middlewares::DefaultHeaders::build()
|
||||||
/// .header("X-Version", "0.2")
|
/// .header("X-Version", "0.2")
|
||||||
|
@ -22,12 +22,12 @@ use middlewares::{Middleware, Started, Finished};
|
|||||||
/// %a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T
|
/// %a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T
|
||||||
/// ```
|
/// ```
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate actix_web;
|
/// # extern crate actix_web;
|
||||||
/// use actix_web::Application;
|
/// use actix_web::Application;
|
||||||
/// use actix_web::middlewares::Logger;
|
/// use actix_web::middlewares::Logger;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::new("/")
|
||||||
/// .middleware(Logger::default())
|
/// .middleware(Logger::default())
|
||||||
/// .middleware(Logger::new("%a %{User-Agent}i"))
|
/// .middleware(Logger::new("%a %{User-Agent}i"))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
|
@ -241,6 +241,11 @@ impl<T> RouteRecognizer<T> {
|
|||||||
self.patterns.get(name)
|
self.patterns.get(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Length of the prefix
|
||||||
|
pub fn prefix(&self) -> usize {
|
||||||
|
self.prefix
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_prefix<P: Into<String>>(&mut self, prefix: P) {
|
pub fn set_prefix<P: Into<String>>(&mut self, prefix: P) {
|
||||||
let p = prefix.into();
|
let p = prefix.into();
|
||||||
if p.ends_with('/') {
|
if p.ends_with('/') {
|
||||||
|
@ -18,13 +18,13 @@ use httprequest::HttpRequest;
|
|||||||
/// route considired matched and route handler get called.
|
/// route considired matched and route handler get called.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate actix_web;
|
/// # extern crate actix_web;
|
||||||
/// use actix_web::*;
|
/// use actix_web::*;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::new("/")
|
||||||
/// .resource(
|
/// .resource(
|
||||||
/// "/", |r| r.route().method(Method::GET).f(|r| HttpResponse::Ok()))
|
/// "/", |r| r.method(Method::GET).f(|r| HttpResponse::Ok()))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
pub struct Resource<S=()> {
|
pub struct Resource<S=()> {
|
||||||
@ -67,11 +67,11 @@ impl<S> Resource<S> where S: 'static {
|
|||||||
/// *Route* is used for route configuration, i.e. adding predicates, setting up handler.
|
/// *Route* is used for route configuration, i.e. adding predicates, setting up handler.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// extern crate actix_web;
|
/// # extern crate actix_web;
|
||||||
/// use actix_web::*;
|
/// use actix_web::*;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::new("/")
|
||||||
/// .resource(
|
/// .resource(
|
||||||
/// "/", |r| r.route()
|
/// "/", |r| r.route()
|
||||||
/// .p(pred::Any(vec![pred::Get(), pred::Put()]))
|
/// .p(pred::Any(vec![pred::Get(), pred::Put()]))
|
||||||
@ -87,7 +87,8 @@ impl<S> Resource<S> where S: 'static {
|
|||||||
|
|
||||||
/// Register a new route and add method check to route.
|
/// Register a new route and add method check to route.
|
||||||
///
|
///
|
||||||
/// This is sortcut for:
|
/// This is shortcut for:
|
||||||
|
///
|
||||||
/// ```rust,ignore
|
/// ```rust,ignore
|
||||||
/// Resource::resource("/", |r| r.route().method(Method::GET).f(index)
|
/// Resource::resource("/", |r| r.route().method(Method::GET).f(index)
|
||||||
/// ```
|
/// ```
|
||||||
@ -98,7 +99,8 @@ impl<S> Resource<S> where S: 'static {
|
|||||||
|
|
||||||
/// Register a new route and add handler object.
|
/// Register a new route and add handler object.
|
||||||
///
|
///
|
||||||
/// This is sortcut for:
|
/// This is shortcut for:
|
||||||
|
///
|
||||||
/// ```rust,ignore
|
/// ```rust,ignore
|
||||||
/// Resource::resource("/", |r| r.route().h(handler)
|
/// Resource::resource("/", |r| r.route().h(handler)
|
||||||
/// ```
|
/// ```
|
||||||
@ -109,7 +111,8 @@ impl<S> Resource<S> where S: 'static {
|
|||||||
|
|
||||||
/// Register a new route and add handler function.
|
/// Register a new route and add handler function.
|
||||||
///
|
///
|
||||||
/// This is sortcut for:
|
/// This is shortcut for:
|
||||||
|
///
|
||||||
/// ```rust,ignore
|
/// ```rust,ignore
|
||||||
/// Resource::resource("/", |r| r.route().f(index)
|
/// Resource::resource("/", |r| r.route().f(index)
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -24,7 +24,7 @@ use openssl::pkcs12::ParsedPkcs12;
|
|||||||
#[cfg(feature="alpn")]
|
#[cfg(feature="alpn")]
|
||||||
use tokio_openssl::{SslStream, SslAcceptorExt};
|
use tokio_openssl::{SslStream, SslAcceptorExt};
|
||||||
|
|
||||||
use channel::{HttpChannel, HttpHandler};
|
use channel::{HttpChannel, HttpHandler, IntoHttpHandler};
|
||||||
|
|
||||||
|
|
||||||
/// An HTTP Server
|
/// An HTTP Server
|
||||||
@ -47,8 +47,10 @@ impl<T: 'static, A: 'static, H: 'static> Actor for HttpServer<T, A, H> {
|
|||||||
impl<T, A, H> HttpServer<T, A, H> where H: HttpHandler
|
impl<T, A, H> HttpServer<T, A, H> where H: HttpHandler
|
||||||
{
|
{
|
||||||
/// Create new http server with vec of http handlers
|
/// Create new http server with vec of http handlers
|
||||||
pub fn new<U: IntoIterator<Item=H>>(handler: U) -> Self {
|
pub fn new<V, U: IntoIterator<Item=V>>(handler: U) -> Self
|
||||||
let apps: Vec<_> = handler.into_iter().collect();
|
where V: IntoHttpHandler<Handler=H>
|
||||||
|
{
|
||||||
|
let apps: Vec<_> = handler.into_iter().map(|h| h.into_handler()).collect();
|
||||||
|
|
||||||
HttpServer {h: Rc::new(apps),
|
HttpServer {h: Rc::new(apps),
|
||||||
io: PhantomData,
|
io: PhantomData,
|
||||||
|
@ -42,7 +42,7 @@
|
|||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! fn main() {
|
//! fn main() {
|
||||||
//! Application::default("/")
|
//! Application::new("/")
|
||||||
//! .resource("/ws/", |r| r.method(Method::GET).f(ws_index)) // <- register websocket route
|
//! .resource("/ws/", |r| r.method(Method::GET).f(ws_index)) // <- register websocket route
|
||||||
//! .finish();
|
//! .finish();
|
||||||
//! }
|
//! }
|
||||||
|
@ -11,20 +11,13 @@ use tokio_core::net::TcpListener;
|
|||||||
use actix::*;
|
use actix::*;
|
||||||
use actix_web::*;
|
use actix_web::*;
|
||||||
|
|
||||||
|
|
||||||
fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
|
|
||||||
HttpServer::new(
|
|
||||||
vec![Application::default("/")
|
|
||||||
.resource("/", |r|
|
|
||||||
r.route().method(Method::GET).h(httpcodes::HTTPOk))
|
|
||||||
.finish()])
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_serve() {
|
fn test_serve() {
|
||||||
thread::spawn(|| {
|
thread::spawn(|| {
|
||||||
let sys = System::new("test");
|
let sys = System::new("test");
|
||||||
let srv = create_server();
|
let srv = HttpServer::new(
|
||||||
|
vec![Application::new("/")
|
||||||
|
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))]);
|
||||||
srv.serve::<_, ()>("127.0.0.1:58902").unwrap();
|
srv.serve::<_, ()>("127.0.0.1:58902").unwrap();
|
||||||
sys.run();
|
sys.run();
|
||||||
});
|
});
|
||||||
@ -42,7 +35,9 @@ fn test_serve_incoming() {
|
|||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
let sys = System::new("test");
|
let sys = System::new("test");
|
||||||
|
|
||||||
let srv = create_server();
|
let srv = HttpServer::new(
|
||||||
|
Application::new("/")
|
||||||
|
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk)));
|
||||||
let tcp = TcpListener::from_listener(tcp, &addr2, Arbiter::handle()).unwrap();
|
let tcp = TcpListener::from_listener(tcp, &addr2, Arbiter::handle()).unwrap();
|
||||||
srv.serve_incoming::<_, ()>(tcp.incoming()).unwrap();
|
srv.serve_incoming::<_, ()>(tcp.incoming()).unwrap();
|
||||||
sys.run();
|
sys.run();
|
||||||
@ -89,19 +84,17 @@ fn test_middlewares() {
|
|||||||
let sys = System::new("test");
|
let sys = System::new("test");
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
vec![Application::default("/")
|
vec![Application::new("/")
|
||||||
.middleware(MiddlewareTest{start: act_num1,
|
.middleware(MiddlewareTest{start: act_num1,
|
||||||
response: act_num2,
|
response: act_num2,
|
||||||
finish: act_num3})
|
finish: act_num3})
|
||||||
.resource("/", |r|
|
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))
|
||||||
r.route().method(Method::GET).h(httpcodes::HTTPOk))
|
|
||||||
.finish()])
|
.finish()])
|
||||||
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
||||||
sys.run();
|
sys.run();
|
||||||
});
|
});
|
||||||
|
|
||||||
assert!(reqwest::get("http://localhost:58904/").unwrap().status().is_success());
|
assert!(reqwest::get("http://localhost:58904/").unwrap().status().is_success());
|
||||||
|
|
||||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||||
|
Loading…
Reference in New Issue
Block a user