1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-27 09:42:57 +01: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) {
Ok(mp) => mp,
Err(e) => return Reply::reply(e),
Err(e) => return e.into(),
};
// get Multipart stream
@ -68,13 +68,12 @@ fn main() {
let sys = actix::System::new("multipart-example");
HttpServer::new(
RoutingMap::default()
.app("/", Application::default()
.resource("/multipart", |r| {
r.post::<MyRoute>();
})
.finish())
.finish())
vec![
Application::default("/")
.resource("/multipart", |r| {
r.post::<MyRoute>();
}).finish()
])
.serve::<_, ()>("127.0.0.1:8080").unwrap();
let _ = sys.run();

View File

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

View File

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

View File

@ -5,55 +5,55 @@ use std::collections::HashMap;
use task::Task;
use payload::Payload;
use route::{RouteHandler, FnHandler};
use router::Handler;
use resource::Resource;
use recognizer::{RouteRecognizer, check_pattern};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use server::HttpHandler;
/// Application
pub struct Application<S=()> {
state: S,
pub struct Application<S> {
state: Rc<S>,
prefix: String,
default: Resource<S>,
handlers: HashMap<String, Box<RouteHandler<S>>>,
resources: HashMap<String, Resource<S>>,
router: RouteRecognizer<Resource<S>>,
}
impl<S> Application<S> where S: 'static
{
pub(crate) fn prepare(self, prefix: String) -> Box<Handler> {
let mut handlers = HashMap::new();
let prefix = if prefix.ends_with('/') { prefix } else { prefix + "/" };
impl<S: 'static> HttpHandler for Application<S> {
let mut routes = Vec::new();
for (path, handler) in self.resources {
routes.push((path, handler))
fn prefix(&self) -> &str {
&self.prefix
}
fn handle(&self, req: HttpRequest, payload: Payload) -> Task {
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 {
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))
}
for (path, mut handler) in self.handlers {
let path = prefix.clone() + path.trim_left_matches('/');
handler.set_prefix(path.clone());
handlers.insert(path, handler);
}
Box::new(
InnerApplication {
state: Rc::new(self.state),
default: self.default,
handlers: handlers,
router: RouteRecognizer::new(prefix, routes) }
)
}
}
impl Application<()> {
/// Create default `ApplicationBuilder` with no state
pub fn default() -> ApplicationBuilder<()> {
pub fn default<T: ToString>(prefix: T) -> ApplicationBuilder<()> {
ApplicationBuilder {
parts: Some(ApplicationBuilderParts {
state: (),
prefix: prefix.to_string(),
default: Resource::default(),
handlers: HashMap::new(),
resources: HashMap::new()})
@ -63,104 +63,29 @@ impl Application<()> {
impl<S> Application<S> where S: 'static {
/// Create application builder
pub fn builder(state: S) -> ApplicationBuilder<S> {
/// 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 builder<T: ToString>(prefix: T, state: S) -> ApplicationBuilder<S> {
ApplicationBuilder {
parts: Some(ApplicationBuilderParts {
state: state,
prefix: prefix.to_string(),
default: Resource::default(),
handlers: 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> {
state: S,
prefix: String,
default: Resource<S>,
handlers: HashMap<String, Box<RouteHandler<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
pub struct ApplicationBuilder<S=()> {
parts: Option<ApplicationBuilderParts<S>>,
@ -170,6 +95,22 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// 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
/// extern crate actix;
/// extern crate actix_web;
@ -193,7 +134,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// }
/// }
/// fn main() {
/// let app = Application::default()
/// let app = Application::default("/")
/// .resource("/test", |r| {
/// r.get::<MyRoute>();
/// r.handler(Method::HEAD, |req, payload, state| {
@ -238,7 +179,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::default()
/// let app = Application::default("/")
/// .handler("/test", |req, payload, state| {
/// match *req.method() {
/// Method::GET => httpcodes::HTTPOk,
@ -277,36 +218,48 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// Construct application
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)
struct InnerApplication<S> {
state: Rc<S>,
default: Resource<S>,
handlers: HashMap<String, Box<RouteHandler<S>>>,
router: RouteRecognizer<Resource<S>>,
impl<S: 'static> From<ApplicationBuilder<S>> for Application<S> {
fn from(mut builder: ApplicationBuilder<S>) -> Application<S> {
builder.finish()
}
}
impl<S: 'static> Iterator for ApplicationBuilder<S> {
type Item = Application<S>;
impl<S: 'static> Handler for InnerApplication<S> {
fn handle(&self, req: HttpRequest, payload: Payload) -> Task {
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))
}
fn next(&mut self) -> Option<Self::Item> {
if self.parts.is_some() {
Some(self.finish())
} 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))
None
}
}
}

View File

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

View File

@ -36,7 +36,6 @@ mod payload;
mod resource;
mod recognizer;
mod route;
mod router;
mod reader;
mod task;
mod staticfiles;
@ -53,7 +52,6 @@ pub use application::{Application, ApplicationBuilder};
pub use httprequest::{HttpRequest, UrlEncoded};
pub use httpresponse::{Body, HttpResponse, HttpResponseBuilder};
pub use payload::{Payload, PayloadItem, PayloadError};
pub use router::{Router, RoutingMap};
pub use route::{Route, RouteFactory, RouteHandler};
pub use resource::{Reply, Resource};
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 task::{Task, RequestInfo};
use router::Router;
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
///
/// `T` - async stream, anything that implements `AsyncRead` + `AsyncWrite`.
///
/// `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>,
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>;
}
impl<T, A> HttpServer<T, A> {
/// Create new http server with specified `RoutingMap`
pub fn new(router: Router) -> Self {
HttpServer {router: Rc::new(router), io: PhantomData, addr: PhantomData}
impl<T, A, H> HttpServer<T, A, H> where H: HttpHandler
{
/// Create new http server with vec of http handlers
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,
A: 'static
A: 'static,
H: HttpHandler,
{
/// Start listening for incomming connections from stream.
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.
///
@ -99,18 +117,21 @@ impl<T, A> ResponseType for IoStream<T, A>
type Error = ();
}
impl<T, A> StreamHandler<IoStream<T, A>, io::Error> for HttpServer<T, A>
where T: AsyncRead + AsyncWrite + 'static, A: 'static {}
impl<T, A> Handler<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
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>)
-> Response<Self, IoStream<T, A>>
{
Arbiter::handle().spawn(
HttpChannel{router: Rc::clone(&self.router),
HttpChannel{router: Rc::clone(&self.h),
addr: msg.1,
stream: msg.0,
reader: Reader::new(),
@ -136,8 +157,8 @@ struct Entry {
const KEEPALIVE_PERIOD: u64 = 15; // seconds
const MAX_PIPELINED_MESSAGES: usize = 16;
pub struct HttpChannel<T: 'static, A: 'static> {
router: Rc<Router>,
pub struct HttpChannel<T: 'static, A: 'static, H: 'static> {
router: Rc<Vec<H>>,
#[allow(dead_code)]
addr: A,
stream: T,
@ -155,14 +176,18 @@ pub struct HttpChannel<T: 'static, A: 'static> {
}
}*/
impl<T, A> Actor for HttpChannel<T, A>
where T: AsyncRead + AsyncWrite + 'static, A: 'static
impl<T, A, H> Actor for HttpChannel<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static
{
type Context = Context<Self>;
}
impl<T, A> Future for HttpChannel<T, A>
where T: AsyncRead + AsyncWrite + 'static, A: 'static
impl<T, A, H> Future for HttpChannel<T, A, H>
where T: AsyncRead + AsyncWrite + 'static,
A: 'static,
H: HttpHandler + 'static
{
type Item = ();
type Error = ();
@ -261,8 +286,16 @@ impl<T, A> Future for HttpChannel<T, A>
// start request processing
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(
Entry {task: self.router.call(req, payload),
Entry {task: task.unwrap_or_else(|| Task::reply(HTTPNotFound)),
req: info,
eof: false,
error: false,

View File

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

View File

@ -12,14 +12,14 @@ use futures::Future;
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(
RoutingMap::default()
.resource("/", |r|
r.handler(Method::GET, |_, _, _| {
httpcodes::HTTPOk
}))
.finish())
vec![Application::default("/")
.resource("/", |r|
r.handler(Method::GET, |_, _, _| {
httpcodes::HTTPOk
}))
.finish()])
}
#[test]