diff --git a/README.md b/README.md index 528098c6b..9502c6501 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,6 @@ Actix web is a small, fast, down-to-earth, open source rust web framework. ```rust,ignore -extern crate actix_web; use actix_web::*; fn index(req: HttpRequest) -> String { @@ -12,7 +11,7 @@ fn index(req: HttpRequest) -> String { fn main() { HttpServer::new( - Application::default("/") + Application::new("/") .resource("/{name}", |r| r.method(Method::GET).f(index))) .serve::<_, ()>("127.0.0.1:8080"); } diff --git a/examples/basic.rs b/examples/basic.rs index db43fce50..164ca7a18 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -57,7 +57,7 @@ fn main() { let sys = actix::System::new("ws-example"); HttpServer::new( - Application::default("/") + Application::new("/") // enable logger .middleware(middlewares::Logger::default()) // cookie session middleware diff --git a/examples/state.rs b/examples/state.rs index 2e8df9256..c199dd5e5 100644 --- a/examples/state.rs +++ b/examples/state.rs @@ -60,13 +60,13 @@ fn main() { let sys = actix::System::new("ws-example"); HttpServer::new( - Application::build("/", AppState{counter: Cell::new(0)}) + Application::with_state("/", AppState{counter: Cell::new(0)}) // enable logger .middleware(middlewares::Logger::default()) // websocket route .resource( - "/ws/", |r| r.method(Method::GET) - .f(|req| ws::start(req, MyWebSocket{counter: 0}))) + "/ws/", |r| + r.method(Method::GET).f(|req| ws::start(req, MyWebSocket{counter: 0}))) // register simple handler, handle all methods .resource("/", |r| r.f(index))) .serve::<_, ()>("127.0.0.1:8080").unwrap(); diff --git a/examples/websocket.rs b/examples/websocket.rs index ba316b601..93b407464 100644 --- a/examples/websocket.rs +++ b/examples/websocket.rs @@ -61,7 +61,7 @@ fn main() { let sys = actix::System::new("ws-example"); HttpServer::new( - Application::default("/") + Application::new("/") // enable logger .middleware(middlewares::Logger::default()) // websocket route diff --git a/guide/src/qs_10.md b/guide/src/qs_10.md index 23275cb4f..664106f99 100644 --- a/guide/src/qs_10.md +++ b/guide/src/qs_10.md @@ -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 ``` ```rust -extern crate actix_web; +# extern crate actix_web; use actix_web::Application; use actix_web::middlewares::Logger; fn main() { - Application::default("/") + Application::new("/") .middleware(Logger::default()) .middleware(Logger::new("%a %{User-Agent}i")) .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. ```rust -extern crate actix_web; +# extern crate actix_web; use actix_web::*; fn main() { - let app = Application::default("/") + let app = Application::new("/") .middleware( middlewares::DefaultHeaders::build() .header("X-Version", "0.2") diff --git a/guide/src/qs_12.md b/guide/src/qs_12.md index 4cfa8b5f4..7cabe7449 100644 --- a/guide/src/qs_12.md +++ b/guide/src/qs_12.md @@ -16,7 +16,7 @@ fn index(req: HttpRequest) -> Result { } fn main() { - Application::default("/") + Application::new("/") .resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index)) .finish(); } @@ -32,7 +32,7 @@ To serve files from specific directory and sub-directories `StaticFiles` could b use actix_web::*; fn main() { - Application::default("/") + Application::new("/") .resource("/static", |r| r.h(fs::StaticFiles::new(".", true))) .finish(); } diff --git a/guide/src/qs_13.md b/guide/src/qs_13.md index b567f6286..c3b0b0e72 100644 --- a/guide/src/qs_13.md +++ b/guide/src/qs_13.md @@ -26,8 +26,8 @@ fn main() { let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap(); HttpServer::new( - Application::default("/") - .route("/index.html", |r| r.f(index)) + Application::new("/") + .resource("/index.html", |r| r.f(index)) .serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap(); } ``` diff --git a/guide/src/qs_2.md b/guide/src/qs_2.md index 41c62a6f1..f8187c70d 100644 --- a/guide/src/qs_2.md +++ b/guide/src/qs_2.md @@ -48,7 +48,7 @@ request handler with the application's `resource` on a particular *HTTP method* # "Hello world!" # } # fn main() { - let app = Application::default("/") + let app = Application::new("/") .resource("/", |r| r.method(Method::GET).f(index)) .finish(); # } @@ -79,7 +79,7 @@ fn main() { let sys = actix::System::new("example"); HttpServer::new( - Application::default("/") + Application::new("/") .resource("/", |r| r.f(index))) .serve::<_, ()>("127.0.0.1:8088").unwrap(); diff --git a/guide/src/qs_3.md b/guide/src/qs_3.md index e70e04bef..2b954045e 100644 --- a/guide/src/qs_3.md +++ b/guide/src/qs_3.md @@ -20,7 +20,7 @@ has same url path prefix: # "Hello world!" # } # fn main() { - let app = Application::default("/prefix") + let app = Application::new("/prefix") .resource("/index.html", |r| r.method(Method::GET).f(index)) .finish() # } @@ -40,15 +40,12 @@ use tokio_core::net::TcpStream; fn main() { HttpServer::::new(vec![ - Application::default("/app1") - .resource("/", |r| r.f(|r| httpcodes::HTTPOk)) - .finish(), - Application::default("/app2") - .resource("/", |r| r.f(|r| httpcodes::HTTPOk)) - .finish(), - Application::default("/") - .resource("/", |r| r.f(|r| httpcodes::HTTPOk)) - .finish(), + Application::new("/app1") + .resource("/", |r| r.f(|r| httpcodes::HTTPOk)), + Application::new("/app2") + .resource("/", |r| r.f(|r| httpcodes::HTTPOk)), + Application::new("/") + .resource("/", |r| r.f(|r| httpcodes::HTTPOk)), ]); } ``` diff --git a/guide/src/qs_4.md b/guide/src/qs_4.md index bd37434b2..ae5ae19c2 100644 --- a/guide/src/qs_4.md +++ b/guide/src/qs_4.md @@ -46,8 +46,8 @@ fn index(req: HttpRequest) -> Box> { Let's create response for custom type that serializes to `application/json` response: ```rust -extern crate actix; -extern crate actix_web; +# extern crate actix; +# extern crate actix_web; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; @@ -77,7 +77,7 @@ fn main() { let sys = actix::System::new("example"); HttpServer::new( - Application::default("/") + Application::new("/") .resource("/", |r| r.method( Method::GET).f(|req| {MyObj{name: "user".to_owned()}}))) .serve::<_, ()>("127.0.0.1:8088").unwrap(); @@ -113,7 +113,7 @@ fn index(req: HttpRequest) -> FutureResult { } fn main() { - Application::default("/") + Application::new("/") .resource("/async", |r| r.route().a(index)) .finish(); } @@ -138,7 +138,7 @@ fn index(req: HttpRequest) -> HttpResponse { } fn main() { - Application::default("/") + Application::new("/") .resource("/async", |r| r.f(index)) .finish(); } diff --git a/guide/src/qs_5.md b/guide/src/qs_5.md index b2ae22753..bd046ddac 100644 --- a/guide/src/qs_5.md +++ b/guide/src/qs_5.md @@ -17,7 +17,7 @@ fn index(req: HttpRequest) -> HttpResponse { } fn main() { - Application::default("/") + Application::new("/") .resource("/prefix", |r| r.f(index)) .finish(); } @@ -36,7 +36,7 @@ fn index(req: HttpRequest) -> HttpResponse { } fn main() { - Application::default("/app") + Application::new("/app") .resource("/prefix", |r| r.f(index)) .finish(); } @@ -53,7 +53,7 @@ if no route could be matched default response `HTTPMethodNotAllowed` get resturn # use actix_web::*; # fn main() { - Application::default("/") + Application::new("/") .resource("/prefix", |r| { r.method(Method::GET).h(httpcodes::HTTPOk); r.method(Method::POST).h(httpcodes::HTTPForbidden); @@ -86,7 +86,7 @@ fn index(req: HttpRequest) -> String { } fn main() { - Application::default("/") + Application::new("/") .resource("/{name}", |r| r.method(Method::GET).f(index)) .finish(); } @@ -104,7 +104,7 @@ You can also specify a custom regex in the form `{identifier:regex}`: # } # fn main() { - Application::default("/") + Application::new("/") .resource(r"{name:\d+}", |r| r.method(Method::GET).f(index)) .finish(); } @@ -125,7 +125,7 @@ fn index(req: HttpRequest) -> Result { } fn main() { - Application::default("/") + Application::new("/") .resource(r"/a/{v1}/{v2}/", |r| r.f(index)) .finish(); } @@ -143,7 +143,7 @@ It is possible to match path tail with custom `.*` regex. # unimplemented!() # } fn main() { - Application::default("/") + Application::new("/") .resource(r"/test/{tail:.*}", |r| r.method(Method::GET).f(index)) .finish(); } @@ -179,7 +179,7 @@ fn index(req: HttpRequest) -> Result { } fn main() { - Application::default("/") + Application::new("/") .resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index)) .finish(); } diff --git a/guide/src/qs_6.md b/guide/src/qs_6.md index 46802014d..73a342ca3 100644 --- a/guide/src/qs_6.md +++ b/guide/src/qs_6.md @@ -30,7 +30,7 @@ fn index(req: HttpRequest) -> String { } 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)) .finish(); } diff --git a/guide/src/qs_7.md b/guide/src/qs_7.md index 7668f0fef..e1f31dd98 100644 --- a/guide/src/qs_7.md +++ b/guide/src/qs_7.md @@ -75,7 +75,7 @@ fn index(req: HttpRequest) -> Result> { } fn main() { - Application::default("/") + Application::new("/") .resource(r"/a/{name}", |r| r.method(Method::GET).f(index)) .finish(); } diff --git a/src/application.rs b/src/application.rs index d0274725a..7dc811095 100644 --- a/src/application.rs +++ b/src/application.rs @@ -3,11 +3,10 @@ use std::collections::HashMap; use error::UriGenerationError; use handler::{Reply, RouteHandler}; -use route::Route; use resource::Resource; use recognizer::{RouteRecognizer, check_pattern, PatternElement}; use httprequest::HttpRequest; -use channel::HttpHandler; +use channel::{HttpHandler, IntoHttpHandler}; use pipeline::Pipeline; use middlewares::Middleware; @@ -56,16 +55,15 @@ impl Router { } /// Application -pub struct Application { +pub struct HttpApplication { state: Rc, prefix: String, default: Resource, - routes: Vec<(String, Route)>, router: Router, middlewares: Rc>>, } -impl Application { +impl HttpApplication { fn run(&self, req: HttpRequest) -> Reply { let mut req = req.with_state(Rc::clone(&self.state)); @@ -73,21 +71,16 @@ impl Application { if let Some((params, h)) = self.router.0.recognize(req.path()) { if let Some(params) = params { req.set_match_info(params); + req.set_prefix(self.router.0.prefix()); } h.handle(req) } 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) } } } -impl HttpHandler for Application { +impl HttpHandler for HttpApplication { fn handle(&self, req: HttpRequest) -> Result { if req.path().starts_with(&self.prefix) { @@ -99,16 +92,31 @@ impl HttpHandler for Application { } } +struct ApplicationParts { + state: S, + prefix: String, + default: Resource, + resources: HashMap>, + middlewares: Vec>, +} + +/// Structure that follows the builder pattern for building `Application` structs. +pub struct Application { + parts: Option>, +} + impl Application<()> { - /// Create default `ApplicationBuilder` with no state - pub fn default>(prefix: T) -> ApplicationBuilder<()> { - ApplicationBuilder { - parts: Some(ApplicationBuilderParts { + /// Create application with empty state. Application can + /// be configured with builder-like pattern. + /// + /// This method accepts path prefix for which it should serve requests. + pub fn new>(prefix: T) -> Application<()> { + Application { + parts: Some(ApplicationParts { state: (), prefix: prefix.into(), default: Resource::default_not_found(), - routes: Vec::new(), resources: HashMap::new(), middlewares: Vec::new(), }) @@ -118,38 +126,22 @@ impl Application<()> { impl Application where S: 'static { - /// Create application builder with specific state. State is shared with all - /// routes within same application and could be - /// accessed with `HttpContext::state()` method. - pub fn build>(prefix: T, state: S) -> ApplicationBuilder { - ApplicationBuilder { - parts: Some(ApplicationBuilderParts { + /// Create application with specific state. Application can be + /// configured with builder-like pattern. + /// + /// State is shared with all reousrces within same application and could be + /// accessed with `HttpRequest::state()` method. + pub fn with_state>(prefix: T, state: S) -> Application { + Application { + parts: Some(ApplicationParts { state: state, prefix: prefix.into(), default: Resource::default_not_found(), - routes: Vec::new(), resources: HashMap::new(), middlewares: Vec::new(), }) } } -} - -struct ApplicationBuilderParts { - state: S, - prefix: String, - default: Resource, - routes: Vec<(String, Route)>, - resources: HashMap>, - middlewares: Vec>, -} - -/// Structure that follows the builder pattern for building `Application` structs. -pub struct ApplicationBuilder { - parts: Option>, -} - -impl ApplicationBuilder where S: 'static { /// Configure resource for specific path. /// @@ -170,11 +162,11 @@ impl ApplicationBuilder where S: 'static { /// store userid and friend in the exposed Params object: /// /// ```rust - /// extern crate actix_web; + /// # extern crate actix_web; /// use actix_web::*; /// /// fn main() { - /// let app = Application::default("/") + /// let app = Application::new("/") /// .resource("/test", |r| { /// r.method(Method::GET).f(|_| httpcodes::HTTPOk); /// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed); @@ -219,39 +211,43 @@ impl ApplicationBuilder where S: 'static { self } - /// Construct application - pub fn finish(&mut self) -> Application { + /// Finish application configuration and create HttpHandler object + pub fn finish(&mut self) -> HttpApplication { let parts = self.parts.take().expect("Use after finish"); - let prefix = if parts.prefix.ends_with('/') { parts.prefix } else { parts.prefix + "/" }; - - let mut routes = Vec::new(); - for (path, route) in parts.routes { - routes.push((prefix.clone() + path.trim_left_matches('/'), route)); - } - Application { + HttpApplication { state: Rc::new(parts.state), prefix: prefix.clone(), default: parts.default, - routes: routes, router: Router::new(prefix, parts.resources), middlewares: Rc::new(parts.middlewares), } } } -impl From> for Application { - fn from(mut builder: ApplicationBuilder) -> Application { - builder.finish() +impl IntoHttpHandler for Application { + type Handler = HttpApplication; + + fn into_handler(mut self) -> HttpApplication { + self.finish() } } -impl Iterator for ApplicationBuilder { - type Item = Application; +impl<'a, S: 'static> IntoHttpHandler for &'a mut Application { + type Handler = HttpApplication; + + fn into_handler(self) -> HttpApplication { + self.finish() + } +} + +#[doc(hidden)] +impl Iterator for Application { + type Item = HttpApplication; fn next(&mut self) -> Option { if self.parts.is_some() { diff --git a/src/channel.rs b/src/channel.rs index a15591c9f..ac9875a47 100644 --- a/src/channel.rs +++ b/src/channel.rs @@ -17,6 +17,23 @@ pub trait HttpHandler: 'static { fn handle(&self, req: HttpRequest) -> Result; } +/// 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 IntoHttpHandler for T { + type Handler = T; + + fn into_handler(self) -> Self::Handler { + self + } +} + enum HttpProtocol where T: AsyncRead + AsyncWrite + 'static, H: 'static { diff --git a/src/dev.rs b/src/dev.rs index 47efce082..fefcfc71f 100644 --- a/src/dev.rs +++ b/src/dev.rs @@ -12,9 +12,8 @@ pub use info::ConnectionInfo; pub use handler::Handler; pub use pipeline::Pipeline; -pub use channel::{HttpChannel, HttpHandler}; +pub use channel::{HttpChannel, HttpHandler, IntoHttpHandler}; pub use recognizer::{FromParam, RouteRecognizer, Pattern, PatternElement}; pub use cookie::CookieBuilder; -pub use application::ApplicationBuilder; pub use httpresponse::HttpResponseBuilder; diff --git a/src/error.rs b/src/error.rs index dcd02fdf0..61aa07df8 100644 --- a/src/error.rs +++ b/src/error.rs @@ -227,7 +227,7 @@ pub enum HttpRangeError { InvalidRange, /// Returned if first-byte-pos of all of the byte-range-spec /// 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")] NoOverlap, } diff --git a/src/fs.rs b/src/fs.rs index 7f0a2a2dc..2c000ffed 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -194,11 +194,12 @@ impl FromRequest for FilesystemElement { /// Can be registered with `Application::route_handler()`. /// /// ```rust -/// extern crate actix_web; +/// # extern crate actix_web; +/// use actix_web::{fs, Application}; /// /// fn main() { -/// let app = actix_web::Application::default("/") -/// .resource("/static", |r| r.h(actix_web::fs::StaticFiles::new(".", true))) +/// let app = Application::new("/") +/// .resource("/static", |r| r.h(fs::StaticFiles::new(".", true))) /// .finish(); /// } /// ``` diff --git a/src/lib.rs b/src/lib.rs index 25a9b2049..8c9218775 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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( specialization, // for impl ErrorResponse for std::error::Error diff --git a/src/middlewares/defaultheaders.rs b/src/middlewares/defaultheaders.rs index 08d6a923f..5f4dd8bcd 100644 --- a/src/middlewares/defaultheaders.rs +++ b/src/middlewares/defaultheaders.rs @@ -11,11 +11,11 @@ use middlewares::{Response, Middleware}; /// This middleware does not set header if response headers already contains it. /// /// ```rust -/// extern crate actix_web; +/// # extern crate actix_web; /// use actix_web::*; /// /// fn main() { -/// let app = Application::default("/") +/// let app = Application::new("/") /// .middleware( /// middlewares::DefaultHeaders::build() /// .header("X-Version", "0.2") diff --git a/src/middlewares/logger.rs b/src/middlewares/logger.rs index 51667a22c..a18e8ad15 100644 --- a/src/middlewares/logger.rs +++ b/src/middlewares/logger.rs @@ -22,12 +22,12 @@ use middlewares::{Middleware, Started, Finished}; /// %a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T /// ``` /// ```rust -/// extern crate actix_web; +/// # extern crate actix_web; /// use actix_web::Application; /// use actix_web::middlewares::Logger; /// /// fn main() { -/// let app = Application::default("/") +/// let app = Application::new("/") /// .middleware(Logger::default()) /// .middleware(Logger::new("%a %{User-Agent}i")) /// .finish(); diff --git a/src/recognizer.rs b/src/recognizer.rs index 3fb34330c..459086550 100644 --- a/src/recognizer.rs +++ b/src/recognizer.rs @@ -241,6 +241,11 @@ impl RouteRecognizer { self.patterns.get(name) } + /// Length of the prefix + pub fn prefix(&self) -> usize { + self.prefix + } + pub fn set_prefix>(&mut self, prefix: P) { let p = prefix.into(); if p.ends_with('/') { diff --git a/src/resource.rs b/src/resource.rs index f499c42b1..3dc50c959 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -18,13 +18,13 @@ use httprequest::HttpRequest; /// route considired matched and route handler get called. /// /// ```rust -/// extern crate actix_web; +/// # extern crate actix_web; /// use actix_web::*; /// /// fn main() { -/// let app = Application::default("/") +/// let app = Application::new("/") /// .resource( -/// "/", |r| r.route().method(Method::GET).f(|r| HttpResponse::Ok())) +/// "/", |r| r.method(Method::GET).f(|r| HttpResponse::Ok())) /// .finish(); /// } pub struct Resource { @@ -67,11 +67,11 @@ impl Resource where S: 'static { /// *Route* is used for route configuration, i.e. adding predicates, setting up handler. /// /// ```rust - /// extern crate actix_web; + /// # extern crate actix_web; /// use actix_web::*; /// /// fn main() { - /// let app = Application::default("/") + /// let app = Application::new("/") /// .resource( /// "/", |r| r.route() /// .p(pred::Any(vec![pred::Get(), pred::Put()])) @@ -87,7 +87,8 @@ impl Resource where S: 'static { /// Register a new route and add method check to route. /// - /// This is sortcut for: + /// This is shortcut for: + /// /// ```rust,ignore /// Resource::resource("/", |r| r.route().method(Method::GET).f(index) /// ``` @@ -98,7 +99,8 @@ impl Resource where S: 'static { /// Register a new route and add handler object. /// - /// This is sortcut for: + /// This is shortcut for: + /// /// ```rust,ignore /// Resource::resource("/", |r| r.route().h(handler) /// ``` @@ -109,7 +111,8 @@ impl Resource where S: 'static { /// Register a new route and add handler function. /// - /// This is sortcut for: + /// This is shortcut for: + /// /// ```rust,ignore /// Resource::resource("/", |r| r.route().f(index) /// ``` diff --git a/src/server.rs b/src/server.rs index d3fd36147..0a58449ff 100644 --- a/src/server.rs +++ b/src/server.rs @@ -24,7 +24,7 @@ use openssl::pkcs12::ParsedPkcs12; #[cfg(feature="alpn")] use tokio_openssl::{SslStream, SslAcceptorExt}; -use channel::{HttpChannel, HttpHandler}; +use channel::{HttpChannel, HttpHandler, IntoHttpHandler}; /// An HTTP Server @@ -47,8 +47,10 @@ impl Actor for HttpServer { impl HttpServer where H: HttpHandler { /// Create new http server with vec of http handlers - pub fn new>(handler: U) -> Self { - let apps: Vec<_> = handler.into_iter().collect(); + pub fn new>(handler: U) -> Self + where V: IntoHttpHandler + { + let apps: Vec<_> = handler.into_iter().map(|h| h.into_handler()).collect(); HttpServer {h: Rc::new(apps), io: PhantomData, diff --git a/src/ws.rs b/src/ws.rs index cbde61e59..551dee622 100644 --- a/src/ws.rs +++ b/src/ws.rs @@ -42,7 +42,7 @@ //! } //! //! fn main() { -//! Application::default("/") +//! Application::new("/") //! .resource("/ws/", |r| r.method(Method::GET).f(ws_index)) // <- register websocket route //! .finish(); //! } diff --git a/tests/test_server.rs b/tests/test_server.rs index 45d0f46e4..7704c3e35 100644 --- a/tests/test_server.rs +++ b/tests/test_server.rs @@ -11,20 +11,13 @@ use tokio_core::net::TcpListener; use actix::*; use actix_web::*; - -fn create_server() -> HttpServer> { - HttpServer::new( - vec![Application::default("/") - .resource("/", |r| - r.route().method(Method::GET).h(httpcodes::HTTPOk)) - .finish()]) -} - #[test] fn test_serve() { thread::spawn(|| { 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(); sys.run(); }); @@ -42,7 +35,9 @@ fn test_serve_incoming() { thread::spawn(move || { 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(); srv.serve_incoming::<_, ()>(tcp.incoming()).unwrap(); sys.run(); @@ -89,19 +84,17 @@ fn test_middlewares() { let sys = System::new("test"); HttpServer::new( - vec![Application::default("/") + vec![Application::new("/") .middleware(MiddlewareTest{start: act_num1, response: act_num2, finish: act_num3}) - .resource("/", |r| - r.route().method(Method::GET).h(httpcodes::HTTPOk)) + .resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk)) .finish()]) .serve::<_, ()>("127.0.0.1:58904").unwrap(); sys.run(); }); assert!(reqwest::get("http://localhost:58904/").unwrap().status().is_success()); - assert_eq!(num1.load(Ordering::Relaxed), 1); assert_eq!(num2.load(Ordering::Relaxed), 1); assert_eq!(num3.load(Ordering::Relaxed), 1);