1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 08:22:59 +01:00

Merge pull request #399 from actix/router-refactor

Router refactoring
This commit is contained in:
Nikolay Kim 2018-07-15 19:16:07 +06:00 committed by GitHub
commit 30c84786b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 718 additions and 757 deletions

View File

@ -36,8 +36,8 @@ script:
fi fi
- | - |
if [[ "$TRAVIS_RUST_VERSION" == "stable" ]]; then if [[ "$TRAVIS_RUST_VERSION" == "stable" ]]; then
bash <(curl https://raw.githubusercontent.com/xd009642/tarpaulin/master/travis-install.sh) RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install cargo-tarpaulin
USE_SKEPTIC=1 cargo tarpaulin --features="alpn,tls" --out Xml --no-count cargo tarpaulin --features="alpn,tls" --out Xml --no-count
bash <(curl -s https://codecov.io/bash) bash <(curl -s https://codecov.io/bash)
echo "Uploaded code coverage" echo "Uploaded code coverage"
fi fi

View File

@ -1,16 +1,15 @@
use std::collections::HashMap;
use std::rc::Rc; use std::rc::Rc;
use handler::{AsyncResult, FromRequest, Handler, Responder, RouteHandler, WrapHandler}; use handler::{AsyncResult, FromRequest, Handler, Responder, WrapHandler};
use header::ContentEncoding; use header::ContentEncoding;
use http::{Method, StatusCode}; use http::Method;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use middleware::Middleware; use middleware::Middleware;
use pipeline::{HandlerType, Pipeline, PipelineHandler}; use pipeline::{Pipeline, PipelineHandler};
use pred::Predicate; use pred::Predicate;
use resource::Resource; use resource::Resource;
use router::{ResourceDef, RouteInfo, Router}; use router::{ResourceDef, Router};
use scope::Scope; use scope::Scope;
use server::{HttpHandler, HttpHandlerTask, IntoHttpHandler, Request}; use server::{HttpHandler, HttpHandlerTask, IntoHttpHandler, Request};
@ -19,7 +18,6 @@ pub struct HttpApplication<S = ()> {
state: Rc<S>, state: Rc<S>,
prefix: String, prefix: String,
prefix_len: usize, prefix_len: usize,
router: Router,
inner: Rc<Inner<S>>, inner: Rc<Inner<S>>,
filters: Option<Vec<Box<Predicate<S>>>>, filters: Option<Vec<Box<Predicate<S>>>>,
middlewares: Rc<Vec<Box<Middleware<S>>>>, middlewares: Rc<Vec<Box<Middleware<S>>>>,
@ -27,16 +25,8 @@ pub struct HttpApplication<S = ()> {
#[doc(hidden)] #[doc(hidden)]
pub struct Inner<S> { pub struct Inner<S> {
prefix: usize, router: Router<S>,
default: Rc<Resource<S>>,
encoding: ContentEncoding, encoding: ContentEncoding,
resources: Vec<Resource<S>>,
handlers: Vec<PrefixHandlerType<S>>,
}
enum PrefixHandlerType<S> {
Handler(String, Box<RouteHandler<S>>),
Scope(ResourceDef, Box<RouteHandler<S>>, Vec<Box<Predicate<S>>>),
} }
impl<S: 'static> PipelineHandler<S> for Inner<S> { impl<S: 'static> PipelineHandler<S> for Inner<S> {
@ -45,80 +35,21 @@ impl<S: 'static> PipelineHandler<S> for Inner<S> {
self.encoding self.encoding
} }
fn handle( fn handle(&self, req: &HttpRequest<S>) -> AsyncResult<HttpResponse> {
&self, req: &HttpRequest<S>, htype: HandlerType, self.router.handle(req)
) -> AsyncResult<HttpResponse> {
match htype {
HandlerType::Normal(idx) => {
if let Some(id) = self.resources[idx].get_route_id(req) {
return self.resources[idx].handle(id, req);
}
}
HandlerType::Handler(idx) => match self.handlers[idx] {
PrefixHandlerType::Handler(_, ref hnd) => return hnd.handle(req),
PrefixHandlerType::Scope(_, ref hnd, _) => return hnd.handle(req),
},
_ => (),
}
if let Some(id) = self.default.get_route_id(req) {
self.default.handle(id, req)
} else {
AsyncResult::ok(HttpResponse::new(StatusCode::NOT_FOUND))
}
} }
} }
impl<S: 'static> HttpApplication<S> { impl<S: 'static> HttpApplication<S> {
#[inline]
fn get_handler(&self, req: &Request) -> (RouteInfo, HandlerType) {
if let Some((idx, info)) = self.router.recognize(req) {
(info, HandlerType::Normal(idx))
} else {
'outer: for idx in 0..self.inner.handlers.len() {
match self.inner.handlers[idx] {
PrefixHandlerType::Handler(ref prefix, _) => {
let m = {
let path = &req.path()[self.inner.prefix..];
let path_len = path.len();
path.starts_with(prefix)
&& (path_len == prefix.len()
|| path.split_at(prefix.len()).1.starts_with('/'))
};
if m {
let prefix_len = (self.inner.prefix + prefix.len()) as u16;
let info = self.router.route_info(req, prefix_len);
return (info, HandlerType::Handler(idx));
}
}
PrefixHandlerType::Scope(ref pattern, _, ref filters) => {
if let Some(params) =
pattern.match_prefix_with_params(req, self.inner.prefix)
{
for filter in filters {
if !filter.check(req, &self.state) {
continue 'outer;
}
}
return (
self.router.route_info_params(params),
HandlerType::Handler(idx),
);
}
}
}
}
(self.router.default_route_info(), HandlerType::Default)
}
}
#[cfg(test)] #[cfg(test)]
pub(crate) fn run(&self, req: Request) -> AsyncResult<HttpResponse> { pub(crate) fn run(&self, req: Request) -> AsyncResult<HttpResponse> {
let (info, tp) = self.get_handler(&req); let info = self
.inner
.router
.recognize(&req, &self.state, self.prefix_len);
let req = HttpRequest::new(req, Rc::clone(&self.state), info); let req = HttpRequest::new(req, Rc::clone(&self.state), info);
self.inner.handle(&req, tp) self.inner.handle(&req)
} }
} }
@ -127,10 +58,14 @@ impl<S: 'static> HttpHandler for HttpApplication<S> {
fn handle(&self, msg: Request) -> Result<Pipeline<S, Inner<S>>, Request> { fn handle(&self, msg: Request) -> Result<Pipeline<S, Inner<S>>, Request> {
let m = { let m = {
if self.prefix_len == 0 {
true
} else {
let path = msg.path(); let path = msg.path();
path.starts_with(&self.prefix) path.starts_with(&self.prefix)
&& (path.len() == self.prefix_len && (path.len() == self.prefix_len
|| path.split_at(self.prefix_len).1.starts_with('/')) || path.split_at(self.prefix_len).1.starts_with('/'))
}
}; };
if m { if m {
if let Some(ref filters) = self.filters { if let Some(ref filters) = self.filters {
@ -141,10 +76,14 @@ impl<S: 'static> HttpHandler for HttpApplication<S> {
} }
} }
let (info, tp) = self.get_handler(&msg); let info = self
.inner
.router
.recognize(&msg, &self.state, self.prefix_len);
let inner = Rc::clone(&self.inner); let inner = Rc::clone(&self.inner);
let req = HttpRequest::new(msg, Rc::clone(&self.state), info); let req = HttpRequest::new(msg, Rc::clone(&self.state), info);
Ok(Pipeline::new(req, Rc::clone(&self.middlewares), inner, tp)) Ok(Pipeline::new(req, Rc::clone(&self.middlewares), inner))
} else { } else {
Err(msg) Err(msg)
} }
@ -154,10 +93,7 @@ impl<S: 'static> HttpHandler for HttpApplication<S> {
struct ApplicationParts<S> { struct ApplicationParts<S> {
state: S, state: S,
prefix: String, prefix: String,
default: Rc<Resource<S>>, router: Router<S>,
resources: Vec<(ResourceDef, Option<Resource<S>>)>,
handlers: Vec<PrefixHandlerType<S>>,
external: HashMap<String, ResourceDef>,
encoding: ContentEncoding, encoding: ContentEncoding,
middlewares: Vec<Box<Middleware<S>>>, middlewares: Vec<Box<Middleware<S>>>,
filters: Vec<Box<Predicate<S>>>, filters: Vec<Box<Predicate<S>>>,
@ -203,11 +139,8 @@ where
App { App {
parts: Some(ApplicationParts { parts: Some(ApplicationParts {
state, state,
prefix: "/".to_owned(), prefix: "".to_owned(),
default: Rc::new(Resource::default_not_found()), router: Router::new(),
resources: Vec::new(),
handlers: Vec::new(),
external: HashMap::new(),
middlewares: Vec::new(), middlewares: Vec::new(),
filters: Vec::new(), filters: Vec::new(),
encoding: ContentEncoding::Auto, encoding: ContentEncoding::Auto,
@ -315,35 +248,11 @@ where
R: Responder + 'static, R: Responder + 'static,
T: FromRequest<S> + 'static, T: FromRequest<S> + 'static,
{ {
{ self.parts
let parts: &mut ApplicationParts<S> = .as_mut()
self.parts.as_mut().expect("Use after finish"); .expect("Use after finish")
.router
let out = { .register_route(path, method, f);
// get resource handler
let mut iterator = parts.resources.iter_mut();
loop {
if let Some(&mut (ref pattern, ref mut handler)) = iterator.next() {
if let Some(ref mut handler) = *handler {
if pattern.pattern() == path {
handler.method(method).with(f);
break None;
}
}
} else {
let mut handler = Resource::default();
handler.method(method).with(f);
let pattern = ResourceDef::new(handler.get_name(), path);
break Some((pattern, Some(handler)));
}
}
};
if let Some(out) = out {
parts.resources.push(out);
}
}
self self
} }
@ -376,17 +285,12 @@ where
where where
F: FnOnce(Scope<S>) -> Scope<S>, F: FnOnce(Scope<S>) -> Scope<S>,
{ {
{ let scope = f(Scope::new(path));
let mut scope = Box::new(f(Scope::new())); self.parts
let parts = self.parts.as_mut().expect("Use after finish"); .as_mut()
.expect("Use after finish")
let filters = scope.take_filters(); .router
parts.handlers.push(PrefixHandlerType::Scope( .register_scope(scope);
ResourceDef::prefix("", &path),
scope,
filters,
));
}
self self
} }
@ -428,25 +332,25 @@ where
{ {
let parts = self.parts.as_mut().expect("Use after finish"); let parts = self.parts.as_mut().expect("Use after finish");
// add resource handler // create resource
let mut handler = Resource::default(); let mut resource = Resource::new(ResourceDef::new(path));
f(&mut handler);
let pattern = ResourceDef::new(handler.get_name(), path); // configure
parts.resources.push((pattern, Some(handler))); f(&mut resource);
parts.router.register_resource(resource);
} }
self self
} }
/// Configure resource for a specific path. /// Configure resource for a specific path.
#[doc(hidden)] #[doc(hidden)]
pub fn register_resource(&mut self, path: &str, resource: Resource<S>) { pub fn register_resource(&mut self, resource: Resource<S>) {
let pattern = ResourceDef::new(resource.get_name(), path);
self.parts self.parts
.as_mut() .as_mut()
.expect("Use after finish") .expect("Use after finish")
.resources .router
.push((pattern, Some(resource))); .register_resource(resource);
} }
/// Default resource to be used if no matching route could be found. /// Default resource to be used if no matching route could be found.
@ -454,12 +358,16 @@ where
where where
F: FnOnce(&mut Resource<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
{ // create and configure default resource
let parts = self.parts.as_mut().expect("Use after finish"); let mut resource = Resource::new(ResourceDef::new(""));
let default = Rc::get_mut(&mut parts.default) f(&mut resource);
.expect("Multiple App instance references are not allowed");
f(default); self.parts
} .as_mut()
.expect("Use after finish")
.router
.register_default_resource(resource.into());
self self
} }
@ -500,17 +408,11 @@ where
T: AsRef<str>, T: AsRef<str>,
U: AsRef<str>, U: AsRef<str>,
{ {
{ self.parts
let parts = self.parts.as_mut().expect("Use after finish"); .as_mut()
.expect("Use after finish")
if parts.external.contains_key(name.as_ref()) { .router
panic!("External resource {:?} is registered.", name.as_ref()); .register_external(name.as_ref(), ResourceDef::external(url.as_ref()));
}
parts.external.insert(
String::from(name.as_ref()),
ResourceDef::external(name.as_ref(), url.as_ref()),
);
}
self self
} }
@ -544,12 +446,11 @@ where
if path.len() > 1 && path.ends_with('/') { if path.len() > 1 && path.ends_with('/') {
path.pop(); path.pop();
} }
let parts = self.parts.as_mut().expect("Use after finish"); self.parts
.as_mut()
parts.handlers.push(PrefixHandlerType::Handler( .expect("Use after finish")
path, .router
Box::new(WrapHandler::new(handler)), .register_handler(&path, Box::new(WrapHandler::new(handler)), None);
));
} }
self self
} }
@ -601,33 +502,11 @@ where
pub fn finish(&mut self) -> HttpApplication<S> { pub fn finish(&mut self) -> HttpApplication<S> {
let mut parts = self.parts.take().expect("Use after finish"); let mut parts = self.parts.take().expect("Use after finish");
let prefix = parts.prefix.trim().trim_right_matches('/'); let prefix = parts.prefix.trim().trim_right_matches('/');
let (prefix, prefix_len) = if prefix.is_empty() { parts.router.finish();
("/".to_owned(), 0)
} else {
(prefix.to_owned(), prefix.len())
};
let mut resources = parts.resources;
for (_, pattern) in parts.external {
resources.push((pattern, None));
}
for handler in &mut parts.handlers {
if let PrefixHandlerType::Scope(_, ref mut route_handler, _) = handler {
if !route_handler.has_default_resource() {
route_handler.default_resource(Rc::clone(&parts.default));
}
};
}
let (router, resources) = Router::new(&prefix, resources);
let inner = Rc::new(Inner { let inner = Rc::new(Inner {
prefix: prefix_len, router: parts.router,
default: Rc::clone(&parts.default),
encoding: parts.encoding, encoding: parts.encoding,
handlers: parts.handlers,
resources,
}); });
let filters = if parts.filters.is_empty() { let filters = if parts.filters.is_empty() {
None None
@ -636,13 +515,12 @@ where
}; };
HttpApplication { HttpApplication {
state: Rc::new(parts.state),
router: router.clone(),
middlewares: Rc::new(parts.middlewares),
prefix,
prefix_len,
inner, inner,
filters, filters,
state: Rc::new(parts.state),
middlewares: Rc::new(parts.middlewares),
prefix: prefix.to_owned(),
prefix_len: prefix.len(),
} }
} }

View File

@ -719,12 +719,9 @@ mod tests {
fn test_request_extract() { fn test_request_extract() {
let req = TestRequest::with_uri("/name/user1/?id=test").finish(); let req = TestRequest::with_uri("/name/user1/?id=test").finish();
let mut resource = Resource::<()>::default(); let mut router = Router::<()>::new();
resource.name("index"); router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/")));
let mut routes = Vec::new(); let info = router.recognize(&req, &(), 0);
routes.push((ResourceDef::new("index", "/{key}/{value}/"), Some(resource)));
let (router, _) = Router::new("", routes);
let info = router.recognize(&req).unwrap().1;
let req = req.with_route_info(info); let req = req.with_route_info(info);
let s = Path::<MyStruct>::from_request(&req, &()).unwrap(); let s = Path::<MyStruct>::from_request(&req, &()).unwrap();
@ -738,8 +735,10 @@ mod tests {
let s = Query::<Id>::from_request(&req, &()).unwrap(); let s = Query::<Id>::from_request(&req, &()).unwrap();
assert_eq!(s.id, "test"); assert_eq!(s.id, "test");
let req = TestRequest::with_uri("/name/32/").finish_with_router(router.clone()); let mut router = Router::<()>::new();
let info = router.recognize(&req).unwrap().1; router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/")));
let req = TestRequest::with_uri("/name/32/").finish();
let info = router.recognize(&req, &(), 0);
let req = req.with_route_info(info); let req = req.with_route_info(info);
let s = Path::<Test2>::from_request(&req, &()).unwrap(); let s = Path::<Test2>::from_request(&req, &()).unwrap();
@ -757,29 +756,22 @@ mod tests {
#[test] #[test]
fn test_extract_path_single() { fn test_extract_path_single() {
let mut resource = Resource::<()>::default(); let mut router = Router::<()>::new();
resource.name("index"); router.register_resource(Resource::new(ResourceDef::new("/{value}/")));
let mut routes = Vec::new();
routes.push((ResourceDef::new("index", "/{value}/"), Some(resource)));
let (router, _) = Router::new("", routes);
let req = TestRequest::with_uri("/32/").finish_with_router(router.clone()); let req = TestRequest::with_uri("/32/").finish();
let info = router.recognize(&req).unwrap().1; let info = router.recognize(&req, &(), 0);
let req = req.with_route_info(info); let req = req.with_route_info(info);
assert_eq!(*Path::<i8>::from_request(&req, &()).unwrap(), 32); assert_eq!(*Path::<i8>::from_request(&req, &()).unwrap(), 32);
} }
#[test] #[test]
fn test_tuple_extract() { fn test_tuple_extract() {
let mut resource = Resource::<()>::default(); let mut router = Router::<()>::new();
resource.name("index"); router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/")));
let mut routes = Vec::new();
routes.push((ResourceDef::new("index", "/{key}/{value}/"), Some(resource)));
let (router, _) = Router::new("", routes);
let req = TestRequest::with_uri("/name/user1/?id=test") let req = TestRequest::with_uri("/name/user1/?id=test").finish();
.finish_with_router(router.clone()); let info = router.recognize(&req, &(), 0);
let info = router.recognize(&req).unwrap().1;
let req = req.with_route_info(info); let req = req.with_route_info(info);
let res = match <(Path<(String, String)>,)>::extract(&req).poll() { let res = match <(Path<(String, String)>,)>::extract(&req).poll() {

View File

@ -1,6 +1,5 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use std::ops::Deref; use std::ops::Deref;
use std::rc::Rc;
use futures::future::{err, ok, Future}; use futures::future::{err, ok, Future};
use futures::{Async, Poll}; use futures::{Async, Poll};
@ -9,7 +8,7 @@ use error::Error;
use http::StatusCode; use http::StatusCode;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use resource::Resource; use resource::DefaultResource;
/// Trait defines object that could be registered as route handler /// Trait defines object that could be registered as route handler
#[allow(unused_variables)] #[allow(unused_variables)]
@ -409,9 +408,11 @@ pub(crate) trait RouteHandler<S>: 'static {
false false
} }
fn default_resource(&mut self, _: Rc<Resource<S>>) { fn default_resource(&mut self, _: DefaultResource<S>) {
unimplemented!() unimplemented!()
} }
fn finish(&mut self) {}
} }
/// Route handler wrapper for Handler /// Route handler wrapper for Handler

View File

@ -92,7 +92,7 @@ impl<S> Handler<S> for NormalizePath {
// merge slashes // merge slashes
let p = self.re_merge.replace_all(req.path(), "/"); let p = self.re_merge.replace_all(req.path(), "/");
if p.len() != req.path().len() { if p.len() != req.path().len() {
if req.route().has_route(p.as_ref()) { if req.resource().has_route(p.as_ref()) {
let p = if !query.is_empty() { let p = if !query.is_empty() {
p + "?" + query p + "?" + query
} else { } else {
@ -105,7 +105,7 @@ impl<S> Handler<S> for NormalizePath {
// merge slashes and append trailing slash // merge slashes and append trailing slash
if self.append && !p.ends_with('/') { if self.append && !p.ends_with('/') {
let p = p.as_ref().to_owned() + "/"; let p = p.as_ref().to_owned() + "/";
if req.route().has_route(&p) { if req.resource().has_route(&p) {
let p = if !query.is_empty() { let p = if !query.is_empty() {
p + "?" + query p + "?" + query
} else { } else {
@ -120,7 +120,7 @@ impl<S> Handler<S> for NormalizePath {
// try to remove trailing slash // try to remove trailing slash
if p.ends_with('/') { if p.ends_with('/') {
let p = p.as_ref().trim_right_matches('/'); let p = p.as_ref().trim_right_matches('/');
if req.route().has_route(p) { if req.resource().has_route(p) {
let mut req = HttpResponse::build(self.redirect); let mut req = HttpResponse::build(self.redirect);
return if !query.is_empty() { return if !query.is_empty() {
req.header( req.header(
@ -135,7 +135,7 @@ impl<S> Handler<S> for NormalizePath {
} else if p.ends_with('/') { } else if p.ends_with('/') {
// try to remove trailing slash // try to remove trailing slash
let p = p.as_ref().trim_right_matches('/'); let p = p.as_ref().trim_right_matches('/');
if req.route().has_route(p) { if req.resource().has_route(p) {
let mut req = HttpResponse::build(self.redirect); let mut req = HttpResponse::build(self.redirect);
return if !query.is_empty() { return if !query.is_empty() {
req.header( req.header(
@ -151,7 +151,7 @@ impl<S> Handler<S> for NormalizePath {
// append trailing slash // append trailing slash
if self.append && !req.path().ends_with('/') { if self.append && !req.path().ends_with('/') {
let p = req.path().to_owned() + "/"; let p = req.path().to_owned() + "/";
if req.route().has_route(&p) { if req.resource().has_route(&p) {
let p = if !query.is_empty() { let p = if !query.is_empty() {
p + "?" + query p + "?" + query
} else { } else {

View File

@ -20,7 +20,7 @@ use httpresponse::{HttpResponse, HttpResponseBuilder};
use info::ConnectionInfo; use info::ConnectionInfo;
use param::Params; use param::Params;
use payload::Payload; use payload::Payload;
use router::{ResourceDef, RouteInfo}; use router::ResourceInfo;
use server::Request; use server::Request;
struct Query(HashMap<String, String>); struct Query(HashMap<String, String>);
@ -30,7 +30,7 @@ struct Cookies(Vec<Cookie<'static>>);
pub struct HttpRequest<S = ()> { pub struct HttpRequest<S = ()> {
req: Option<Request>, req: Option<Request>,
state: Rc<S>, state: Rc<S>,
route: RouteInfo, resource: ResourceInfo,
} }
impl<S> HttpMessage for HttpRequest<S> { impl<S> HttpMessage for HttpRequest<S> {
@ -61,10 +61,12 @@ impl<S> Deref for HttpRequest<S> {
impl<S> HttpRequest<S> { impl<S> HttpRequest<S> {
#[inline] #[inline]
pub(crate) fn new(req: Request, state: Rc<S>, route: RouteInfo) -> HttpRequest<S> { pub(crate) fn new(
req: Request, state: Rc<S>, resource: ResourceInfo,
) -> HttpRequest<S> {
HttpRequest { HttpRequest {
state, state,
route, resource,
req: Some(req), req: Some(req),
} }
} }
@ -75,15 +77,17 @@ impl<S> HttpRequest<S> {
HttpRequest { HttpRequest {
state, state,
req: self.req.as_ref().map(|r| r.clone()), req: self.req.as_ref().map(|r| r.clone()),
route: self.route.clone(), resource: self.resource.clone(),
} }
} }
#[inline] #[inline]
/// Construct new http request with new RouteInfo. /// Construct new http request with new RouteInfo.
pub(crate) fn with_route_info(&self, route: RouteInfo) -> HttpRequest<S> { pub(crate) fn with_route_info(&self, mut resource: ResourceInfo) -> HttpRequest<S> {
resource.merge(&self.resource);
HttpRequest { HttpRequest {
route, resource,
req: self.req.as_ref().map(|r| r.clone()), req: self.req.as_ref().map(|r| r.clone()),
state: self.state.clone(), state: self.state.clone(),
} }
@ -191,7 +195,7 @@ impl<S> HttpRequest<S> {
U: IntoIterator<Item = I>, U: IntoIterator<Item = I>,
I: AsRef<str>, I: AsRef<str>,
{ {
self.route.url_for(&self, name, elements) self.resource.url_for(&self, name, elements)
} }
/// Generate url for named resource /// Generate url for named resource
@ -205,14 +209,8 @@ impl<S> HttpRequest<S> {
/// This method returns reference to current `RouteInfo` object. /// This method returns reference to current `RouteInfo` object.
#[inline] #[inline]
pub fn route(&self) -> &RouteInfo { pub fn resource(&self) -> &ResourceInfo {
&self.route &self.resource
}
/// This method returns reference to matched `Resource` object.
#[inline]
pub fn resource(&self) -> Option<&ResourceDef> {
self.route.resource()
} }
/// Peer socket address /// Peer socket address
@ -298,7 +296,7 @@ impl<S> HttpRequest<S> {
/// access the matched value for that segment. /// access the matched value for that segment.
#[inline] #[inline]
pub fn match_info(&self) -> &Params { pub fn match_info(&self) -> &Params {
&self.route.match_info() &self.resource.match_info()
} }
/// Check if request requires connection upgrade /// Check if request requires connection upgrade
@ -329,7 +327,7 @@ impl<S> Clone for HttpRequest<S> {
HttpRequest { HttpRequest {
req: self.req.as_ref().map(|r| r.clone()), req: self.req.as_ref().map(|r| r.clone()),
state: self.state.clone(), state: self.state.clone(),
route: self.route.clone(), resource: self.resource.clone(),
} }
} }
} }
@ -422,26 +420,21 @@ mod tests {
#[test] #[test]
fn test_request_match_info() { fn test_request_match_info() {
let mut resource = Resource::<()>::default(); let mut router = Router::<()>::new();
resource.name("index"); router.register_resource(Resource::new(ResourceDef::new("/{key}/")));
let mut routes = Vec::new();
routes.push((ResourceDef::new("index", "/{key}/"), Some(resource)));
let (router, _) = Router::new("", routes);
let req = TestRequest::with_uri("/value/?id=test").finish(); let req = TestRequest::with_uri("/value/?id=test").finish();
let info = router.recognize(&req).unwrap().1; let info = router.recognize(&req, &(), 0);
assert_eq!(info.match_info().get("key"), Some("value")); assert_eq!(info.match_info().get("key"), Some("value"));
} }
#[test] #[test]
fn test_url_for() { fn test_url_for() {
let mut resource = Resource::<()>::default(); let mut router = Router::<()>::new();
let mut resource = Resource::new(ResourceDef::new("/user/{name}.{ext}"));
resource.name("index"); resource.name("index");
let routes = vec![( router.register_resource(resource);
ResourceDef::new("index", "/user/{name}.{ext}"),
Some(resource),
)];
let (router, _) = Router::new("/", routes);
let info = router.default_route_info(); let info = router.default_route_info();
assert!(info.has_route("/user/test.html")); assert!(info.has_route("/user/test.html"));
assert!(!info.has_route("/test/unknown")); assert!(!info.has_route("/test/unknown"));
@ -466,18 +459,19 @@ mod tests {
#[test] #[test]
fn test_url_for_with_prefix() { fn test_url_for_with_prefix() {
let mut resource = Resource::<()>::default(); let mut resource = Resource::new(ResourceDef::new("/user/{name}.html"));
resource.name("index"); resource.name("index");
let routes = vec![( let mut router = Router::<()>::new();
ResourceDef::new("index", "/user/{name}.html"), router.register_resource(resource);
Some(resource),
)]; let mut info = router.default_route_info();
let (router, _) = Router::new("/prefix/", routes); info.set_prefix(7);
let info = router.default_route_info();
assert!(info.has_route("/user/test.html")); assert!(info.has_route("/user/test.html"));
assert!(!info.has_route("/prefix/user/test.html")); assert!(!info.has_route("/prefix/user/test.html"));
let req = TestRequest::with_header(header::HOST, "www.rust-lang.org") let req = TestRequest::with_uri("/prefix/test")
.prefix(7)
.header(header::HOST, "www.rust-lang.org")
.finish_with_router(router); .finish_with_router(router);
let url = req.url_for("index", &["test"]); let url = req.url_for("index", &["test"]);
assert_eq!( assert_eq!(
@ -488,15 +482,18 @@ mod tests {
#[test] #[test]
fn test_url_for_static() { fn test_url_for_static() {
let mut resource = Resource::<()>::default(); let mut resource = Resource::new(ResourceDef::new("/index.html"));
resource.name("index"); resource.name("index");
let routes = vec![(ResourceDef::new("index", "/index.html"), Some(resource))]; let mut router = Router::<()>::new();
let (router, _) = Router::new("/prefix/", routes); router.register_resource(resource);
let info = router.default_route_info();
let mut info = router.default_route_info();
info.set_prefix(7);
assert!(info.has_route("/index.html")); assert!(info.has_route("/index.html"));
assert!(!info.has_route("/prefix/index.html")); assert!(!info.has_route("/prefix/index.html"));
let req = TestRequest::default() let req = TestRequest::with_uri("/prefix/test")
.prefix(7)
.header(header::HOST, "www.rust-lang.org") .header(header::HOST, "www.rust-lang.org")
.finish_with_router(router); .finish_with_router(router);
let url = req.url_for_static("index"); let url = req.url_for_static("index");
@ -508,13 +505,12 @@ mod tests {
#[test] #[test]
fn test_url_for_external() { fn test_url_for_external() {
let mut resource = Resource::<()>::default(); let mut router = Router::<()>::new();
resource.name("index"); router.register_external(
let routes = vec![( "youtube",
ResourceDef::external("youtube", "https://youtube.com/watch/{video_id}"), ResourceDef::external("https://youtube.com/watch/{video_id}"),
None, );
)];
let router = Router::new::<()>("", routes).0;
let info = router.default_route_info(); let info = router.default_route_info();
assert!(!info.has_route("https://youtube.com/watch/unknown")); assert!(!info.has_route("https://youtube.com/watch/unknown"));

View File

@ -246,7 +246,7 @@ pub mod dev {
pub use param::{FromParam, Params}; pub use param::{FromParam, Params};
pub use resource::Resource; pub use resource::Resource;
pub use route::Route; pub use route::Route;
pub use router::{ResourceDef, ResourceType, Router}; pub use router::{ResourceDef, ResourceInfo, ResourceType, Router};
} }
pub mod http { pub mod http {

View File

@ -60,6 +60,7 @@ use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use middleware::{Middleware, Response, Started}; use middleware::{Middleware, Response, Started};
use resource::Resource; use resource::Resource;
use router::ResourceDef;
use server::Request; use server::Request;
/// A set of errors that can occur during processing CORS /// A set of errors that can occur during processing CORS
@ -515,7 +516,7 @@ pub struct CorsBuilder<S = ()> {
methods: bool, methods: bool,
error: Option<http::Error>, error: Option<http::Error>,
expose_hdrs: HashSet<HeaderName>, expose_hdrs: HashSet<HeaderName>,
resources: Vec<(String, Resource<S>)>, resources: Vec<Resource<S>>,
app: Option<App<S>>, app: Option<App<S>>,
} }
@ -798,10 +799,10 @@ impl<S: 'static> CorsBuilder<S> {
F: FnOnce(&mut Resource<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
// add resource handler // add resource handler
let mut handler = Resource::default(); let mut resource = Resource::new(ResourceDef::new(path));
f(&mut handler); f(&mut resource);
self.resources.push((path.to_owned(), handler)); self.resources.push(resource);
self self
} }
@ -878,9 +879,9 @@ impl<S: 'static> CorsBuilder<S> {
.expect("CorsBuilder has to be constructed with Cors::for_app(app)"); .expect("CorsBuilder has to be constructed with Cors::for_app(app)");
// register resources // register resources
for (path, mut resource) in self.resources.drain(..) { for mut resource in self.resources.drain(..) {
cors.clone().register(&mut resource); cors.clone().register(&mut resource);
app.register_resource(&path, resource); app.register_resource(resource);
} }
app app

View File

@ -61,6 +61,10 @@ impl Params {
self.tail = tail; self.tail = tail;
} }
pub(crate) fn set_url(&mut self, url: Url) {
self.url = url;
}
pub(crate) fn add(&mut self, name: Rc<String>, value: ParamItem) { pub(crate) fn add(&mut self, name: Rc<String>, value: ParamItem) {
self.segments.push((name, value)); self.segments.push((name, value));
} }
@ -99,6 +103,11 @@ impl Params {
} }
} }
/// Get unprocessed part of path
pub fn unprocessed(&self) -> &str {
&self.url.path()[(self.tail as usize)..]
}
/// Get matched `FromParam` compatible parameter by name. /// Get matched `FromParam` compatible parameter by name.
/// ///
/// If keyed parameter is not available empty string is used as default /// If keyed parameter is not available empty string is used as default

View File

@ -16,19 +16,11 @@ use httpresponse::HttpResponse;
use middleware::{Finished, Middleware, Response, Started}; use middleware::{Finished, Middleware, Response, Started};
use server::{HttpHandlerTask, Writer, WriterState}; use server::{HttpHandlerTask, Writer, WriterState};
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub enum HandlerType {
Normal(usize),
Handler(usize),
Default,
}
#[doc(hidden)] #[doc(hidden)]
pub trait PipelineHandler<S> { pub trait PipelineHandler<S> {
fn encoding(&self) -> ContentEncoding; fn encoding(&self) -> ContentEncoding;
fn handle(&self, &HttpRequest<S>, HandlerType) -> AsyncResult<HttpResponse>; fn handle(&self, &HttpRequest<S>) -> AsyncResult<HttpResponse>;
} }
#[doc(hidden)] #[doc(hidden)]
@ -99,7 +91,6 @@ impl<S: 'static> PipelineInfo<S> {
impl<S: 'static, H: PipelineHandler<S>> Pipeline<S, H> { impl<S: 'static, H: PipelineHandler<S>> Pipeline<S, H> {
pub fn new( pub fn new(
req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>, handler: Rc<H>, req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>, handler: Rc<H>,
htype: HandlerType,
) -> Pipeline<S, H> { ) -> Pipeline<S, H> {
let mut info = PipelineInfo { let mut info = PipelineInfo {
req, req,
@ -109,7 +100,7 @@ impl<S: 'static, H: PipelineHandler<S>> Pipeline<S, H> {
disconnected: None, disconnected: None,
encoding: handler.encoding(), encoding: handler.encoding(),
}; };
let state = StartMiddlewares::init(&mut info, &mws, handler, htype); let state = StartMiddlewares::init(&mut info, &mws, handler);
Pipeline(info, state, mws) Pipeline(info, state, mws)
} }
@ -204,7 +195,6 @@ type Fut = Box<Future<Item = Option<HttpResponse>, Error = Error>>;
/// Middlewares start executor /// Middlewares start executor
struct StartMiddlewares<S, H> { struct StartMiddlewares<S, H> {
hnd: Rc<H>, hnd: Rc<H>,
htype: HandlerType,
fut: Option<Fut>, fut: Option<Fut>,
_s: PhantomData<S>, _s: PhantomData<S>,
} }
@ -212,7 +202,6 @@ struct StartMiddlewares<S, H> {
impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> { impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> {
fn init( fn init(
info: &mut PipelineInfo<S>, mws: &[Box<Middleware<S>>], hnd: Rc<H>, info: &mut PipelineInfo<S>, mws: &[Box<Middleware<S>>], hnd: Rc<H>,
htype: HandlerType,
) -> PipelineState<S, H> { ) -> PipelineState<S, H> {
// execute middlewares, we need this stage because middlewares could be // execute middlewares, we need this stage because middlewares could be
// non-async and we can move to next state immediately // non-async and we can move to next state immediately
@ -220,7 +209,7 @@ impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> {
loop { loop {
if info.count == len { if info.count == len {
let reply = hnd.handle(&info.req, htype); let reply = hnd.handle(&info.req);
return WaitingResponse::init(info, mws, reply); return WaitingResponse::init(info, mws, reply);
} else { } else {
match mws[info.count as usize].start(&info.req) { match mws[info.count as usize].start(&info.req) {
@ -231,7 +220,6 @@ impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> {
Ok(Started::Future(fut)) => { Ok(Started::Future(fut)) => {
return PipelineState::Starting(StartMiddlewares { return PipelineState::Starting(StartMiddlewares {
hnd, hnd,
htype,
fut: Some(fut), fut: Some(fut),
_s: PhantomData, _s: PhantomData,
}) })
@ -261,7 +249,7 @@ impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> {
} }
loop { loop {
if info.count == len { if info.count == len {
let reply = self.hnd.handle(&info.req, self.htype); let reply = self.hnd.handle(&info.req);
return Some(WaitingResponse::init(info, mws, reply)); return Some(WaitingResponse::init(info, mws, reply));
} else { } else {
let res = mws[info.count as usize].start(&info.req); let res = mws[info.count as usize].start(&info.req);

View File

@ -1,4 +1,4 @@
use std::marker::PhantomData; use std::ops::Deref;
use std::rc::Rc; use std::rc::Rc;
use futures::Future; use futures::Future;
@ -12,6 +12,7 @@ use httpresponse::HttpResponse;
use middleware::Middleware; use middleware::Middleware;
use pred; use pred;
use route::Route; use route::Route;
use router::ResourceDef;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub(crate) struct RouteId(usize); pub(crate) struct RouteId(usize);
@ -37,40 +38,34 @@ pub(crate) struct RouteId(usize);
/// .finish(); /// .finish();
/// } /// }
pub struct Resource<S = ()> { pub struct Resource<S = ()> {
name: String, rdef: ResourceDef,
state: PhantomData<S>,
routes: SmallVec<[Route<S>; 3]>, routes: SmallVec<[Route<S>; 3]>,
middlewares: Rc<Vec<Box<Middleware<S>>>>, middlewares: Rc<Vec<Box<Middleware<S>>>>,
} }
impl<S> Default for Resource<S> {
fn default() -> Self {
Resource {
name: String::new(),
state: PhantomData,
routes: SmallVec::new(),
middlewares: Rc::new(Vec::new()),
}
}
}
impl<S> Resource<S> { impl<S> Resource<S> {
pub(crate) fn default_not_found() -> Self { /// Create new resource with specified resource definition
pub fn new(rdef: ResourceDef) -> Self {
Resource { Resource {
name: String::new(), rdef,
state: PhantomData,
routes: SmallVec::new(), routes: SmallVec::new(),
middlewares: Rc::new(Vec::new()), middlewares: Rc::new(Vec::new()),
} }
} }
/// Name of the resource
pub(crate) fn get_name(&self) -> &str {
self.rdef.name()
}
/// Set resource name /// Set resource name
pub fn name<T: Into<String>>(&mut self, name: T) { pub fn name(&mut self, name: &str) {
self.name = name.into(); self.rdef.set_name(name);
} }
pub(crate) fn get_name(&self) -> &str { /// Resource definition
&self.name pub fn rdef(&self) -> &ResourceDef {
&self.rdef
} }
} }
@ -303,3 +298,26 @@ impl<S: 'static> Resource<S> {
} }
} }
} }
/// Default resource
pub struct DefaultResource<S>(Rc<Resource<S>>);
impl<S> Deref for DefaultResource<S> {
type Target = Resource<S>;
fn deref(&self) -> &Resource<S> {
self.0.as_ref()
}
}
impl<S> Clone for DefaultResource<S> {
fn clone(&self) -> Self {
DefaultResource(self.0.clone())
}
}
impl<S> From<Resource<S>> for DefaultResource<S> {
fn from(res: Resource<S>) -> Self {
DefaultResource(Rc::new(res))
}
}

View File

@ -1,3 +1,4 @@
use std::cmp::min;
use std::collections::HashMap; use std::collections::HashMap;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::rc::Rc; use std::rc::Rc;
@ -6,37 +7,76 @@ use regex::{escape, Regex};
use url::Url; use url::Url;
use error::UrlGenerationError; use error::UrlGenerationError;
use handler::{AsyncResult, FromRequest, Responder, RouteHandler};
use http::{Method, StatusCode};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use param::{ParamItem, Params}; use param::{ParamItem, Params};
use resource::Resource; use pred::Predicate;
use resource::{DefaultResource, Resource};
use scope::Scope;
use server::Request; use server::Request;
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) enum RouterResource { pub(crate) enum ResourceId {
Notset, Default,
Normal(u16), Normal(u16),
} }
/// Interface for application router. enum ResourcePattern<S> {
pub struct Router(Rc<Inner>); Resource(ResourceDef),
Handler(ResourceDef, Option<Vec<Box<Predicate<S>>>>),
#[derive(Clone)] Scope(ResourceDef, Vec<Box<Predicate<S>>>),
pub struct RouteInfo {
router: Rc<Inner>,
resource: RouterResource,
params: Params,
} }
impl RouteInfo { enum ResourceItem<S> {
/// This method returns reference to matched `Resource` object. Resource(Resource<S>),
Handler(Box<RouteHandler<S>>),
Scope(Scope<S>),
}
/// Interface for application router.
pub struct Router<S> {
defs: Rc<Inner>,
patterns: Vec<ResourcePattern<S>>,
resources: Vec<ResourceItem<S>>,
default: Option<DefaultResource<S>>,
}
/// Information about current resource
#[derive(Clone)]
pub struct ResourceInfo {
router: Rc<Inner>,
resource: ResourceId,
params: Params,
prefix: u16,
}
impl ResourceInfo {
/// Name os the resource
#[inline] #[inline]
pub fn resource(&self) -> Option<&ResourceDef> { pub fn name(&self) -> &str {
if let RouterResource::Normal(idx) = self.resource { if let ResourceId::Normal(idx) = self.resource {
self.router.patterns[idx as usize].name()
} else {
""
}
}
/// This method returns reference to matched `ResourceDef` object.
#[inline]
pub fn rdef(&self) -> Option<&ResourceDef> {
if let ResourceId::Normal(idx) = self.resource {
Some(&self.router.patterns[idx as usize]) Some(&self.router.patterns[idx as usize])
} else { } else {
None None
} }
} }
pub(crate) fn set_prefix(&mut self, prefix: u16) {
self.prefix = prefix;
}
/// Get a reference to the Params object. /// Get a reference to the Params object.
/// ///
/// Params is a container for url parameters. /// Params is a container for url parameters.
@ -49,18 +89,15 @@ impl RouteInfo {
} }
#[inline] #[inline]
pub(crate) fn merge(&self, params: &Params) -> RouteInfo { pub(crate) fn merge(&mut self, info: &ResourceInfo) {
let mut p = self.params.clone(); let mut p = info.params.clone();
p.set_tail(params.tail); p.set_tail(self.params.tail);
for item in &params.segments { for item in &self.params.segments {
p.add(item.0.clone(), item.1.clone()); p.add(item.0.clone(), item.1.clone());
} }
RouteInfo { self.prefix = info.params.tail;
params: p, self.params = p;
router: self.router.clone(),
resource: self.resource,
}
} }
/// Generate url for named resource /// Generate url for named resource
@ -75,7 +112,8 @@ impl RouteInfo {
I: AsRef<str>, I: AsRef<str>,
{ {
if let Some(pattern) = self.router.named.get(name) { if let Some(pattern) = self.router.named.get(name) {
let path = pattern.0.resource_path(elements, &self.router.prefix)?; let path =
pattern.resource_path(elements, &req.path()[..(self.prefix as usize)])?;
if path.starts_with('/') { if path.starts_with('/') {
let conn = req.connection_info(); let conn = req.connection_info();
Ok(Url::parse(&format!( Ok(Url::parse(&format!(
@ -111,104 +149,248 @@ impl RouteInfo {
} }
struct Inner { struct Inner {
prefix: String, named: HashMap<String, ResourceDef>,
prefix_len: usize,
named: HashMap<String, (ResourceDef, bool)>,
patterns: Vec<ResourceDef>, patterns: Vec<ResourceDef>,
} }
impl Router { impl<S: 'static> Default for Router<S> {
/// Create new router fn default() -> Self {
pub fn new<S>( Router::new()
prefix: &str, map: Vec<(ResourceDef, Option<Resource<S>>)>,
) -> (Router, Vec<Resource<S>>) {
let prefix = prefix.trim().trim_right_matches('/').to_owned();
let mut named = HashMap::new();
let mut patterns = Vec::new();
let mut resources = Vec::new();
for (pattern, resource) in map {
if !pattern.name().is_empty() {
let name = pattern.name().into();
named.insert(name, (pattern.clone(), resource.is_none()));
}
if let Some(resource) = resource {
patterns.push(pattern);
resources.push(resource);
}
}
let prefix_len = prefix.len();
(
Router(Rc::new(Inner {
prefix,
prefix_len,
named,
patterns,
})),
resources,
)
}
/// Router prefix
#[inline]
pub fn prefix(&self) -> &str {
&self.0.prefix
}
pub(crate) fn route_info(&self, req: &Request, prefix: u16) -> RouteInfo {
let mut params = Params::with_url(req.url());
params.set_tail(prefix);
RouteInfo {
params,
router: self.0.clone(),
resource: RouterResource::Notset,
}
}
pub(crate) fn route_info_params(&self, params: Params) -> RouteInfo {
RouteInfo {
params,
router: self.0.clone(),
resource: RouterResource::Notset,
}
}
pub(crate) fn default_route_info(&self) -> RouteInfo {
RouteInfo {
router: self.0.clone(),
resource: RouterResource::Notset,
params: Params::new(),
}
}
/// Query for matched resource
pub fn recognize(&self, req: &Request) -> Option<(usize, RouteInfo)> {
if self.0.prefix_len > req.path().len() {
return None;
}
for (idx, pattern) in self.0.patterns.iter().enumerate() {
if let Some(params) = pattern.match_with_params(req, self.0.prefix_len, true)
{
return Some((
idx,
RouteInfo {
params,
router: self.0.clone(),
resource: RouterResource::Normal(idx as u16),
},
));
}
}
None
} }
} }
impl Clone for Router { impl<S: 'static> Router<S> {
fn clone(&self) -> Router { pub(crate) fn new() -> Self {
Router(Rc::clone(&self.0)) Router {
defs: Rc::new(Inner {
named: HashMap::new(),
patterns: Vec::new(),
}),
resources: Vec::new(),
patterns: Vec::new(),
default: None,
}
}
#[inline]
pub(crate) fn route_info_params(&self, idx: u16, params: Params) -> ResourceInfo {
ResourceInfo {
params,
prefix: 0,
router: self.defs.clone(),
resource: ResourceId::Normal(idx),
}
}
#[cfg(test)]
pub(crate) fn route_info(&self, req: &Request, prefix: u16) -> ResourceInfo {
let mut params = Params::with_url(req.url());
params.set_tail(prefix);
ResourceInfo {
params,
prefix: 0,
router: self.defs.clone(),
resource: ResourceId::Default,
}
}
#[cfg(test)]
pub(crate) fn default_route_info(&self) -> ResourceInfo {
ResourceInfo {
params: Params::new(),
router: self.defs.clone(),
resource: ResourceId::Default,
prefix: 0,
}
}
pub(crate) fn register_resource(&mut self, resource: Resource<S>) {
{
let inner = Rc::get_mut(&mut self.defs).unwrap();
let name = resource.get_name();
if !name.is_empty() {
assert!(
!inner.named.contains_key(name),
"Named resource {:?} is registered.",
name
);
inner.named.insert(name.to_owned(), resource.rdef().clone());
}
inner.patterns.push(resource.rdef().clone());
}
self.patterns
.push(ResourcePattern::Resource(resource.rdef().clone()));
self.resources.push(ResourceItem::Resource(resource));
}
pub(crate) fn register_scope(&mut self, mut scope: Scope<S>) {
Rc::get_mut(&mut self.defs)
.unwrap()
.patterns
.push(scope.rdef().clone());
let filters = scope.take_filters();
self.patterns
.push(ResourcePattern::Scope(scope.rdef().clone(), filters));
self.resources.push(ResourceItem::Scope(scope));
}
pub(crate) fn register_handler(
&mut self, path: &str, hnd: Box<RouteHandler<S>>,
filters: Option<Vec<Box<Predicate<S>>>>,
) {
let rdef = ResourceDef::prefix(path);
Rc::get_mut(&mut self.defs)
.unwrap()
.patterns
.push(rdef.clone());
self.resources.push(ResourceItem::Handler(hnd));
self.patterns.push(ResourcePattern::Handler(rdef, filters));
}
pub(crate) fn has_default_resource(&self) -> bool {
self.default.is_some()
}
pub(crate) fn register_default_resource(&mut self, resource: DefaultResource<S>) {
self.default = Some(resource);
}
pub(crate) fn finish(&mut self) {
if let Some(ref default) = self.default {
for resource in &mut self.resources {
match resource {
ResourceItem::Resource(_) => (),
ResourceItem::Scope(scope) => {
if !scope.has_default_resource() {
scope.default_resource(default.clone());
}
scope.finish()
}
ResourceItem::Handler(hnd) => {
if !hnd.has_default_resource() {
hnd.default_resource(default.clone());
}
hnd.finish()
}
}
}
}
}
pub(crate) fn register_external(&mut self, name: &str, rdef: ResourceDef) {
let inner = Rc::get_mut(&mut self.defs).unwrap();
assert!(
!inner.named.contains_key(name),
"Named resource {:?} is registered.",
name
);
inner.named.insert(name.to_owned(), rdef);
}
pub(crate) fn register_route<T, F, R>(&mut self, path: &str, method: Method, f: F)
where
F: Fn(T) -> R + 'static,
R: Responder + 'static,
T: FromRequest<S> + 'static,
{
let out = {
// get resource handler
let mut iterator = self.resources.iter_mut();
loop {
if let Some(ref mut resource) = iterator.next() {
if let ResourceItem::Resource(ref mut resource) = resource {
if resource.rdef().pattern() == path {
resource.method(method).with(f);
break None;
}
}
} else {
let mut resource = Resource::new(ResourceDef::new(path));
resource.method(method).with(f);
break Some(resource);
}
}
};
if let Some(out) = out {
self.register_resource(out);
}
}
/// Handle request
pub fn handle(&self, req: &HttpRequest<S>) -> AsyncResult<HttpResponse> {
let resource = match req.resource().resource {
ResourceId::Normal(idx) => &self.resources[idx as usize],
ResourceId::Default => {
if let Some(ref default) = self.default {
if let Some(id) = default.get_route_id(req) {
return default.handle(id, req);
}
}
return AsyncResult::ok(HttpResponse::new(StatusCode::NOT_FOUND));
}
};
match resource {
ResourceItem::Resource(ref resource) => {
if let Some(id) = resource.get_route_id(req) {
return resource.handle(id, req);
}
if let Some(ref default) = self.default {
if let Some(id) = default.get_route_id(req) {
return default.handle(id, req);
}
}
}
ResourceItem::Handler(hnd) => return hnd.handle(req),
ResourceItem::Scope(hnd) => return hnd.handle(req),
}
AsyncResult::ok(HttpResponse::new(StatusCode::NOT_FOUND))
}
/// Query for matched resource
pub fn recognize(&self, req: &Request, state: &S, tail: usize) -> ResourceInfo {
if tail <= req.path().len() {
'outer: for (idx, resource) in self.patterns.iter().enumerate() {
match resource {
ResourcePattern::Resource(rdef) => {
if let Some(params) = rdef.match_with_params(req, tail) {
return self.route_info_params(idx as u16, params);
}
}
ResourcePattern::Handler(rdef, filters) => {
if let Some(params) = rdef.match_prefix_with_params(req, tail) {
if let Some(ref filters) = filters {
for filter in filters {
if !filter.check(req, state) {
continue 'outer;
}
}
}
return self.route_info_params(idx as u16, params);
}
}
ResourcePattern::Scope(rdef, filters) => {
if let Some(params) = rdef.match_prefix_with_params(req, tail) {
for filter in filters {
if !filter.check(req, state) {
continue 'outer;
}
}
return self.route_info_params(idx as u16, params);
}
}
}
}
}
ResourceInfo {
prefix: tail as u16,
params: Params::new(),
router: self.defs.clone(),
resource: ResourceId::Default,
}
} }
} }
@ -252,8 +434,8 @@ impl ResourceDef {
/// Parse path pattern and create new `Resource` instance. /// Parse path pattern and create new `Resource` instance.
/// ///
/// Panics if path pattern is wrong. /// Panics if path pattern is wrong.
pub fn new(name: &str, path: &str) -> Self { pub fn new(path: &str) -> Self {
ResourceDef::with_prefix(name, path, "/", false) ResourceDef::with_prefix(path, "/", false)
} }
/// Parse path pattern and create new `Resource` instance. /// Parse path pattern and create new `Resource` instance.
@ -261,21 +443,21 @@ impl ResourceDef {
/// Use `prefix` type instead of `static`. /// Use `prefix` type instead of `static`.
/// ///
/// Panics if path regex pattern is wrong. /// Panics if path regex pattern is wrong.
pub fn prefix(name: &str, path: &str) -> Self { pub fn prefix(path: &str) -> Self {
ResourceDef::with_prefix(name, path, "/", true) ResourceDef::with_prefix(path, "/", true)
} }
/// Construct external resource /// Construct external resource
/// ///
/// Panics if path pattern is wrong. /// Panics if path pattern is wrong.
pub fn external(name: &str, path: &str) -> Self { pub fn external(path: &str) -> Self {
let mut resource = ResourceDef::with_prefix(name, path, "/", false); let mut resource = ResourceDef::with_prefix(path, "/", false);
resource.rtp = ResourceType::External; resource.rtp = ResourceType::External;
resource resource
} }
/// Parse path pattern and create new `Resource` instance with custom prefix /// Parse path pattern and create new `Resource` instance with custom prefix
pub fn with_prefix(name: &str, path: &str, prefix: &str, for_prefix: bool) -> Self { pub fn with_prefix(path: &str, prefix: &str, for_prefix: bool) -> Self {
let (pattern, elements, is_dynamic, len) = let (pattern, elements, is_dynamic, len) =
ResourceDef::parse(path, prefix, for_prefix); ResourceDef::parse(path, prefix, for_prefix);
@ -299,20 +481,25 @@ impl ResourceDef {
ResourceDef { ResourceDef {
tp, tp,
elements, elements,
name: name.into(), name: "".to_string(),
rtp: ResourceType::Normal, rtp: ResourceType::Normal,
pattern: path.to_owned(), pattern: path.to_owned(),
} }
} }
/// Name of the resource /// Resource type
pub fn rtype(&self) -> ResourceType {
self.rtp
}
/// Resource name
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
&self.name &self.name
} }
/// Resource type /// Resource name
pub fn rtype(&self) -> ResourceType { pub(crate) fn set_name(&mut self, name: &str) {
self.rtp self.name = name.to_owned();
} }
/// Path pattern of the resource /// Path pattern of the resource
@ -330,19 +517,8 @@ impl ResourceDef {
} }
/// Are the given path and parameters a match against this resource? /// Are the given path and parameters a match against this resource?
pub fn match_with_params( pub fn match_with_params(&self, req: &Request, plen: usize) -> Option<Params> {
&self, req: &Request, plen: usize, insert: bool,
) -> Option<Params> {
let path = &req.path()[plen..]; let path = &req.path()[plen..];
if insert {
if path.is_empty() {
"/"
} else {
path
}
} else {
path
};
match self.tp { match self.tp {
PatternType::Static(ref s) => if s != path { PatternType::Static(ref s) => if s != path {
@ -443,7 +619,7 @@ impl ResourceDef {
return None; return None;
}; };
let mut params = Params::with_url(req.url()); let mut params = Params::with_url(req.url());
params.set_tail((plen + len) as u16); params.set_tail(min(req.path().len(), plen + len) as u16);
Some(params) Some(params)
} }
} }
@ -592,218 +768,184 @@ mod tests {
#[test] #[test]
fn test_recognizer10() { fn test_recognizer10() {
let routes = vec![ let mut router = Router::<()>::new();
(ResourceDef::new("", "/name"), Some(Resource::default())), router.register_resource(Resource::new(ResourceDef::new("/name")));
( router.register_resource(Resource::new(ResourceDef::new("/name/{val}")));
ResourceDef::new("", "/name/{val}"), router.register_resource(Resource::new(ResourceDef::new(
Some(Resource::default()), "/name/{val}/index.html",
), )));
( router.register_resource(Resource::new(ResourceDef::new("/file/{file}.{ext}")));
ResourceDef::new("", "/name/{val}/index.html"), router.register_resource(Resource::new(ResourceDef::new(
Some(Resource::default()), "/v{val}/{val2}/index.html",
), )));
( router.register_resource(Resource::new(ResourceDef::new("/v/{tail:.*}")));
ResourceDef::new("", "/file/{file}.{ext}"), router.register_resource(Resource::new(ResourceDef::new("/test2/{test}.html")));
Some(Resource::default()), router.register_resource(Resource::new(ResourceDef::new("{test}/index.html")));
),
(
ResourceDef::new("", "/v{val}/{val2}/index.html"),
Some(Resource::default()),
),
(
ResourceDef::new("", "/v/{tail:.*}"),
Some(Resource::default()),
),
(
ResourceDef::new("", "/test2/{test}.html"),
Some(Resource::default()),
),
(
ResourceDef::new("", "{test}/index.html"),
Some(Resource::default()),
),
];
let (rec, _) = Router::new::<()>("", routes);
let req = TestRequest::with_uri("/name").finish(); let req = TestRequest::with_uri("/name").finish();
assert_eq!(rec.recognize(&req).unwrap().0, 0); let info = router.recognize(&req, &(), 0);
assert!(req.match_info().is_empty()); assert_eq!(info.resource, ResourceId::Normal(0));
assert!(info.match_info().is_empty());
let req = TestRequest::with_uri("/name/value").finish(); let req = TestRequest::with_uri("/name/value").finish();
let info = rec.recognize(&req).unwrap().1; let info = router.recognize(&req, &(), 0);
let req = req.with_route_info(info); assert_eq!(info.resource, ResourceId::Normal(1));
assert_eq!(req.match_info().get("val").unwrap(), "value"); assert_eq!(info.match_info().get("val").unwrap(), "value");
assert_eq!(&req.match_info()["val"], "value"); assert_eq!(&info.match_info()["val"], "value");
let req = TestRequest::with_uri("/name/value2/index.html").finish(); let req = TestRequest::with_uri("/name/value2/index.html").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 0);
assert_eq!(info.0, 2); assert_eq!(info.resource, ResourceId::Normal(2));
let req = req.with_route_info(info.1); assert_eq!(info.match_info().get("val").unwrap(), "value2");
assert_eq!(req.match_info().get("val").unwrap(), "value2");
let req = TestRequest::with_uri("/file/file.gz").finish(); let req = TestRequest::with_uri("/file/file.gz").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 0);
assert_eq!(info.0, 3); assert_eq!(info.resource, ResourceId::Normal(3));
let req = req.with_route_info(info.1); assert_eq!(info.match_info().get("file").unwrap(), "file");
assert_eq!(req.match_info().get("file").unwrap(), "file"); assert_eq!(info.match_info().get("ext").unwrap(), "gz");
assert_eq!(req.match_info().get("ext").unwrap(), "gz");
let req = TestRequest::with_uri("/vtest/ttt/index.html").finish(); let req = TestRequest::with_uri("/vtest/ttt/index.html").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 0);
assert_eq!(info.0, 4); assert_eq!(info.resource, ResourceId::Normal(4));
let req = req.with_route_info(info.1); assert_eq!(info.match_info().get("val").unwrap(), "test");
assert_eq!(req.match_info().get("val").unwrap(), "test"); assert_eq!(info.match_info().get("val2").unwrap(), "ttt");
assert_eq!(req.match_info().get("val2").unwrap(), "ttt");
let req = TestRequest::with_uri("/v/blah-blah/index.html").finish(); let req = TestRequest::with_uri("/v/blah-blah/index.html").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 0);
assert_eq!(info.0, 5); assert_eq!(info.resource, ResourceId::Normal(5));
let req = req.with_route_info(info.1);
assert_eq!( assert_eq!(
req.match_info().get("tail").unwrap(), info.match_info().get("tail").unwrap(),
"blah-blah/index.html" "blah-blah/index.html"
); );
let req = TestRequest::with_uri("/test2/index.html").finish(); let req = TestRequest::with_uri("/test2/index.html").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 0);
assert_eq!(info.0, 6); assert_eq!(info.resource, ResourceId::Normal(6));
let req = req.with_route_info(info.1); assert_eq!(info.match_info().get("test").unwrap(), "index");
assert_eq!(req.match_info().get("test").unwrap(), "index");
let req = TestRequest::with_uri("/bbb/index.html").finish(); let req = TestRequest::with_uri("/bbb/index.html").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 0);
assert_eq!(info.0, 7); assert_eq!(info.resource, ResourceId::Normal(7));
let req = req.with_route_info(info.1); assert_eq!(info.match_info().get("test").unwrap(), "bbb");
assert_eq!(req.match_info().get("test").unwrap(), "bbb");
} }
#[test] #[test]
fn test_recognizer_2() { fn test_recognizer_2() {
let routes = vec![ let mut router = Router::<()>::new();
( router.register_resource(Resource::new(ResourceDef::new("/index.json")));
ResourceDef::new("", "/index.json"), router.register_resource(Resource::new(ResourceDef::new("/{source}.json")));
Some(Resource::default()),
),
(
ResourceDef::new("", "/{source}.json"),
Some(Resource::default()),
),
];
let (rec, _) = Router::new::<()>("", routes);
let req = TestRequest::with_uri("/index.json").finish(); let req = TestRequest::with_uri("/index.json").finish();
assert_eq!(rec.recognize(&req).unwrap().0, 0); let info = router.recognize(&req, &(), 0);
assert_eq!(info.resource, ResourceId::Normal(0));
let req = TestRequest::with_uri("/test.json").finish(); let req = TestRequest::with_uri("/test.json").finish();
assert_eq!(rec.recognize(&req).unwrap().0, 1); let info = router.recognize(&req, &(), 0);
assert_eq!(info.resource, ResourceId::Normal(1));
} }
#[test] #[test]
fn test_recognizer_with_prefix() { fn test_recognizer_with_prefix() {
let routes = vec![ let mut router = Router::<()>::new();
(ResourceDef::new("", "/name"), Some(Resource::default())), router.register_resource(Resource::new(ResourceDef::new("/name")));
( router.register_resource(Resource::new(ResourceDef::new("/name/{val}")));
ResourceDef::new("", "/name/{val}"),
Some(Resource::default()),
),
];
let (rec, _) = Router::new::<()>("/test", routes);
let req = TestRequest::with_uri("/name").finish(); let req = TestRequest::with_uri("/name").finish();
assert!(rec.recognize(&req).is_none()); let info = router.recognize(&req, &(), 5);
assert_eq!(info.resource, ResourceId::Default);
let req = TestRequest::with_uri("/test/name").finish(); let req = TestRequest::with_uri("/test/name").finish();
assert_eq!(rec.recognize(&req).unwrap().0, 0); let info = router.recognize(&req, &(), 5);
assert_eq!(info.resource, ResourceId::Normal(0));
let req = TestRequest::with_uri("/test/name/value").finish(); let req = TestRequest::with_uri("/test/name/value").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 5);
assert_eq!(info.0, 1); assert_eq!(info.resource, ResourceId::Normal(1));
let req = req.with_route_info(info.1); assert_eq!(info.match_info().get("val").unwrap(), "value");
assert_eq!(req.match_info().get("val").unwrap(), "value"); assert_eq!(&info.match_info()["val"], "value");
assert_eq!(&req.match_info()["val"], "value");
// same patterns // same patterns
let routes = vec![ let mut router = Router::<()>::new();
(ResourceDef::new("", "/name"), Some(Resource::default())), router.register_resource(Resource::new(ResourceDef::new("/name")));
( router.register_resource(Resource::new(ResourceDef::new("/name/{val}")));
ResourceDef::new("", "/name/{val}"),
Some(Resource::default()),
),
];
let (rec, _) = Router::new::<()>("/test2", routes);
let req = TestRequest::with_uri("/name").finish(); let req = TestRequest::with_uri("/name").finish();
assert!(rec.recognize(&req).is_none()); let info = router.recognize(&req, &(), 6);
assert_eq!(info.resource, ResourceId::Default);
let req = TestRequest::with_uri("/test2/name").finish(); let req = TestRequest::with_uri("/test2/name").finish();
assert_eq!(rec.recognize(&req).unwrap().0, 0); let info = router.recognize(&req, &(), 6);
assert_eq!(info.resource, ResourceId::Normal(0));
let req = TestRequest::with_uri("/test2/name-test").finish(); let req = TestRequest::with_uri("/test2/name-test").finish();
assert!(rec.recognize(&req).is_none()); let info = router.recognize(&req, &(), 6);
assert_eq!(info.resource, ResourceId::Default);
let req = TestRequest::with_uri("/test2/name/ttt").finish(); let req = TestRequest::with_uri("/test2/name/ttt").finish();
let info = rec.recognize(&req).unwrap(); let info = router.recognize(&req, &(), 6);
assert_eq!(info.0, 1); assert_eq!(info.resource, ResourceId::Normal(1));
let req = req.with_route_info(info.1); assert_eq!(&info.match_info()["val"], "ttt");
assert_eq!(&req.match_info()["val"], "ttt");
} }
#[test] #[test]
fn test_parse_static() { fn test_parse_static() {
let re = ResourceDef::new("test", "/"); let re = ResourceDef::new("/");
assert!(re.is_match("/")); assert!(re.is_match("/"));
assert!(!re.is_match("/a")); assert!(!re.is_match("/a"));
let re = ResourceDef::new("test", "/name"); let re = ResourceDef::new("/name");
assert!(re.is_match("/name")); assert!(re.is_match("/name"));
assert!(!re.is_match("/name1")); assert!(!re.is_match("/name1"));
assert!(!re.is_match("/name/")); assert!(!re.is_match("/name/"));
assert!(!re.is_match("/name~")); assert!(!re.is_match("/name~"));
let re = ResourceDef::new("test", "/name/"); let re = ResourceDef::new("/name/");
assert!(re.is_match("/name/")); assert!(re.is_match("/name/"));
assert!(!re.is_match("/name")); assert!(!re.is_match("/name"));
assert!(!re.is_match("/name/gs")); assert!(!re.is_match("/name/gs"));
let re = ResourceDef::new("test", "/user/profile"); let re = ResourceDef::new("/user/profile");
assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/profile"));
assert!(!re.is_match("/user/profile/profile")); assert!(!re.is_match("/user/profile/profile"));
} }
#[test] #[test]
fn test_parse_param() { fn test_parse_param() {
let re = ResourceDef::new("test", "/user/{id}"); let re = ResourceDef::new("/user/{id}");
assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345")); assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/")); assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg")); assert!(!re.is_match("/user/2345/sdg"));
let req = TestRequest::with_uri("/user/profile").finish(); let req = TestRequest::with_uri("/user/profile").finish();
let info = re.match_with_params(&req, 0, true).unwrap(); let info = re.match_with_params(&req, 0).unwrap();
assert_eq!(info.get("id").unwrap(), "profile"); assert_eq!(info.get("id").unwrap(), "profile");
let req = TestRequest::with_uri("/user/1245125").finish(); let req = TestRequest::with_uri("/user/1245125").finish();
let info = re.match_with_params(&req, 0, true).unwrap(); let info = re.match_with_params(&req, 0).unwrap();
assert_eq!(info.get("id").unwrap(), "1245125"); assert_eq!(info.get("id").unwrap(), "1245125");
let re = ResourceDef::new("test", "/v{version}/resource/{id}"); let re = ResourceDef::new("/v{version}/resource/{id}");
assert!(re.is_match("/v1/resource/320120")); assert!(re.is_match("/v1/resource/320120"));
assert!(!re.is_match("/v/resource/1")); assert!(!re.is_match("/v/resource/1"));
assert!(!re.is_match("/resource")); assert!(!re.is_match("/resource"));
let req = TestRequest::with_uri("/v151/resource/adahg32").finish(); let req = TestRequest::with_uri("/v151/resource/adahg32").finish();
let info = re.match_with_params(&req, 0, true).unwrap(); let info = re.match_with_params(&req, 0).unwrap();
assert_eq!(info.get("version").unwrap(), "151"); assert_eq!(info.get("version").unwrap(), "151");
assert_eq!(info.get("id").unwrap(), "adahg32"); assert_eq!(info.get("id").unwrap(), "adahg32");
} }
#[test] #[test]
fn test_resource_prefix() { fn test_resource_prefix() {
let re = ResourceDef::prefix("test", "/name"); let re = ResourceDef::prefix("/name");
assert!(re.is_match("/name")); assert!(re.is_match("/name"));
assert!(re.is_match("/name/")); assert!(re.is_match("/name/"));
assert!(re.is_match("/name/test/test")); assert!(re.is_match("/name/test/test"));
assert!(re.is_match("/name1")); assert!(re.is_match("/name1"));
assert!(re.is_match("/name~")); assert!(re.is_match("/name~"));
let re = ResourceDef::prefix("test", "/name/"); let re = ResourceDef::prefix("/name/");
assert!(re.is_match("/name/")); assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs")); assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name")); assert!(!re.is_match("/name"));
@ -811,46 +953,41 @@ mod tests {
#[test] #[test]
fn test_reousrce_prefix_dynamic() { fn test_reousrce_prefix_dynamic() {
let re = ResourceDef::prefix("test", "/{name}/"); let re = ResourceDef::prefix("/{name}/");
assert!(re.is_match("/name/")); assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs")); assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name")); assert!(!re.is_match("/name"));
let req = TestRequest::with_uri("/test2/").finish(); let req = TestRequest::with_uri("/test2/").finish();
let info = re.match_with_params(&req, 0, true).unwrap(); let info = re.match_with_params(&req, 0).unwrap();
assert_eq!(&info["name"], "test2"); assert_eq!(&info["name"], "test2");
assert_eq!(&info[0], "test2"); assert_eq!(&info[0], "test2");
let req = TestRequest::with_uri("/test2/subpath1/subpath2/index.html").finish(); let req = TestRequest::with_uri("/test2/subpath1/subpath2/index.html").finish();
let info = re.match_with_params(&req, 0, true).unwrap(); let info = re.match_with_params(&req, 0).unwrap();
assert_eq!(&info["name"], "test2"); assert_eq!(&info["name"], "test2");
assert_eq!(&info[0], "test2"); assert_eq!(&info[0], "test2");
} }
#[test] #[test]
fn test_request_resource() { fn test_request_resource() {
let routes = vec![ let mut router = Router::<()>::new();
( let mut resource = Resource::new(ResourceDef::new("/index.json"));
ResourceDef::new("r1", "/index.json"), resource.name("r1");
Some(Resource::default()), router.register_resource(resource);
), let mut resource = Resource::new(ResourceDef::new("/test.json"));
( resource.name("r2");
ResourceDef::new("r2", "/test.json"), router.register_resource(resource);
Some(Resource::default()),
),
];
let (router, _) = Router::new::<()>("", routes);
let req = TestRequest::with_uri("/index.json").finish(); let req = TestRequest::with_uri("/index.json").finish();
assert_eq!(router.recognize(&req).unwrap().0, 0); let info = router.recognize(&req, &(), 0);
let info = router.recognize(&req).unwrap().1; assert_eq!(info.resource, ResourceId::Normal(0));
let resource = info.resource().unwrap();
assert_eq!(resource.name(), "r1"); assert_eq!(info.name(), "r1");
let req = TestRequest::with_uri("/test.json").finish(); let req = TestRequest::with_uri("/test.json").finish();
assert_eq!(router.recognize(&req).unwrap().0, 1); let info = router.recognize(&req, &(), 0);
let info = router.recognize(&req).unwrap().1; assert_eq!(info.resource, ResourceId::Normal(1));
let resource = info.resource().unwrap(); assert_eq!(info.name(), "r2");
assert_eq!(resource.name(), "r2");
} }
} }

View File

@ -6,7 +6,7 @@ use futures::{Async, Future, Poll};
use error::Error; use error::Error;
use handler::{AsyncResult, AsyncResultItem, FromRequest, Responder, RouteHandler}; use handler::{AsyncResult, AsyncResultItem, FromRequest, Responder, RouteHandler};
use http::{Method, StatusCode}; use http::Method;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use middleware::{ use middleware::{
@ -14,15 +14,10 @@ use middleware::{
Started as MiddlewareStarted, Started as MiddlewareStarted,
}; };
use pred::Predicate; use pred::Predicate;
use resource::{Resource, RouteId}; use resource::{DefaultResource, Resource};
use router::ResourceDef; use router::{ResourceDef, Router};
use server::Request; use server::Request;
type ScopeResource<S> = Rc<Resource<S>>;
type Route<S> = Box<RouteHandler<S>>;
type ScopeResources<S> = Rc<Vec<(ResourceDef, ScopeResource<S>)>>;
type NestedInfo<S> = (ResourceDef, Route<S>, Vec<Box<Predicate<S>>>);
/// Resources scope /// Resources scope
/// ///
/// Scope is a set of resources with common root path. /// Scope is a set of resources with common root path.
@ -53,29 +48,31 @@ type NestedInfo<S> = (ResourceDef, Route<S>, Vec<Box<Predicate<S>>>);
/// * /{project_id}/path2 - `GET` requests /// * /{project_id}/path2 - `GET` requests
/// * /{project_id}/path3 - `HEAD` requests /// * /{project_id}/path3 - `HEAD` requests
/// ///
#[derive(Default)] pub struct Scope<S> {
pub struct Scope<S: 'static> { rdef: ResourceDef,
router: Rc<Router<S>>,
filters: Vec<Box<Predicate<S>>>, filters: Vec<Box<Predicate<S>>>,
nested: Vec<NestedInfo<S>>,
middlewares: Rc<Vec<Box<Middleware<S>>>>, middlewares: Rc<Vec<Box<Middleware<S>>>>,
default: Option<ScopeResource<S>>,
resources: ScopeResources<S>,
} }
#[cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))] #[cfg_attr(feature = "cargo-clippy", allow(new_without_default_derive))]
impl<S: 'static> Scope<S> { impl<S: 'static> Scope<S> {
/// Create a new scope /// Create a new scope
// TODO: Why is this not exactly the default impl? // TODO: Why is this not exactly the default impl?
pub fn new() -> Scope<S> { pub fn new(path: &str) -> Scope<S> {
Scope { Scope {
rdef: ResourceDef::prefix(path),
router: Rc::new(Router::new()),
filters: Vec::new(), filters: Vec::new(),
nested: Vec::new(),
resources: Rc::new(Vec::new()),
middlewares: Rc::new(Vec::new()), middlewares: Rc::new(Vec::new()),
default: None,
} }
} }
#[inline]
pub(crate) fn rdef(&self) -> &ResourceDef {
&self.rdef
}
#[inline] #[inline]
pub(crate) fn take_filters(&mut self) -> Vec<Box<Predicate<S>>> { pub(crate) fn take_filters(&mut self) -> Vec<Box<Predicate<S>>> {
mem::replace(&mut self.filters, Vec::new()) mem::replace(&mut self.filters, Vec::new())
@ -132,11 +129,10 @@ impl<S: 'static> Scope<S> {
F: FnOnce(Scope<T>) -> Scope<T>, F: FnOnce(Scope<T>) -> Scope<T>,
{ {
let scope = Scope { let scope = Scope {
rdef: ResourceDef::prefix(path),
filters: Vec::new(), filters: Vec::new(),
nested: Vec::new(), router: Rc::new(Router::new()),
resources: Rc::new(Vec::new()),
middlewares: Rc::new(Vec::new()), middlewares: Rc::new(Vec::new()),
default: None,
}; };
let mut scope = f(scope); let mut scope = f(scope);
@ -146,8 +142,12 @@ impl<S: 'static> Scope<S> {
filters: scope.take_filters(), filters: scope.take_filters(),
})]; })];
let handler = Box::new(Wrapper { scope, state }); let handler = Box::new(Wrapper { scope, state });
self.nested
.push((ResourceDef::prefix("", &path), handler, filters)); Rc::get_mut(&mut self.router).unwrap().register_handler(
path,
handler,
Some(filters),
);
self self
} }
@ -175,17 +175,14 @@ impl<S: 'static> Scope<S> {
F: FnOnce(Scope<S>) -> Scope<S>, F: FnOnce(Scope<S>) -> Scope<S>,
{ {
let scope = Scope { let scope = Scope {
rdef: ResourceDef::prefix(&path),
filters: Vec::new(), filters: Vec::new(),
nested: Vec::new(), router: Rc::new(Router::new()),
resources: Rc::new(Vec::new()),
middlewares: Rc::new(Vec::new()), middlewares: Rc::new(Vec::new()),
default: None,
}; };
let mut scope = f(scope); Rc::get_mut(&mut self.router)
.unwrap()
let filters = scope.take_filters(); .register_scope(f(scope));
self.nested
.push((ResourceDef::prefix("", &path), Box::new(scope), filters));
self self
} }
@ -223,39 +220,9 @@ impl<S: 'static> Scope<S> {
R: Responder + 'static, R: Responder + 'static,
T: FromRequest<S> + 'static, T: FromRequest<S> + 'static,
{ {
// check if we have resource handler Rc::get_mut(&mut self.router)
let mut found = false; .unwrap()
for &(ref pattern, _) in self.resources.iter() { .register_route(path, method, f);
if pattern.pattern() == path {
found = true;
break;
}
}
if found {
let resources = Rc::get_mut(&mut self.resources)
.expect("Multiple scope references are not allowed");
for &mut (ref pattern, ref mut resource) in resources.iter_mut() {
if pattern.pattern() == path {
let res = Rc::get_mut(resource)
.expect("Multiple scope references are not allowed");
res.method(method).with(f);
break;
}
}
} else {
let mut handler = Resource::default();
handler.method(method).with(f);
let pattern = ResourceDef::with_prefix(
handler.get_name(),
path,
if path.is_empty() { "" } else { "/" },
false,
);
Rc::get_mut(&mut self.resources)
.expect("Can not use after configuration")
.push((pattern, Rc::new(handler)));
}
self self
} }
@ -286,20 +253,18 @@ impl<S: 'static> Scope<S> {
where where
F: FnOnce(&mut Resource<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
// add resource handler // add resource
let mut handler = Resource::default();
f(&mut handler);
let pattern = ResourceDef::with_prefix( let pattern = ResourceDef::with_prefix(
handler.get_name(),
path, path,
if path.is_empty() { "" } else { "/" }, if path.is_empty() { "" } else { "/" },
false, false,
); );
Rc::get_mut(&mut self.resources) let mut resource = Resource::new(pattern);
.expect("Can not use after configuration") f(&mut resource);
.push((pattern, Rc::new(handler)));
Rc::get_mut(&mut self.router)
.unwrap()
.register_resource(resource);
self self
} }
@ -308,14 +273,14 @@ impl<S: 'static> Scope<S> {
where where
F: FnOnce(&mut Resource<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
if self.default.is_none() { // create and configure default resource
self.default = Some(Rc::new(Resource::default_not_found())); let mut resource = Resource::new(ResourceDef::new(""));
} f(&mut resource);
{
let default = Rc::get_mut(self.default.as_mut().unwrap()) Rc::get_mut(&mut self.router)
.expect("Multiple copies of default handler"); .expect("Multiple copies of scope router")
f(default); .register_default_resource(resource.into());
}
self self
} }
@ -339,64 +304,33 @@ impl<S: 'static> RouteHandler<S> for Scope<S> {
let tail = req.match_info().tail as usize; let tail = req.match_info().tail as usize;
// recognize resources // recognize resources
for &(ref pattern, ref resource) in self.resources.iter() { let info = self.router.recognize(req, req.state(), tail);
if let Some(params) = pattern.match_with_params(req, tail, false) { let req2 = req.with_route_info(info);
let req2 = req.with_route_info(req.route().merge(&params));
if let Some(id) = resource.get_route_id(&req2) {
if self.middlewares.is_empty() { if self.middlewares.is_empty() {
return resource.handle(id, &req2); self.router.handle(&req2)
} else { } else {
return AsyncResult::async(Box::new(Compose::new( AsyncResult::async(Box::new(Compose::new(
id,
req2, req2,
Rc::clone(&self.router),
Rc::clone(&self.middlewares), Rc::clone(&self.middlewares),
Rc::clone(&resource), )))
)));
} }
} }
}
}
// nested scopes
'outer: for &(ref prefix, ref handler, ref filters) in &self.nested {
if let Some(params) = prefix.match_prefix_with_params(req, tail) {
let req2 = req.with_route_info(req.route().merge(&params));
let state = req.state();
for filter in filters {
if !filter.check(&req2, state) {
continue 'outer;
}
}
return handler.handle(&req2);
}
}
// default handler
if let Some(ref resource) = self.default {
if let Some(id) = resource.get_route_id(req) {
if self.middlewares.is_empty() {
return resource.handle(id, req);
} else {
return AsyncResult::async(Box::new(Compose::new(
id,
req.clone(),
Rc::clone(&self.middlewares),
Rc::clone(resource),
)));
}
}
}
AsyncResult::ok(HttpResponse::new(StatusCode::NOT_FOUND))
}
fn has_default_resource(&self) -> bool { fn has_default_resource(&self) -> bool {
self.default.is_some() self.router.has_default_resource()
} }
fn default_resource(&mut self, default: ScopeResource<S>) { fn default_resource(&mut self, default: DefaultResource<S>) {
self.default = Some(default); Rc::get_mut(&mut self.router)
.expect("Can not use after configuration")
.register_default_resource(default);
}
fn finish(&mut self) {
Rc::get_mut(&mut self.router)
.expect("Can not use after configuration")
.finish();
} }
} }
@ -436,10 +370,9 @@ struct Compose<S: 'static> {
struct ComposeInfo<S: 'static> { struct ComposeInfo<S: 'static> {
count: usize, count: usize,
id: RouteId,
req: HttpRequest<S>, req: HttpRequest<S>,
router: Rc<Router<S>>,
mws: Rc<Vec<Box<Middleware<S>>>>, mws: Rc<Vec<Box<Middleware<S>>>>,
resource: Rc<Resource<S>>,
} }
enum ComposeState<S: 'static> { enum ComposeState<S: 'static> {
@ -464,14 +397,12 @@ impl<S: 'static> ComposeState<S> {
impl<S: 'static> Compose<S> { impl<S: 'static> Compose<S> {
fn new( fn new(
id: RouteId, req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>, req: HttpRequest<S>, router: Rc<Router<S>>, mws: Rc<Vec<Box<Middleware<S>>>>,
resource: Rc<Resource<S>>,
) -> Self { ) -> Self {
let mut info = ComposeInfo { let mut info = ComposeInfo {
id,
mws, mws,
req, req,
resource, router,
count: 0, count: 0,
}; };
let state = StartMiddlewares::init(&mut info); let state = StartMiddlewares::init(&mut info);
@ -513,7 +444,7 @@ impl<S: 'static> StartMiddlewares<S> {
loop { loop {
if info.count == len { if info.count == len {
let reply = info.resource.handle(info.id, &info.req); let reply = info.router.handle(&info.req);
return WaitingResponse::init(info, reply); return WaitingResponse::init(info, reply);
} else { } else {
let result = info.mws[info.count].start(&info.req); let result = info.mws[info.count].start(&info.req);
@ -552,7 +483,7 @@ impl<S: 'static> StartMiddlewares<S> {
} }
loop { loop {
if info.count == len { if info.count == len {
let reply = { info.resource.handle(info.id, &info.req) }; let reply = info.router.handle(&info.req);
return Some(WaitingResponse::init(info, reply)); return Some(WaitingResponse::init(info, reply));
} else { } else {
let result = info.mws[info.count].start(&info.req); let result = info.mws[info.count].start(&info.req);

View File

@ -543,11 +543,6 @@ mod tests {
err: None, err: None,
} }
} }
fn feed_data(&mut self, data: &'static str) {
let mut b = BytesMut::from(self.buf.as_ref());
b.extend(data.as_bytes());
self.buf = b.take().freeze();
}
} }
impl AsyncRead for Buffer {} impl AsyncRead for Buffer {}

View File

@ -417,6 +417,7 @@ pub struct TestRequest<S> {
params: Params, params: Params,
cookies: Option<Vec<Cookie<'static>>>, cookies: Option<Vec<Cookie<'static>>>,
payload: Option<Payload>, payload: Option<Payload>,
prefix: u16,
} }
impl Default for TestRequest<()> { impl Default for TestRequest<()> {
@ -430,6 +431,7 @@ impl Default for TestRequest<()> {
params: Params::new(), params: Params::new(),
cookies: None, cookies: None,
payload: None, payload: None,
prefix: 0,
} }
} }
} }
@ -467,6 +469,7 @@ impl<S: 'static> TestRequest<S> {
params: Params::new(), params: Params::new(),
cookies: None, cookies: None,
payload: None, payload: None,
prefix: 0,
} }
} }
@ -527,6 +530,12 @@ impl<S: 'static> TestRequest<S> {
self self
} }
/// Set request's prefix
pub fn prefix(mut self, prefix: u16) -> Self {
self.prefix = prefix;
self
}
/// Complete request creation and generate `HttpRequest` instance /// Complete request creation and generate `HttpRequest` instance
pub fn finish(self) -> HttpRequest<S> { pub fn finish(self) -> HttpRequest<S> {
let TestRequest { let TestRequest {
@ -535,11 +544,12 @@ impl<S: 'static> TestRequest<S> {
uri, uri,
version, version,
headers, headers,
params, mut params,
cookies, cookies,
payload, payload,
prefix,
} = self; } = self;
let (router, _) = Router::new::<S>("/", Vec::new()); let router = Router::<()>::new();
let pool = RequestPool::pool(ServerSettings::default()); let pool = RequestPool::pool(ServerSettings::default());
let mut req = RequestPool::get(pool); let mut req = RequestPool::get(pool);
@ -551,25 +561,28 @@ impl<S: 'static> TestRequest<S> {
inner.headers = headers; inner.headers = headers;
*inner.payload.borrow_mut() = payload; *inner.payload.borrow_mut() = payload;
} }
params.set_url(req.url().clone());
let mut info = router.route_info_params(0, params);
info.set_prefix(prefix);
let mut req = let mut req = HttpRequest::new(req, Rc::new(state), info);
HttpRequest::new(req, Rc::new(state), router.route_info_params(params));
req.set_cookies(cookies); req.set_cookies(cookies);
req req
} }
#[cfg(test)] #[cfg(test)]
/// Complete request creation and generate `HttpRequest` instance /// Complete request creation and generate `HttpRequest` instance
pub(crate) fn finish_with_router(self, router: Router) -> HttpRequest<S> { pub(crate) fn finish_with_router(self, router: Router<S>) -> HttpRequest<S> {
let TestRequest { let TestRequest {
state, state,
method, method,
uri, uri,
version, version,
headers, headers,
params, mut params,
cookies, cookies,
payload, payload,
prefix,
} = self; } = self;
let pool = RequestPool::pool(ServerSettings::default()); let pool = RequestPool::pool(ServerSettings::default());
@ -582,8 +595,10 @@ impl<S: 'static> TestRequest<S> {
inner.headers = headers; inner.headers = headers;
*inner.payload.borrow_mut() = payload; *inner.payload.borrow_mut() = payload;
} }
let mut req = params.set_url(req.url().clone());
HttpRequest::new(req, Rc::new(state), router.route_info_params(params)); let mut info = router.route_info_params(0, params);
info.set_prefix(prefix);
let mut req = HttpRequest::new(req, Rc::new(state), info);
req.set_cookies(cookies); req.set_cookies(cookies);
req req
} }