1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-25 19:11:10 +00:00

refactor server router

This commit is contained in:
Nikolay Kim 2017-10-21 18:54:24 -07:00
parent 0d6e42e748
commit 6a33b65f02
10 changed files with 173 additions and 373 deletions

View file

@ -20,7 +20,7 @@ impl Route for MyRoute {
let multipart = match req.multipart(payload) { let multipart = match req.multipart(payload) {
Ok(mp) => mp, Ok(mp) => mp,
Err(e) => return Reply::reply(e), Err(e) => return e.into(),
}; };
// get Multipart stream // get Multipart stream
@ -68,13 +68,12 @@ fn main() {
let sys = actix::System::new("multipart-example"); let sys = actix::System::new("multipart-example");
HttpServer::new( HttpServer::new(
RoutingMap::default() vec![
.app("/", Application::default() Application::default("/")
.resource("/multipart", |r| { .resource("/multipart", |r| {
r.post::<MyRoute>(); r.post::<MyRoute>();
}) }).finish()
.finish()) ])
.finish())
.serve::<_, ()>("127.0.0.1:8080").unwrap(); .serve::<_, ()>("127.0.0.1:8080").unwrap();
let _ = sys.run(); let _ = sys.run();

View file

@ -212,22 +212,19 @@ fn main() {
// Create Http server with websocket support // Create Http server with websocket support
HttpServer::new( HttpServer::new(
RoutingMap::default() Application::builder("/", state)
.app("/", Application::builder(state) // redirect to websocket.html
// redirect to websocket.html .resource("/", |r|
.resource("/", |r| r.handler(Method::GET, |req, payload, state| {
r.handler(Method::GET, |req, payload, state| { httpcodes::HTTPFound
httpcodes::HTTPFound .builder()
.builder() .header("LOCATION", "/static/websocket.html")
.header("LOCATION", "/static/websocket.html") .body(Body::Empty)
.body(Body::Empty) }))
})) // websocket
// websocket .resource("/ws/", |r| r.get::<WsChatSession>())
.resource("/ws/", |r| r.get::<WsChatSession>()) // static resources
// static resources .route_handler("/static", StaticFiles::new("static/", true)))
.route_handler("/static", StaticFiles::new("static/", true))
.finish())
.finish())
.serve::<_, ()>("127.0.0.1:8080").unwrap(); .serve::<_, ()>("127.0.0.1:8080").unwrap();
let _ = sys.run(); let _ = sys.run();

View file

@ -58,17 +58,13 @@ impl Handler<ws::Message> for MyWebSocket {
} }
} }
fn main() { fn main() {
let sys = actix::System::new("ws-example"); let sys = actix::System::new("ws-example");
HttpServer::new( HttpServer::new(
RoutingMap::default() Application::default("/")
.resource("/ws/", |r| r.get::<MyWebSocket>()) .resource("/ws/", |r| r.get::<MyWebSocket>())
.app("/", Application::default() .route_handler("/", StaticFiles::new("static/", true)))
.route_handler("/", StaticFiles::new("static/", true))
.finish())
.finish())
.serve::<_, ()>("127.0.0.1:8080").unwrap(); .serve::<_, ()>("127.0.0.1:8080").unwrap();
println!("Started http server: 127.0.0.1:8080"); println!("Started http server: 127.0.0.1:8080");

View file

@ -5,55 +5,55 @@ use std::collections::HashMap;
use task::Task; use task::Task;
use payload::Payload; use payload::Payload;
use route::{RouteHandler, FnHandler}; use route::{RouteHandler, FnHandler};
use router::Handler;
use resource::Resource; use resource::Resource;
use recognizer::{RouteRecognizer, check_pattern}; use recognizer::{RouteRecognizer, check_pattern};
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use server::HttpHandler;
/// Application /// Application
pub struct Application<S=()> { pub struct Application<S> {
state: S, state: Rc<S>,
prefix: String,
default: Resource<S>, default: Resource<S>,
handlers: HashMap<String, Box<RouteHandler<S>>>, handlers: HashMap<String, Box<RouteHandler<S>>>,
resources: HashMap<String, Resource<S>>, router: RouteRecognizer<Resource<S>>,
} }
impl<S> Application<S> where S: 'static impl<S: 'static> HttpHandler for Application<S> {
{
pub(crate) fn prepare(self, prefix: String) -> Box<Handler> {
let mut handlers = HashMap::new();
let prefix = if prefix.ends_with('/') { prefix } else { prefix + "/" };
let mut routes = Vec::new(); fn prefix(&self) -> &str {
for (path, handler) in self.resources { &self.prefix
routes.push((path, handler)) }
}
for (path, mut handler) in self.handlers { fn handle(&self, req: HttpRequest, payload: Payload) -> Task {
let path = prefix.clone() + path.trim_left_matches('/'); if let Some((params, h)) = self.router.recognize(req.path()) {
handler.set_prefix(path.clone()); if let Some(params) = params {
handlers.insert(path, handler); h.handle(
req.with_match_info(params), payload, Rc::clone(&self.state))
} else {
h.handle(req, payload, Rc::clone(&self.state))
}
} else {
for (prefix, handler) in &self.handlers {
if req.path().starts_with(prefix) {
return handler.handle(req, payload, Rc::clone(&self.state))
}
}
self.default.handle(req, payload, Rc::clone(&self.state))
} }
Box::new(
InnerApplication {
state: Rc::new(self.state),
default: self.default,
handlers: handlers,
router: RouteRecognizer::new(prefix, routes) }
)
} }
} }
impl Application<()> { impl Application<()> {
/// Create default `ApplicationBuilder` with no state /// Create default `ApplicationBuilder` with no state
pub fn default() -> ApplicationBuilder<()> { pub fn default<T: ToString>(prefix: T) -> ApplicationBuilder<()> {
ApplicationBuilder { ApplicationBuilder {
parts: Some(ApplicationBuilderParts { parts: Some(ApplicationBuilderParts {
state: (), state: (),
prefix: prefix.to_string(),
default: Resource::default(), default: Resource::default(),
handlers: HashMap::new(), handlers: HashMap::new(),
resources: HashMap::new()}) resources: HashMap::new()})
@ -63,104 +63,29 @@ impl Application<()> {
impl<S> Application<S> where S: 'static { impl<S> Application<S> where S: 'static {
/// Create application builder /// Create application builder with specific state. State is shared with all
pub fn builder(state: S) -> ApplicationBuilder<S> { /// routes within same application and could be
/// accessed with `HttpContext::state()` method.
pub fn builder<T: ToString>(prefix: T, state: S) -> ApplicationBuilder<S> {
ApplicationBuilder { ApplicationBuilder {
parts: Some(ApplicationBuilderParts { parts: Some(ApplicationBuilderParts {
state: state, state: state,
prefix: prefix.to_string(),
default: Resource::default(), default: Resource::default(),
handlers: HashMap::new(), handlers: HashMap::new(),
resources: HashMap::new()}) resources: HashMap::new()})
} }
} }
/// Create http application with specific state. State is shared with all
/// routes within same application and could be
/// accessed with `HttpContext::state()` method.
pub fn new(state: S) -> Application<S> {
Application {
state: state,
default: Resource::default(),
handlers: HashMap::new(),
resources: HashMap::new(),
}
}
/// Add resource by path.
pub fn resource<P: ToString>(&mut self, path: P) -> &mut Resource<S>
{
let path = path.to_string();
// add resource
if !self.resources.contains_key(&path) {
check_pattern(&path);
self.resources.insert(path.clone(), Resource::default());
}
self.resources.get_mut(&path).unwrap()
}
/// This method register handler for specified path.
///
/// ```rust
/// extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let mut app = Application::new(());
///
/// app.handler("/test", |req, payload, state| {
/// httpcodes::HTTPOk
/// });
/// }
/// ```
pub fn handler<P, F, R>(&mut self, path: P, handler: F) -> &mut Self
where F: Fn(HttpRequest, Payload, &S) -> R + 'static,
R: Into<HttpResponse> + 'static,
P: ToString,
{
self.handlers.insert(path.to_string(), Box::new(FnHandler::new(handler)));
self
}
/// Add path handler
pub fn route_handler<H, P>(&mut self, path: P, h: H)
where H: RouteHandler<S> + 'static, P: ToString
{
let path = path.to_string();
// add resource
if self.handlers.contains_key(&path) {
panic!("Handler already registered: {:?}", path);
}
self.handlers.insert(path, Box::new(h));
}
/// Default resource is used if no matches route could be found.
pub fn default_resource(&mut self) -> &mut Resource<S> {
&mut self.default
}
} }
struct ApplicationBuilderParts<S> { struct ApplicationBuilderParts<S> {
state: S, state: S,
prefix: String,
default: Resource<S>, default: Resource<S>,
handlers: HashMap<String, Box<RouteHandler<S>>>, handlers: HashMap<String, Box<RouteHandler<S>>>,
resources: HashMap<String, Resource<S>>, resources: HashMap<String, Resource<S>>,
} }
impl<S> From<ApplicationBuilderParts<S>> for Application<S> {
fn from(b: ApplicationBuilderParts<S>) -> Self {
Application {
state: b.state,
default: b.default,
handlers: b.handlers,
resources: b.resources,
}
}
}
/// Application builder /// Application builder
pub struct ApplicationBuilder<S=()> { pub struct ApplicationBuilder<S=()> {
parts: Option<ApplicationBuilderParts<S>>, parts: Option<ApplicationBuilderParts<S>>,
@ -170,6 +95,22 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// Configure resource for specific path. /// Configure resource for specific path.
/// ///
/// Resource may have variable path also. For instance, a resource with
/// the path */a/{name}/c* would match all incoming requests with paths
/// such as */a/b/c*, */a/1/c*, and */a/etc/c*.
///
/// A variable part is specified in the form `{identifier}`, where
/// the identifier can be used later in a request handler to access the matched
/// value for that part. This is done by looking up the identifier
/// in the `Params` object returned by `Request.match_info()` method.
///
/// By default, each part matches the regular expression `[^{}/]+`.
///
/// You can also specify a custom regex in the form `{identifier:regex}`:
///
/// For instance, to route Get requests on any route matching `/users/{userid}/{friend}` and
/// store userid and friend in the exposed Params object:
///
/// ```rust /// ```rust
/// extern crate actix; /// extern crate actix;
/// extern crate actix_web; /// extern crate actix_web;
@ -193,7 +134,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// } /// }
/// } /// }
/// fn main() { /// fn main() {
/// let app = Application::default() /// let app = Application::default("/")
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.get::<MyRoute>(); /// r.get::<MyRoute>();
/// r.handler(Method::HEAD, |req, payload, state| { /// r.handler(Method::HEAD, |req, payload, state| {
@ -238,7 +179,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// use actix_web::*; /// use actix_web::*;
/// ///
/// fn main() { /// fn main() {
/// let app = Application::default() /// let app = Application::default("/")
/// .handler("/test", |req, payload, state| { /// .handler("/test", |req, payload, state| {
/// match *req.method() { /// match *req.method() {
/// Method::GET => httpcodes::HTTPOk, /// Method::GET => httpcodes::HTTPOk,
@ -277,36 +218,48 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// Construct application /// Construct application
pub fn finish(&mut self) -> Application<S> { pub fn finish(&mut self) -> Application<S> {
self.parts.take().expect("Use after finish").into() let parts = self.parts.take().expect("Use after finish");
let mut handlers = HashMap::new();
let prefix = if parts.prefix.ends_with('/') {
parts.prefix
} else {
parts.prefix + "/"
};
let mut routes = Vec::new();
for (path, handler) in parts.resources {
routes.push((path, handler))
}
for (path, mut handler) in parts.handlers {
let path = prefix.clone() + path.trim_left_matches('/');
handler.set_prefix(path.clone());
handlers.insert(path, handler);
}
Application {
state: Rc::new(parts.state),
prefix: prefix.clone(),
default: parts.default,
handlers: handlers,
router: RouteRecognizer::new(prefix, routes) }
} }
} }
pub(crate) impl<S: 'static> From<ApplicationBuilder<S>> for Application<S> {
struct InnerApplication<S> { fn from(mut builder: ApplicationBuilder<S>) -> Application<S> {
state: Rc<S>, builder.finish()
default: Resource<S>, }
handlers: HashMap<String, Box<RouteHandler<S>>>,
router: RouteRecognizer<Resource<S>>,
} }
impl<S: 'static> Iterator for ApplicationBuilder<S> {
type Item = Application<S>;
impl<S: 'static> Handler for InnerApplication<S> { fn next(&mut self) -> Option<Self::Item> {
if self.parts.is_some() {
fn handle(&self, req: HttpRequest, payload: Payload) -> Task { Some(self.finish())
if let Some((params, h)) = self.router.recognize(req.path()) {
if let Some(params) = params {
h.handle(
req.with_match_info(params), payload, Rc::clone(&self.state))
} else {
h.handle(req, payload, Rc::clone(&self.state))
}
} else { } else {
for (prefix, handler) in &self.handlers { None
if req.path().starts_with(prefix) {
return handler.handle(req, payload, Rc::clone(&self.state))
}
}
self.default.handle(req, payload, Rc::clone(&self.state))
} }
} }
} }

View file

@ -14,7 +14,6 @@ pub use application::{Application, ApplicationBuilder};
pub use httprequest::HttpRequest; pub use httprequest::HttpRequest;
pub use httpresponse::{Body, HttpResponse, HttpResponseBuilder}; pub use httpresponse::{Body, HttpResponse, HttpResponseBuilder};
pub use payload::{Payload, PayloadItem, PayloadError}; pub use payload::{Payload, PayloadItem, PayloadError};
pub use router::RoutingMap;
pub use resource::{Reply, Resource}; pub use resource::{Reply, Resource};
pub use route::{Route, RouteFactory, RouteHandler}; pub use route::{Route, RouteFactory, RouteHandler};
pub use recognizer::Params; pub use recognizer::Params;

View file

@ -36,7 +36,6 @@ mod payload;
mod resource; mod resource;
mod recognizer; mod recognizer;
mod route; mod route;
mod router;
mod reader; mod reader;
mod task; mod task;
mod staticfiles; mod staticfiles;
@ -53,7 +52,6 @@ pub use application::{Application, ApplicationBuilder};
pub use httprequest::{HttpRequest, UrlEncoded}; pub use httprequest::{HttpRequest, UrlEncoded};
pub use httpresponse::{Body, HttpResponse, HttpResponseBuilder}; pub use httpresponse::{Body, HttpResponse, HttpResponseBuilder};
pub use payload::{Payload, PayloadItem, PayloadError}; pub use payload::{Payload, PayloadItem, PayloadError};
pub use router::{Router, RoutingMap};
pub use route::{Route, RouteFactory, RouteHandler}; pub use route::{Route, RouteFactory, RouteHandler};
pub use resource::{Reply, Resource}; pub use resource::{Reply, Resource};
pub use recognizer::{Params, RouteRecognizer}; pub use recognizer::{Params, RouteRecognizer};

View file

@ -1,175 +0,0 @@
use std::rc::Rc;
use std::string::ToString;
use std::collections::HashMap;
use task::Task;
use payload::Payload;
use route::RouteHandler;
use resource::Resource;
use recognizer::{RouteRecognizer, check_pattern};
use application::Application;
use httpcodes::HTTPNotFound;
use httprequest::HttpRequest;
pub(crate) trait Handler: 'static {
fn handle(&self, req: HttpRequest, payload: Payload) -> Task;
}
/// Server routing map
pub struct Router {
apps: HashMap<String, Box<Handler>>,
resources: RouteRecognizer<Resource>,
}
impl Router {
pub(crate) fn call(&self, req: HttpRequest, payload: Payload) -> Task
{
if let Some((params, h)) = self.resources.recognize(req.path()) {
if let Some(params) = params {
h.handle(
req.with_match_info(params), payload, Rc::new(()))
} else {
h.handle(req, payload, Rc::new(()))
}
} else {
for (prefix, app) in &self.apps {
if req.path().starts_with(prefix) {
return app.handle(req, payload)
}
}
Task::reply(HTTPNotFound.response())
}
}
}
/// Request routing map builder
///
/// Resource may have variable path also. For instance, a resource with
/// the path */a/{name}/c* would match all incoming requests with paths
/// such as */a/b/c*, */a/1/c*, and */a/etc/c*.
///
/// A variable part is specified in the form `{identifier}`, where
/// the identifier can be used later in a request handler to access the matched
/// value for that part. This is done by looking up the identifier
/// in the `Params` object returned by `Request.match_info()` method.
///
/// By default, each part matches the regular expression `[^{}/]+`.
///
/// You can also specify a custom regex in the form `{identifier:regex}`:
///
/// For instance, to route Get requests on any route matching `/users/{userid}/{friend}` and
/// store userid and friend in the exposed Params object:
///
/// ```rust,ignore
/// let mut map = RoutingMap::default();
///
/// map.resource("/users/{userid}/{friend}", |r| r.get::<MyRoute>());
/// ```
pub struct RoutingMap {
parts: Option<RoutingMapParts>,
}
struct RoutingMapParts {
apps: HashMap<String, Box<Handler>>,
resources: HashMap<String, Resource>,
}
impl Default for RoutingMap {
fn default() -> Self {
RoutingMap {
parts: Some(RoutingMapParts {
apps: HashMap::new(),
resources: HashMap::new()}),
}
}
}
impl RoutingMap {
/// Add `Application` object with specific prefix.
/// Application prefixes all registered resources with specified prefix.
///
/// ```rust,ignore
///
/// struct MyRoute;
///
/// fn main() {
/// let mut router =
/// RoutingMap::default()
/// .app("/pre", Application::default()
/// .resource("/users/{userid}", |r| {
/// r.get::<MyRoute>();
/// r.post::<MyRoute>();
/// })
/// .finish()
/// ).finish();
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../pre/test` url.
pub fn app<P, S: 'static>(&mut self, prefix: P, app: Application<S>) -> &mut Self
where P: ToString
{
{
let parts = self.parts.as_mut().expect("Use after finish");
// we can not override registered resource
let prefix = prefix.to_string();
if parts.apps.contains_key(&prefix) {
panic!("Resource is registered: {}", prefix);
}
// add application
parts.apps.insert(prefix.clone(), app.prepare(prefix));
}
self
}
/// Configure resource for specific path.
///
/// ```rust,ignore
///
/// struct MyRoute;
///
/// fn main() {
/// RoutingMap::default().resource("/test", |r| {
/// r.post::<MyRoute>();
/// }).finish();
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../test` url.
pub fn resource<P, F>(&mut self, path: P, f: F) -> &mut Self
where F: FnOnce(&mut Resource<()>) + 'static,
P: ToString,
{
{
let parts = self.parts.as_mut().expect("Use after finish");
// add resource
let path = path.to_string();
if !parts.resources.contains_key(&path) {
check_pattern(&path);
parts.resources.insert(path.clone(), Resource::default());
}
// configure resource
f(parts.resources.get_mut(&path).unwrap());
}
self
}
/// Finish configuration and create `Router` instance
pub fn finish(&mut self) -> Router
{
let parts = self.parts.take().expect("Use after finish");
let mut routes = Vec::new();
for (path, resource) in parts.resources {
routes.push((path, resource))
}
Router {
apps: parts.apps,
resources: RouteRecognizer::new("/".to_owned(), routes),
}
}
}

View file

@ -11,34 +11,52 @@ use tokio_core::net::{TcpListener, TcpStream};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use task::{Task, RequestInfo}; use task::{Task, RequestInfo};
use router::Router;
use reader::{Reader, ReaderError}; use reader::{Reader, ReaderError};
use payload::Payload;
use httpcodes::HTTPNotFound;
use httprequest::HttpRequest;
/// Low level http request handler
pub trait HttpHandler: 'static {
/// Http handler prefix
fn prefix(&self) -> &str;
/// Handle request
fn handle(&self, req: HttpRequest, payload: Payload) -> Task;
}
/// An HTTP Server /// An HTTP Server
/// ///
/// `T` - async stream, anything that implements `AsyncRead` + `AsyncWrite`. /// `T` - async stream, anything that implements `AsyncRead` + `AsyncWrite`.
/// ///
/// `A` - peer address /// `A` - peer address
pub struct HttpServer<T, A> { ///
router: Rc<Router>, /// `H` - request handler
pub struct HttpServer<T, A, H> {
h: Rc<Vec<H>>,
io: PhantomData<T>, io: PhantomData<T>,
addr: PhantomData<A>, addr: PhantomData<A>,
} }
impl<T: 'static, A: 'static> Actor for HttpServer<T, A> { impl<T: 'static, A: 'static, H: 'static> Actor for HttpServer<T, A, H> {
type Context = Context<Self>; type Context = Context<Self>;
} }
impl<T, A> HttpServer<T, A> { impl<T, A, H> HttpServer<T, A, H> where H: HttpHandler
/// Create new http server with specified `RoutingMap` {
pub fn new(router: Router) -> Self { /// Create new http server with vec of http handlers
HttpServer {router: Rc::new(router), io: PhantomData, addr: PhantomData} pub fn new<U: IntoIterator<Item=H>>(handler: U) -> Self {
let apps: Vec<_> = handler.into_iter().map(|h| h.into()).collect();
HttpServer {h: Rc::new(apps),
io: PhantomData,
addr: PhantomData}
} }
} }
impl<T, A> HttpServer<T, A> impl<T, A, H> HttpServer<T, A, H>
where T: AsyncRead + AsyncWrite + 'static, where T: AsyncRead + AsyncWrite + 'static,
A: 'static A: 'static,
H: HttpHandler,
{ {
/// Start listening for incomming connections from stream. /// Start listening for incomming connections from stream.
pub fn serve_incoming<S, Addr>(self, stream: S) -> io::Result<Addr> pub fn serve_incoming<S, Addr>(self, stream: S) -> io::Result<Addr>
@ -52,7 +70,7 @@ impl<T, A> HttpServer<T, A>
} }
} }
impl HttpServer<TcpStream, net::SocketAddr> { impl<H: HttpHandler> HttpServer<TcpStream, net::SocketAddr, H> {
/// Start listening for incomming connections. /// Start listening for incomming connections.
/// ///
@ -99,18 +117,21 @@ impl<T, A> ResponseType for IoStream<T, A>
type Error = (); type Error = ();
} }
impl<T, A> StreamHandler<IoStream<T, A>, io::Error> for HttpServer<T, A> impl<T, A, H> StreamHandler<IoStream<T, A>, io::Error> for HttpServer<T, A, H>
where T: AsyncRead + AsyncWrite + 'static, A: 'static {}
impl<T, A> Handler<IoStream<T, A>, io::Error> for HttpServer<T, A>
where T: AsyncRead + AsyncWrite + 'static, where T: AsyncRead + AsyncWrite + 'static,
A: 'static A: 'static,
H: HttpHandler + 'static {}
impl<T, A, H> Handler<IoStream<T, A>, io::Error> for HttpServer<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static,
{ {
fn handle(&mut self, msg: IoStream<T, A>, _: &mut Context<Self>) fn handle(&mut self, msg: IoStream<T, A>, _: &mut Context<Self>)
-> Response<Self, IoStream<T, A>> -> Response<Self, IoStream<T, A>>
{ {
Arbiter::handle().spawn( Arbiter::handle().spawn(
HttpChannel{router: Rc::clone(&self.router), HttpChannel{router: Rc::clone(&self.h),
addr: msg.1, addr: msg.1,
stream: msg.0, stream: msg.0,
reader: Reader::new(), reader: Reader::new(),
@ -136,8 +157,8 @@ struct Entry {
const KEEPALIVE_PERIOD: u64 = 15; // seconds const KEEPALIVE_PERIOD: u64 = 15; // seconds
const MAX_PIPELINED_MESSAGES: usize = 16; const MAX_PIPELINED_MESSAGES: usize = 16;
pub struct HttpChannel<T: 'static, A: 'static> { pub struct HttpChannel<T: 'static, A: 'static, H: 'static> {
router: Rc<Router>, router: Rc<Vec<H>>,
#[allow(dead_code)] #[allow(dead_code)]
addr: A, addr: A,
stream: T, stream: T,
@ -155,14 +176,18 @@ pub struct HttpChannel<T: 'static, A: 'static> {
} }
}*/ }*/
impl<T, A> Actor for HttpChannel<T, A> impl<T, A, H> Actor for HttpChannel<T, A, H>
where T: AsyncRead + AsyncWrite + 'static, A: 'static where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static
{ {
type Context = Context<Self>; type Context = Context<Self>;
} }
impl<T, A> Future for HttpChannel<T, A> impl<T, A, H> Future for HttpChannel<T, A, H>
where T: AsyncRead + AsyncWrite + 'static, A: 'static where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static
{ {
type Item = (); type Item = ();
type Error = (); type Error = ();
@ -261,8 +286,16 @@ impl<T, A> Future for HttpChannel<T, A>
// start request processing // start request processing
let info = RequestInfo::new(&req); let info = RequestInfo::new(&req);
let mut task = None;
for h in self.router.iter() {
if req.path().starts_with(h.prefix()) {
task = Some(h.handle(req, payload));
break
}
}
self.items.push_back( self.items.push_back(
Entry {task: self.router.call(req, payload), Entry {task: task.unwrap_or_else(|| Task::reply(HTTPNotFound)),
req: info, req: info,
eof: false, eof: false,
error: false, error: false,

View file

@ -26,7 +26,7 @@ use httpcodes::{HTTPOk, HTTPNotFound, HTTPForbidden, HTTPInternalServerError};
/// use actix_web::*; /// use actix_web::*;
/// ///
/// fn main() { /// fn main() {
/// let app = Application::default() /// let app = Application::default("/")
/// .route_handler("/static", StaticFiles::new(".", true)) /// .route_handler("/static", StaticFiles::new(".", true))
/// .finish(); /// .finish();
/// } /// }

View file

@ -12,14 +12,14 @@ use futures::Future;
use tokio_core::net::{TcpStream, TcpListener}; use tokio_core::net::{TcpStream, TcpListener};
fn create_server<T, A>() -> HttpServer<T, A> { fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
HttpServer::new( HttpServer::new(
RoutingMap::default() vec![Application::default("/")
.resource("/", |r| .resource("/", |r|
r.handler(Method::GET, |_, _, _| { r.handler(Method::GET, |_, _, _| {
httpcodes::HTTPOk httpcodes::HTTPOk
})) }))
.finish()) .finish()])
} }
#[test] #[test]