1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-27 12:01:15 +00:00

rename ResourceHandler to Resource

This commit is contained in:
Nikolay Kim 2018-07-12 15:30:01 +06:00
parent db005af1af
commit b8b90d9ec9
10 changed files with 137 additions and 132 deletions

View file

@ -9,8 +9,8 @@ use httpresponse::HttpResponse;
use middleware::Middleware; use middleware::Middleware;
use pipeline::{HandlerType, Pipeline, PipelineHandler}; use pipeline::{HandlerType, Pipeline, PipelineHandler};
use pred::Predicate; use pred::Predicate;
use resource::ResourceHandler; use resource::Resource;
use router::{Resource, RouteInfo, Router}; use router::{ResourceDef, RouteInfo, Router};
use scope::Scope; use scope::Scope;
use server::{HttpHandler, HttpHandlerTask, IntoHttpHandler, Request}; use server::{HttpHandler, HttpHandlerTask, IntoHttpHandler, Request};
@ -28,15 +28,15 @@ pub struct HttpApplication<S = ()> {
#[doc(hidden)] #[doc(hidden)]
pub struct Inner<S> { pub struct Inner<S> {
prefix: usize, prefix: usize,
default: Rc<ResourceHandler<S>>, default: Rc<Resource<S>>,
encoding: ContentEncoding, encoding: ContentEncoding,
resources: Vec<ResourceHandler<S>>, resources: Vec<Resource<S>>,
handlers: Vec<PrefixHandlerType<S>>, handlers: Vec<PrefixHandlerType<S>>,
} }
enum PrefixHandlerType<S> { enum PrefixHandlerType<S> {
Handler(String, Box<RouteHandler<S>>), Handler(String, Box<RouteHandler<S>>),
Scope(Resource, Box<RouteHandler<S>>, Vec<Box<Predicate<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> {
@ -154,10 +154,10 @@ impl<S: 'static> HttpHandler for HttpApplication<S> {
struct ApplicationParts<S> { struct ApplicationParts<S> {
state: S, state: S,
prefix: String, prefix: String,
default: Rc<ResourceHandler<S>>, default: Rc<Resource<S>>,
resources: Vec<(Resource, Option<ResourceHandler<S>>)>, resources: Vec<(ResourceDef, Option<Resource<S>>)>,
handlers: Vec<PrefixHandlerType<S>>, handlers: Vec<PrefixHandlerType<S>>,
external: HashMap<String, Resource>, 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,7 +204,7 @@ where
parts: Some(ApplicationParts { parts: Some(ApplicationParts {
state, state,
prefix: "/".to_owned(), prefix: "/".to_owned(),
default: Rc::new(ResourceHandler::default_not_found()), default: Rc::new(Resource::default_not_found()),
resources: Vec::new(), resources: Vec::new(),
handlers: Vec::new(), handlers: Vec::new(),
external: HashMap::new(), external: HashMap::new(),
@ -332,9 +332,9 @@ where
} }
} }
} else { } else {
let mut handler = ResourceHandler::default(); let mut handler = Resource::default();
handler.method(method).with(f); handler.method(method).with(f);
let pattern = Resource::new(handler.get_name(), path); let pattern = ResourceDef::new(handler.get_name(), path);
break Some((pattern, Some(handler))); break Some((pattern, Some(handler)));
} }
} }
@ -382,7 +382,7 @@ where
let filters = scope.take_filters(); let filters = scope.take_filters();
parts.handlers.push(PrefixHandlerType::Scope( parts.handlers.push(PrefixHandlerType::Scope(
Resource::prefix("", &path), ResourceDef::prefix("", &path),
scope, scope,
filters, filters,
)); ));
@ -423,16 +423,16 @@ where
/// ``` /// ```
pub fn resource<F, R>(mut self, path: &str, f: F) -> App<S> pub fn resource<F, R>(mut self, path: &str, f: F) -> App<S>
where where
F: FnOnce(&mut ResourceHandler<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
{ {
let parts = self.parts.as_mut().expect("Use after finish"); let parts = self.parts.as_mut().expect("Use after finish");
// add resource handler // add resource handler
let mut handler = ResourceHandler::default(); let mut handler = Resource::default();
f(&mut handler); f(&mut handler);
let pattern = Resource::new(handler.get_name(), path); let pattern = ResourceDef::new(handler.get_name(), path);
parts.resources.push((pattern, Some(handler))); parts.resources.push((pattern, Some(handler)));
} }
self self
@ -440,8 +440,8 @@ where
/// 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: ResourceHandler<S>) { pub fn register_resource(&mut self, path: &str, resource: Resource<S>) {
let pattern = Resource::new(resource.get_name(), path); let pattern = ResourceDef::new(resource.get_name(), path);
self.parts self.parts
.as_mut() .as_mut()
.expect("Use after finish") .expect("Use after finish")
@ -452,7 +452,7 @@ where
/// Default resource to be used if no matching route could be found. /// Default resource to be used if no matching route could be found.
pub fn default_resource<F, R>(mut self, f: F) -> App<S> pub fn default_resource<F, R>(mut self, f: F) -> App<S>
where where
F: FnOnce(&mut ResourceHandler<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
{ {
let parts = self.parts.as_mut().expect("Use after finish"); let parts = self.parts.as_mut().expect("Use after finish");
@ -508,7 +508,7 @@ where
} }
parts.external.insert( parts.external.insert(
String::from(name.as_ref()), String::from(name.as_ref()),
Resource::external(name.as_ref(), url.as_ref()), ResourceDef::external(name.as_ref(), url.as_ref()),
); );
} }
self self

View file

@ -613,8 +613,8 @@ mod tests {
use futures::{Async, Future}; use futures::{Async, Future};
use http::header; use http::header;
use mime; use mime;
use resource::ResourceHandler; use resource::Resource;
use router::{Resource, Router}; use router::{ResourceDef, Router};
use test::TestRequest; use test::TestRequest;
#[derive(Deserialize, Debug, PartialEq)] #[derive(Deserialize, Debug, PartialEq)]
@ -710,10 +710,10 @@ 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 = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let mut routes = Vec::new(); let mut routes = Vec::new();
routes.push((Resource::new("index", "/{key}/{value}/"), Some(resource))); routes.push((ResourceDef::new("index", "/{key}/{value}/"), Some(resource)));
let (router, _) = Router::new("", routes); let (router, _) = Router::new("", routes);
let info = router.recognize(&req).unwrap().1; let info = router.recognize(&req).unwrap().1;
let req = req.with_route_info(info); let req = req.with_route_info(info);
@ -748,10 +748,10 @@ mod tests {
#[test] #[test]
fn test_extract_path_single() { fn test_extract_path_single() {
let mut resource = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let mut routes = Vec::new(); let mut routes = Vec::new();
routes.push((Resource::new("index", "/{value}/"), Some(resource))); routes.push((ResourceDef::new("index", "/{value}/"), Some(resource)));
let (router, _) = Router::new("", routes); let (router, _) = Router::new("", routes);
let req = TestRequest::with_uri("/32/").finish_with_router(router.clone()); let req = TestRequest::with_uri("/32/").finish_with_router(router.clone());
@ -762,10 +762,10 @@ mod tests {
#[test] #[test]
fn test_tuple_extract() { fn test_tuple_extract() {
let mut resource = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let mut routes = Vec::new(); let mut routes = Vec::new();
routes.push((Resource::new("index", "/{key}/{value}/"), Some(resource))); routes.push((ResourceDef::new("index", "/{key}/{value}/"), Some(resource)));
let (router, _) = Router::new("", routes); let (router, _) = Router::new("", routes);
let req = TestRequest::with_uri("/name/user1/?id=test") let req = TestRequest::with_uri("/name/user1/?id=test")

View file

@ -9,7 +9,7 @@ use error::Error;
use http::StatusCode; use http::StatusCode;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use resource::ResourceHandler; use resource::Resource;
/// 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,7 +409,7 @@ pub(crate) trait RouteHandler<S>: 'static {
false false
} }
fn default_resource(&mut self, _: Rc<ResourceHandler<S>>) { fn default_resource(&mut self, _: Rc<Resource<S>>) {
unimplemented!() unimplemented!()
} }
} }

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::{Resource, RouteInfo}; use router::{ResourceDef, RouteInfo};
use server::Request; use server::Request;
struct Query(HashMap<String, String>); struct Query(HashMap<String, String>);
@ -211,7 +211,7 @@ impl<S> HttpRequest<S> {
/// This method returns reference to matched `Resource` object. /// This method returns reference to matched `Resource` object.
#[inline] #[inline]
pub fn resource(&self) -> Option<&Resource> { pub fn resource(&self) -> Option<&ResourceDef> {
self.route.resource() self.route.resource()
} }
@ -370,8 +370,8 @@ impl<S> fmt::Debug for HttpRequest<S> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use resource::ResourceHandler; use resource::Resource;
use router::{Resource, Router}; use router::{ResourceDef, Router};
use test::TestRequest; use test::TestRequest;
#[test] #[test]
@ -422,10 +422,10 @@ mod tests {
#[test] #[test]
fn test_request_match_info() { fn test_request_match_info() {
let mut resource = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let mut routes = Vec::new(); let mut routes = Vec::new();
routes.push((Resource::new("index", "/{key}/"), Some(resource))); routes.push((ResourceDef::new("index", "/{key}/"), Some(resource)));
let (router, _) = Router::new("", routes); let (router, _) = Router::new("", routes);
let req = TestRequest::with_uri("/value/?id=test").finish(); let req = TestRequest::with_uri("/value/?id=test").finish();
@ -435,10 +435,12 @@ mod tests {
#[test] #[test]
fn test_url_for() { fn test_url_for() {
let mut resource = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let routes = let routes = vec![(
vec![(Resource::new("index", "/user/{name}.{ext}"), Some(resource))]; ResourceDef::new("index", "/user/{name}.{ext}"),
Some(resource),
)];
let (router, _) = Router::new("/", routes); 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"));
@ -464,9 +466,12 @@ mod tests {
#[test] #[test]
fn test_url_for_with_prefix() { fn test_url_for_with_prefix() {
let mut resource = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let routes = vec![(Resource::new("index", "/user/{name}.html"), Some(resource))]; let routes = vec![(
ResourceDef::new("index", "/user/{name}.html"),
Some(resource),
)];
let (router, _) = Router::new("/prefix/", routes); 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"));
@ -483,9 +488,9 @@ mod tests {
#[test] #[test]
fn test_url_for_static() { fn test_url_for_static() {
let mut resource = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let routes = vec![(Resource::new("index", "/index.html"), Some(resource))]; let routes = vec![(ResourceDef::new("index", "/index.html"), Some(resource))];
let (router, _) = Router::new("/prefix/", routes); let (router, _) = Router::new("/prefix/", routes);
let info = router.default_route_info(); let info = router.default_route_info();
assert!(info.has_route("/index.html")); assert!(info.has_route("/index.html"));
@ -503,10 +508,10 @@ mod tests {
#[test] #[test]
fn test_url_for_external() { fn test_url_for_external() {
let mut resource = ResourceHandler::<()>::default(); let mut resource = Resource::<()>::default();
resource.name("index"); resource.name("index");
let routes = vec![( let routes = vec![(
Resource::external("youtube", "https://youtube.com/watch/{video_id}"), ResourceDef::external("youtube", "https://youtube.com/watch/{video_id}"),
None, None,
)]; )];
let router = Router::new::<()>("", routes).0; let router = Router::new::<()>("", routes).0;

View file

@ -244,9 +244,9 @@ pub mod dev {
pub use info::ConnectionInfo; pub use info::ConnectionInfo;
pub use json::{JsonBody, JsonConfig}; pub use json::{JsonBody, JsonConfig};
pub use param::{FromParam, Params}; pub use param::{FromParam, Params};
pub use resource::ResourceHandler; pub use resource::Resource;
pub use route::Route; pub use route::Route;
pub use router::{Resource, ResourceType, Router}; pub use router::{ResourceDef, ResourceType, Router};
} }
pub mod http { pub mod http {

View file

@ -11,7 +11,7 @@
//! constructed backend. //! constructed backend.
//! //!
//! Cors middleware could be used as parameter for `App::middleware()` or //! Cors middleware could be used as parameter for `App::middleware()` or
//! `ResourceHandler::middleware()` methods. But you have to use //! `Resource::middleware()` methods. But you have to use
//! `Cors::for_app()` method to support *preflight* OPTIONS request. //! `Cors::for_app()` method to support *preflight* OPTIONS request.
//! //!
//! //!
@ -59,7 +59,7 @@ use httpmessage::HttpMessage;
use httprequest::HttpRequest; use httprequest::HttpRequest;
use httpresponse::HttpResponse; use httpresponse::HttpResponse;
use middleware::{Middleware, Response, Started}; use middleware::{Middleware, Response, Started};
use resource::ResourceHandler; use resource::Resource;
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
@ -277,9 +277,9 @@ impl Cors {
/// adds route for *OPTIONS* preflight requests. /// adds route for *OPTIONS* preflight requests.
/// ///
/// It is possible to register *Cors* middleware with /// It is possible to register *Cors* middleware with
/// `ResourceHandler::middleware()` method, but in that case *Cors* /// `Resource::middleware()` method, but in that case *Cors*
/// middleware wont be able to handle *OPTIONS* requests. /// middleware wont be able to handle *OPTIONS* requests.
pub fn register<S: 'static>(self, resource: &mut ResourceHandler<S>) { pub fn register<S: 'static>(self, resource: &mut Resource<S>) {
resource resource
.method(Method::OPTIONS) .method(Method::OPTIONS)
.h(|_: &_| HttpResponse::Ok()); .h(|_: &_| HttpResponse::Ok());
@ -515,7 +515,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, ResourceHandler<S>)>, resources: Vec<(String, Resource<S>)>,
app: Option<App<S>>, app: Option<App<S>>,
} }
@ -795,10 +795,10 @@ impl<S: 'static> CorsBuilder<S> {
/// ``` /// ```
pub fn resource<F, R>(&mut self, path: &str, f: F) -> &mut CorsBuilder<S> pub fn resource<F, R>(&mut self, path: &str, f: F) -> &mut CorsBuilder<S>
where where
F: FnOnce(&mut ResourceHandler<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
// add resource handler // add resource handler
let mut handler = ResourceHandler::default(); let mut handler = Resource::default();
f(&mut handler); f(&mut handler);
self.resources.push((path.to_owned(), handler)); self.resources.push((path.to_owned(), handler));

View file

@ -36,16 +36,16 @@ pub(crate) struct RouteId(usize);
/// "/", |r| r.method(http::Method::GET).f(|r| HttpResponse::Ok())) /// "/", |r| r.method(http::Method::GET).f(|r| HttpResponse::Ok()))
/// .finish(); /// .finish();
/// } /// }
pub struct ResourceHandler<S = ()> { pub struct Resource<S = ()> {
name: String, name: String,
state: PhantomData<S>, 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 ResourceHandler<S> { impl<S> Default for Resource<S> {
fn default() -> Self { fn default() -> Self {
ResourceHandler { Resource {
name: String::new(), name: String::new(),
state: PhantomData, state: PhantomData,
routes: SmallVec::new(), routes: SmallVec::new(),
@ -54,9 +54,9 @@ impl<S> Default for ResourceHandler<S> {
} }
} }
impl<S> ResourceHandler<S> { impl<S> Resource<S> {
pub(crate) fn default_not_found() -> Self { pub(crate) fn default_not_found() -> Self {
ResourceHandler { Resource {
name: String::new(), name: String::new(),
state: PhantomData, state: PhantomData,
routes: SmallVec::new(), routes: SmallVec::new(),
@ -74,7 +74,7 @@ impl<S> ResourceHandler<S> {
} }
} }
impl<S: 'static> ResourceHandler<S> { impl<S: 'static> Resource<S> {
/// Register a new route and return mutable reference to *Route* object. /// Register a new route and return mutable reference to *Route* object.
/// *Route* is used for route configuration, i.e. adding predicates, /// *Route* is used for route configuration, i.e. adding predicates,
/// setting up handler. /// setting up handler.

View file

@ -7,7 +7,7 @@ use url::Url;
use error::UrlGenerationError; use error::UrlGenerationError;
use param::{ParamItem, Params}; use param::{ParamItem, Params};
use resource::ResourceHandler; use resource::Resource;
use server::Request; use server::Request;
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq)]
@ -29,7 +29,7 @@ pub struct RouteInfo {
impl RouteInfo { impl RouteInfo {
/// This method returns reference to matched `Resource` object. /// This method returns reference to matched `Resource` object.
#[inline] #[inline]
pub fn resource(&self) -> Option<&Resource> { pub fn resource(&self) -> Option<&ResourceDef> {
if let RouterResource::Normal(idx) = self.resource { if let RouterResource::Normal(idx) = self.resource {
Some(&self.router.patterns[idx as usize]) Some(&self.router.patterns[idx as usize])
} else { } else {
@ -113,15 +113,15 @@ impl RouteInfo {
struct Inner { struct Inner {
prefix: String, prefix: String,
prefix_len: usize, prefix_len: usize,
named: HashMap<String, (Resource, bool)>, named: HashMap<String, (ResourceDef, bool)>,
patterns: Vec<Resource>, patterns: Vec<ResourceDef>,
} }
impl Router { impl Router {
/// Create new router /// Create new router
pub fn new<S>( pub fn new<S>(
prefix: &str, map: Vec<(Resource, Option<ResourceHandler<S>>)>, prefix: &str, map: Vec<(ResourceDef, Option<Resource<S>>)>,
) -> (Router, Vec<ResourceHandler<S>>) { ) -> (Router, Vec<Resource<S>>) {
let prefix = prefix.trim().trim_right_matches('/').to_owned(); let prefix = prefix.trim().trim_right_matches('/').to_owned();
let mut named = HashMap::new(); let mut named = HashMap::new();
let mut patterns = Vec::new(); let mut patterns = Vec::new();
@ -240,7 +240,7 @@ pub enum ResourceType {
/// Resource type describes an entry in resources table /// Resource type describes an entry in resources table
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Resource { pub struct ResourceDef {
tp: PatternType, tp: PatternType,
rtp: ResourceType, rtp: ResourceType,
name: String, name: String,
@ -248,12 +248,12 @@ pub struct Resource {
elements: Vec<PatternElement>, elements: Vec<PatternElement>,
} }
impl Resource { 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(name: &str, path: &str) -> Self {
Resource::with_prefix(name, path, "/", false) ResourceDef::with_prefix(name, path, "/", false)
} }
/// Parse path pattern and create new `Resource` instance. /// Parse path pattern and create new `Resource` instance.
@ -262,14 +262,14 @@ impl Resource {
/// ///
/// 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(name: &str, path: &str) -> Self {
Resource::with_prefix(name, path, "/", true) ResourceDef::with_prefix(name, 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(name: &str, path: &str) -> Self {
let mut resource = Resource::with_prefix(name, path, "/", false); let mut resource = ResourceDef::with_prefix(name, path, "/", false);
resource.rtp = ResourceType::External; resource.rtp = ResourceType::External;
resource resource
} }
@ -277,7 +277,7 @@ impl 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(name: &str, path: &str, prefix: &str, for_prefix: bool) -> Self {
let (pattern, elements, is_dynamic, len) = let (pattern, elements, is_dynamic, len) =
Resource::parse(path, prefix, for_prefix); ResourceDef::parse(path, prefix, for_prefix);
let tp = if is_dynamic { let tp = if is_dynamic {
let re = match Regex::new(&pattern) { let re = match Regex::new(&pattern) {
@ -296,7 +296,7 @@ impl Resource {
PatternType::Static(pattern.clone()) PatternType::Static(pattern.clone())
}; };
Resource { ResourceDef {
tp, tp,
elements, elements,
name: name.into(), name: name.into(),
@ -571,15 +571,15 @@ impl Resource {
} }
} }
impl PartialEq for Resource { impl PartialEq for ResourceDef {
fn eq(&self, other: &Resource) -> bool { fn eq(&self, other: &ResourceDef) -> bool {
self.pattern == other.pattern self.pattern == other.pattern
} }
} }
impl Eq for Resource {} impl Eq for ResourceDef {}
impl Hash for Resource { impl Hash for ResourceDef {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.pattern.hash(state); self.pattern.hash(state);
} }
@ -593,34 +593,34 @@ mod tests {
#[test] #[test]
fn test_recognizer10() { fn test_recognizer10() {
let routes = vec![ let routes = vec![
(Resource::new("", "/name"), Some(ResourceHandler::default())), (ResourceDef::new("", "/name"), Some(Resource::default())),
( (
Resource::new("", "/name/{val}"), ResourceDef::new("", "/name/{val}"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("", "/name/{val}/index.html"), ResourceDef::new("", "/name/{val}/index.html"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("", "/file/{file}.{ext}"), ResourceDef::new("", "/file/{file}.{ext}"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("", "/v{val}/{val2}/index.html"), ResourceDef::new("", "/v{val}/{val2}/index.html"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("", "/v/{tail:.*}"), ResourceDef::new("", "/v/{tail:.*}"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("", "/test2/{test}.html"), ResourceDef::new("", "/test2/{test}.html"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("", "{test}/index.html"), ResourceDef::new("", "{test}/index.html"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
]; ];
let (rec, _) = Router::new::<()>("", routes); let (rec, _) = Router::new::<()>("", routes);
@ -681,12 +681,12 @@ mod tests {
fn test_recognizer_2() { fn test_recognizer_2() {
let routes = vec![ let routes = vec![
( (
Resource::new("", "/index.json"), ResourceDef::new("", "/index.json"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("", "/{source}.json"), ResourceDef::new("", "/{source}.json"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
]; ];
let (rec, _) = Router::new::<()>("", routes); let (rec, _) = Router::new::<()>("", routes);
@ -701,10 +701,10 @@ mod tests {
#[test] #[test]
fn test_recognizer_with_prefix() { fn test_recognizer_with_prefix() {
let routes = vec![ let routes = vec![
(Resource::new("", "/name"), Some(ResourceHandler::default())), (ResourceDef::new("", "/name"), Some(Resource::default())),
( (
Resource::new("", "/name/{val}"), ResourceDef::new("", "/name/{val}"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
]; ];
let (rec, _) = Router::new::<()>("/test", routes); let (rec, _) = Router::new::<()>("/test", routes);
@ -724,10 +724,10 @@ mod tests {
// same patterns // same patterns
let routes = vec![ let routes = vec![
(Resource::new("", "/name"), Some(ResourceHandler::default())), (ResourceDef::new("", "/name"), Some(Resource::default())),
( (
Resource::new("", "/name/{val}"), ResourceDef::new("", "/name/{val}"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
]; ];
let (rec, _) = Router::new::<()>("/test2", routes); let (rec, _) = Router::new::<()>("/test2", routes);
@ -747,29 +747,29 @@ mod tests {
#[test] #[test]
fn test_parse_static() { fn test_parse_static() {
let re = Resource::new("test", "/"); let re = ResourceDef::new("test", "/");
assert!(re.is_match("/")); assert!(re.is_match("/"));
assert!(!re.is_match("/a")); assert!(!re.is_match("/a"));
let re = Resource::new("test", "/name"); let re = ResourceDef::new("test", "/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 = Resource::new("test", "/name/"); let re = ResourceDef::new("test", "/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 = Resource::new("test", "/user/profile"); let re = ResourceDef::new("test", "/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 = Resource::new("test", "/user/{id}"); let re = ResourceDef::new("test", "/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 +783,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 = Resource::new("test", "/v{version}/resource/{id}"); let re = ResourceDef::new("test", "/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 +796,14 @@ mod tests {
#[test] #[test]
fn test_resource_prefix() { fn test_resource_prefix() {
let re = Resource::prefix("test", "/name"); let re = ResourceDef::prefix("test", "/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 = Resource::prefix("test", "/name/"); let re = ResourceDef::prefix("test", "/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 +811,7 @@ mod tests {
#[test] #[test]
fn test_reousrce_prefix_dynamic() { fn test_reousrce_prefix_dynamic() {
let re = Resource::prefix("test", "/{name}/"); let re = ResourceDef::prefix("test", "/{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"));
@ -831,12 +831,12 @@ mod tests {
fn test_request_resource() { fn test_request_resource() {
let routes = vec![ let routes = vec![
( (
Resource::new("r1", "/index.json"), ResourceDef::new("r1", "/index.json"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
( (
Resource::new("r2", "/test.json"), ResourceDef::new("r2", "/test.json"),
Some(ResourceHandler::default()), Some(Resource::default()),
), ),
]; ];
let (router, _) = Router::new::<()>("", routes); let (router, _) = Router::new::<()>("", routes);

View file

@ -14,14 +14,14 @@ use middleware::{
Started as MiddlewareStarted, Started as MiddlewareStarted,
}; };
use pred::Predicate; use pred::Predicate;
use resource::{ResourceHandler, RouteId}; use resource::{Resource, RouteId};
use router::Resource; use router::ResourceDef;
use server::Request; use server::Request;
type ScopeResource<S> = Rc<ResourceHandler<S>>; type ScopeResource<S> = Rc<Resource<S>>;
type Route<S> = Box<RouteHandler<S>>; type Route<S> = Box<RouteHandler<S>>;
type ScopeResources<S> = Rc<Vec<(Resource, ScopeResource<S>)>>; type ScopeResources<S> = Rc<Vec<(ResourceDef, ScopeResource<S>)>>;
type NestedInfo<S> = (Resource, Route<S>, Vec<Box<Predicate<S>>>); type NestedInfo<S> = (ResourceDef, Route<S>, Vec<Box<Predicate<S>>>);
/// Resources scope /// Resources scope
/// ///
@ -147,7 +147,7 @@ impl<S: 'static> Scope<S> {
})]; })];
let handler = Box::new(Wrapper { scope, state }); let handler = Box::new(Wrapper { scope, state });
self.nested self.nested
.push((Resource::prefix("", &path), handler, filters)); .push((ResourceDef::prefix("", &path), handler, filters));
self self
} }
@ -185,7 +185,7 @@ impl<S: 'static> Scope<S> {
let filters = scope.take_filters(); let filters = scope.take_filters();
self.nested self.nested
.push((Resource::prefix("", &path), Box::new(scope), filters)); .push((ResourceDef::prefix("", &path), Box::new(scope), filters));
self self
} }
@ -244,9 +244,9 @@ impl<S: 'static> Scope<S> {
} }
} }
} else { } else {
let mut handler = ResourceHandler::default(); let mut handler = Resource::default();
handler.method(method).with(f); handler.method(method).with(f);
let pattern = Resource::with_prefix( let pattern = ResourceDef::with_prefix(
handler.get_name(), handler.get_name(),
path, path,
if path.is_empty() { "" } else { "/" }, if path.is_empty() { "" } else { "/" },
@ -284,13 +284,13 @@ impl<S: 'static> Scope<S> {
/// ``` /// ```
pub fn resource<F, R>(mut self, path: &str, f: F) -> Scope<S> pub fn resource<F, R>(mut self, path: &str, f: F) -> Scope<S>
where where
F: FnOnce(&mut ResourceHandler<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
// add resource handler // add resource handler
let mut handler = ResourceHandler::default(); let mut handler = Resource::default();
f(&mut handler); f(&mut handler);
let pattern = Resource::with_prefix( let pattern = ResourceDef::with_prefix(
handler.get_name(), handler.get_name(),
path, path,
if path.is_empty() { "" } else { "/" }, if path.is_empty() { "" } else { "/" },
@ -306,10 +306,10 @@ impl<S: 'static> Scope<S> {
/// Default resource to be used if no matching route could be found. /// Default resource to be used if no matching route could be found.
pub fn default_resource<F, R>(mut self, f: F) -> Scope<S> pub fn default_resource<F, R>(mut self, f: F) -> Scope<S>
where where
F: FnOnce(&mut ResourceHandler<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
if self.default.is_none() { if self.default.is_none() {
self.default = Some(Rc::new(ResourceHandler::default_not_found())); self.default = Some(Rc::new(Resource::default_not_found()));
} }
{ {
let default = Rc::get_mut(self.default.as_mut().unwrap()) let default = Rc::get_mut(self.default.as_mut().unwrap())
@ -439,7 +439,7 @@ struct ComposeInfo<S: 'static> {
id: RouteId, id: RouteId,
req: HttpRequest<S>, req: HttpRequest<S>,
mws: Rc<Vec<Box<Middleware<S>>>>, mws: Rc<Vec<Box<Middleware<S>>>>,
resource: Rc<ResourceHandler<S>>, resource: Rc<Resource<S>>,
} }
enum ComposeState<S: 'static> { enum ComposeState<S: 'static> {
@ -465,7 +465,7 @@ 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>>>>, id: RouteId, req: HttpRequest<S>, mws: Rc<Vec<Box<Middleware<S>>>>,
resource: Rc<ResourceHandler<S>>, resource: Rc<Resource<S>>,
) -> Self { ) -> Self {
let mut info = ComposeInfo { let mut info = ComposeInfo {
id, id,

View file

@ -27,7 +27,7 @@ use httpresponse::HttpResponse;
use middleware::Middleware; use middleware::Middleware;
use param::Params; use param::Params;
use payload::Payload; use payload::Payload;
use resource::ResourceHandler; use resource::Resource;
use router::Router; use router::Router;
use server::message::{Request, RequestPool}; use server::message::{Request, RequestPool};
use server::{HttpServer, IntoHttpHandler, ServerSettings}; use server::{HttpServer, IntoHttpHandler, ServerSettings};
@ -353,7 +353,7 @@ impl<S: 'static> TestApp<S> {
/// to `App::resource()` method. /// to `App::resource()` method.
pub fn resource<F, R>(&mut self, path: &str, f: F) -> &mut TestApp<S> pub fn resource<F, R>(&mut self, path: &str, f: F) -> &mut TestApp<S>
where where
F: FnOnce(&mut ResourceHandler<S>) -> R + 'static, F: FnOnce(&mut Resource<S>) -> R + 'static,
{ {
self.app = Some(self.app.take().unwrap().resource(path, f)); self.app = Some(self.app.take().unwrap().resource(path, f));
self self