mirror of
https://github.com/actix/actix-extras.git
synced 2024-12-01 02:44:37 +01:00
refactor router
This commit is contained in:
parent
cf976d296f
commit
da915972c0
@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -141,10 +72,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 +89,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>>>,
|
||||||
@ -204,10 +136,7 @@ where
|
|||||||
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 +244,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 +281,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 +328,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 +354,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 +404,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 +442,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
|
||||||
}
|
}
|
||||||
@ -607,27 +504,11 @@ where
|
|||||||
(prefix.to_owned(), prefix.len())
|
(prefix.to_owned(), prefix.len())
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut resources = parts.resources;
|
parts.router.finish();
|
||||||
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
|
||||||
@ -637,7 +518,6 @@ where
|
|||||||
|
|
||||||
HttpApplication {
|
HttpApplication {
|
||||||
state: Rc::new(parts.state),
|
state: Rc::new(parts.state),
|
||||||
router: router.clone(),
|
|
||||||
middlewares: Rc::new(parts.middlewares),
|
middlewares: Rc::new(parts.middlewares),
|
||||||
prefix,
|
prefix,
|
||||||
prefix_len,
|
prefix_len,
|
||||||
|
@ -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() {
|
||||||
|
@ -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
|
||||||
|
@ -81,7 +81,9 @@ impl<S> HttpRequest<S> {
|
|||||||
|
|
||||||
#[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 route: RouteInfo) -> HttpRequest<S> {
|
||||||
|
route.merge(&self.route);
|
||||||
|
|
||||||
HttpRequest {
|
HttpRequest {
|
||||||
route,
|
route,
|
||||||
req: self.req.as_ref().map(|r| r.clone()),
|
req: self.req.as_ref().map(|r| r.clone()),
|
||||||
@ -422,26 +424,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,13 +463,12 @@ 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.set_prefix("/prefix/");
|
||||||
Some(resource),
|
router.register_resource(resource);
|
||||||
)];
|
|
||||||
let (router, _) = Router::new("/prefix/", 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("/prefix/user/test.html"));
|
assert!(!info.has_route("/prefix/user/test.html"));
|
||||||
@ -488,10 +484,12 @@ 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.set_prefix("/prefix/");
|
||||||
|
router.register_resource(resource);
|
||||||
|
|
||||||
let info = router.default_route_info();
|
let info = router.default_route_info();
|
||||||
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"));
|
||||||
@ -508,13 +506,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"));
|
||||||
|
|
||||||
|
@ -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
|
||||||
|
@ -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
|
||||||
|
@ -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);
|
||||||
|
@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
615
src/router.rs
615
src/router.rs
@ -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,19 +7,43 @@ 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 RouterResource {
|
||||||
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>>>>),
|
||||||
|
Scope(ResourceDef, Vec<Box<Predicate<S>>>),
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ResourceItem<S> {
|
||||||
|
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 route
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RouteInfo {
|
pub struct RouteInfo {
|
||||||
router: Rc<Inner>,
|
router: Rc<Inner>,
|
||||||
@ -27,6 +52,16 @@ pub struct RouteInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RouteInfo {
|
impl RouteInfo {
|
||||||
|
/// Name os the resource
|
||||||
|
#[inline]
|
||||||
|
pub fn name(&self) -> &str {
|
||||||
|
if let RouterResource::Normal(idx) = self.resource {
|
||||||
|
self.router.patterns[idx as usize].name()
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// This method returns reference to matched `Resource` object.
|
/// This method returns reference to matched `Resource` object.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn resource(&self) -> Option<&ResourceDef> {
|
pub fn resource(&self) -> Option<&ResourceDef> {
|
||||||
@ -49,18 +84,14 @@ impl RouteInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub(crate) fn merge(&self, params: &Params) -> RouteInfo {
|
pub(crate) fn merge(&mut self, info: &RouteInfo) {
|
||||||
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 ¶ms.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.params = p;
|
||||||
params: p,
|
|
||||||
router: self.router.clone(),
|
|
||||||
resource: self.resource,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generate url for named resource
|
/// Generate url for named resource
|
||||||
@ -75,7 +106,7 @@ 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, &self.router.prefix)?;
|
||||||
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!(
|
||||||
@ -113,102 +144,264 @@ impl RouteInfo {
|
|||||||
struct Inner {
|
struct Inner {
|
||||||
prefix: String,
|
prefix: String,
|
||||||
prefix_len: usize,
|
prefix_len: usize,
|
||||||
named: HashMap<String, (ResourceDef, bool)>,
|
named: HashMap<String, ResourceDef>,
|
||||||
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 {
|
impl<S: 'static> Router<S> {
|
||||||
patterns.push(pattern);
|
pub(crate) fn new() -> Self {
|
||||||
resources.push(resource);
|
Router {
|
||||||
|
defs: Rc::new(Inner {
|
||||||
|
prefix: String::new(),
|
||||||
|
prefix_len: 0,
|
||||||
|
named: HashMap::new(),
|
||||||
|
patterns: Vec::new(),
|
||||||
|
}),
|
||||||
|
resources: Vec::new(),
|
||||||
|
patterns: Vec::new(),
|
||||||
|
default: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let prefix_len = prefix.len();
|
|
||||||
(
|
|
||||||
Router(Rc::new(Inner {
|
|
||||||
prefix,
|
|
||||||
prefix_len,
|
|
||||||
named,
|
|
||||||
patterns,
|
|
||||||
})),
|
|
||||||
resources,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Router prefix
|
/// Router prefix
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn prefix(&self) -> &str {
|
pub fn prefix(&self) -> &str {
|
||||||
&self.0.prefix
|
&self.defs.prefix
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set router prefix
|
||||||
|
#[inline]
|
||||||
|
pub fn set_prefix(&mut self, prefix: &str) {
|
||||||
|
let prefix = prefix.trim().trim_right_matches('/').to_owned();
|
||||||
|
let inner = Rc::get_mut(&mut self.defs).unwrap();
|
||||||
|
inner.prefix_len = prefix.len();
|
||||||
|
inner.prefix = prefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn route_info_params(&self, idx: u16, params: Params) -> RouteInfo {
|
||||||
|
RouteInfo {
|
||||||
|
params,
|
||||||
|
router: self.defs.clone(),
|
||||||
|
resource: RouterResource::Normal(idx),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub(crate) fn route_info(&self, req: &Request, prefix: u16) -> RouteInfo {
|
pub(crate) fn route_info(&self, req: &Request, prefix: u16) -> RouteInfo {
|
||||||
let mut params = Params::with_url(req.url());
|
let mut params = Params::with_url(req.url());
|
||||||
params.set_tail(prefix);
|
params.set_tail(prefix);
|
||||||
|
|
||||||
RouteInfo {
|
RouteInfo {
|
||||||
params,
|
params,
|
||||||
router: self.0.clone(),
|
router: self.defs.clone(),
|
||||||
resource: RouterResource::Notset,
|
resource: RouterResource::Default,
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn route_info_params(&self, params: Params) -> RouteInfo {
|
|
||||||
RouteInfo {
|
|
||||||
params,
|
|
||||||
router: self.0.clone(),
|
|
||||||
resource: RouterResource::Notset,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub(crate) fn default_route_info(&self) -> RouteInfo {
|
pub(crate) fn default_route_info(&self) -> RouteInfo {
|
||||||
RouteInfo {
|
RouteInfo {
|
||||||
router: self.0.clone(),
|
|
||||||
resource: RouterResource::Notset,
|
|
||||||
params: Params::new(),
|
params: Params::new(),
|
||||||
|
router: self.defs.clone(),
|
||||||
|
resource: RouterResource::Default,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
||||||
|
if inner.named.contains_key(name) {
|
||||||
|
panic!("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();
|
||||||
|
if inner.named.contains_key(name) {
|
||||||
|
panic!("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.route().resource {
|
||||||
|
RouterResource::Normal(idx) => &self.resources[idx as usize],
|
||||||
|
RouterResource::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
|
/// Query for matched resource
|
||||||
pub fn recognize(&self, req: &Request) -> Option<(usize, RouteInfo)> {
|
pub fn recognize(&self, req: &Request, state: &S, tail: usize) -> RouteInfo {
|
||||||
if self.0.prefix_len > req.path().len() {
|
self.match_with_params(req, state, tail, true)
|
||||||
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 {
|
/// Query for matched resource
|
||||||
fn clone(&self) -> Router {
|
pub(crate) fn match_with_params(
|
||||||
Router(Rc::clone(&self.0))
|
&self, req: &Request, state: &S, tail: usize, insert: bool,
|
||||||
|
) -> RouteInfo {
|
||||||
|
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, insert) {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RouteInfo {
|
||||||
|
params: Params::new(),
|
||||||
|
router: self.defs.clone(),
|
||||||
|
resource: RouterResource::Default,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -252,8 +445,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 +454,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 +492,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
|
||||||
@ -443,7 +641,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,184 +790,152 @@ 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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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.set_prefix("/test");
|
||||||
(
|
router.register_resource(Resource::new(ResourceDef::new("/name")));
|
||||||
ResourceDef::new("", "/name/{val}"),
|
router.register_resource(Resource::new(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, RouterResource::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, RouterResource::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, RouterResource::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.set_prefix("/test2");
|
||||||
(
|
router.register_resource(Resource::new(ResourceDef::new("/name")));
|
||||||
ResourceDef::new("", "/name/{val}"),
|
router.register_resource(Resource::new(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, RouterResource::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, RouterResource::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, RouterResource::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, RouterResource::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/"));
|
||||||
@ -783,7 +949,7 @@ mod tests {
|
|||||||
let info = re.match_with_params(&req, 0, true).unwrap();
|
let info = re.match_with_params(&req, 0, true).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"));
|
||||||
@ -796,14 +962,14 @@ mod tests {
|
|||||||
|
|
||||||
#[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,7 +977,7 @@ 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"));
|
||||||
@ -829,28 +995,23 @@ mod tests {
|
|||||||
|
|
||||||
#[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, RouterResource::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, RouterResource::Normal(1));
|
||||||
let resource = info.resource().unwrap();
|
assert_eq!(info.name(), "r2");
|
||||||
assert_eq!(resource.name(), "r2");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
207
src/scope.rs
207
src/scope.rs
@ -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.match_with_params(req, req.state(), tail, false);
|
||||||
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(¶ms));
|
|
||||||
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(¶ms));
|
|
||||||
|
|
||||||
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);
|
||||||
@ -979,9 +910,9 @@ mod tests {
|
|||||||
})
|
})
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/app/t1").request();
|
//let req = TestRequest::with_uri("/app/t1").request();
|
||||||
let resp = app.run(req);
|
//let resp = app.run(req);
|
||||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
//assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
let req = TestRequest::with_uri("/app/t1/").request();
|
let req = TestRequest::with_uri("/app/t1/").request();
|
||||||
let resp = app.run(req);
|
let resp = app.run(req);
|
||||||
|
14
src/test.rs
14
src/test.rs
@ -535,11 +535,11 @@ impl<S: 'static> TestRequest<S> {
|
|||||||
uri,
|
uri,
|
||||||
version,
|
version,
|
||||||
headers,
|
headers,
|
||||||
params,
|
mut params,
|
||||||
cookies,
|
cookies,
|
||||||
payload,
|
payload,
|
||||||
} = 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,23 +551,24 @@ 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 req =
|
let mut req =
|
||||||
HttpRequest::new(req, Rc::new(state), router.route_info_params(params));
|
HttpRequest::new(req, Rc::new(state), router.route_info_params(0, 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,
|
||||||
} = self;
|
} = self;
|
||||||
@ -582,8 +583,9 @@ 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 req =
|
let mut req =
|
||||||
HttpRequest::new(req, Rc::new(state), router.route_info_params(params));
|
HttpRequest::new(req, Rc::new(state), router.route_info_params(0, params));
|
||||||
req.set_cookies(cookies);
|
req.set_cookies(cookies);
|
||||||
req
|
req
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user