1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use hyper::{Method, StatusCode};
use futures::{Future, IntoFuture};
use std::collections::HashMap;
use recognizer::{Match, Router as Recognizer};
use proto::{ArcHandler, ArcService, MiddleWare};
use routing::{RouteGroup, stripTrailingSlash};
use core::{Request, Response};
use std::sync::Arc;

/// The main router of you application
/// that is supplied to the ArcReactor.
pub struct Router {
	pub(crate) routes: HashMap<Method, Recognizer<ArcHandler>>,
	pub(crate) before: Option<Arc<Box<MiddleWare<Request>>>>,
	pub(crate) after: Option<Arc<Box<MiddleWare<Response>>>>,
	pub(crate) notFound: Option<Box<ArcService>>,
}

impl Router {
	/// construct a new Router.
	pub fn new() -> Self {
		Self {
			before: None,
			routes: HashMap::new(),
			after: None,
			notFound: None,
		}
	}


	/// Mount a routegroup on this router.
	/// It will apply the middlewares already mounted
	/// on the `Router` to all the routes on the `RouteGroup`
	///
	/// ```
	///  let router = Router::new();
	///  router.get("/users", UserService); // this will match "/users"
	///
	/// let nestedgroup = RouteGroup::new("admin");
	///  // by nesting it on `router`, this will match "/admin/delete/user"
	///  let nestedgroup.get("/delete/user", DeleteService);
	///
	///  router.group(nestedgroup);
	/// ```
	pub fn group(mut self, group: RouteGroup) -> Self {
		let RouteGroup { routes, .. } = group;
		{
			for (method, map) in routes.into_iter() {
				for (path, routehandler) in map {
					let handler = ArcHandler {
						before: self.before.clone(),
						handler: Arc::new(box routehandler),
						after: self.after.clone(),
					};

					self
						.routes
						.entry(method.clone())
						.or_insert(Recognizer::new())
						.add(path.as_str(), handler)
				}
			}
		}

		self
	}

	/// mount a request middleware on this router
	///
	/// ensure that the request middleware is added before any routes on the router.
	/// the middleware only applies to the routes that are added after it has been mounted.
	pub fn before<T: 'static + MiddleWare<Request>>(mut self, before: T) -> Self {
		self.before = Some(Arc::new(box before));

		self
	}

	/// mount a reesponse middleware on this router
	///
	/// ensure that the request middleware is added before any routes on the router.
	/// the middleware only applies to the routes that are added after it has been mounted.
	pub fn after<T: 'static + MiddleWare<Response>>(mut self, after: T) -> Self {
		self.after = Some(Arc::new(box after));

		self
	}

	/// add a route and a ServiceHandler for a get request
	pub fn get<S>(self, route: &'static str, handler: S) -> Self
	where
		S: ArcService + 'static + Send + Sync,
	{
		self.route(Method::Get, route, handler)
	}

	/// add a route and a ServiceHandler for a post request
	pub fn post<S>(self, route: &'static str, handler: S) -> Self
	where
		S: ArcService + 'static + Send + Sync,
	{
		self.route(Method::Post, route, handler)
	}

	/// add a route and a ServiceHandler for a put request
	pub fn put<S>(self, route: &'static str, handler: S) -> Self
	where
		S: ArcService + 'static + Send + Sync,
	{
		self.route(Method::Put, route, handler)
	}

	/// add a route and a ServiceHandler for a patch request
	pub fn patch<S>(self, route: &'static str, handler: S) -> Self
	where
		S: ArcService + 'static + Send + Sync,
	{
		self.route(Method::Patch, route, handler)
	}

	/// add a route and a ServiceHandler for a delete request
	pub fn delete<S>(self, route: &'static str, handler: S) -> Self
	where
		S: ArcService + 'static + Send + Sync,
	{
		self.route(Method::Delete, route, handler)
	}

	/// add a 404 handler
	pub fn notFound<S>(mut self, handler: S) -> Self
	where
		S: ArcService + 'static + Send + Sync,
	{
		self.notFound = Some(box handler);

		self
	}

	fn route<S>(mut self, method: Method, path: &'static str, routehandler: S) -> Self
	where
		S: ArcService + 'static + Send + Sync,
	{
		{
			let handler = ArcHandler {
				before: self.before.clone(),
				handler: Arc::new(box routehandler),
				after: self.after.clone(),
			};
			self
				.routes
				.entry(method)
				.or_insert(Recognizer::new())
				.add(path.as_ref(), handler);
		}

		self
	}

	pub(crate) fn matchRoute<P>(&self, route: P, method: &Method) -> Option<Match<&ArcHandler>>
	where
		P: AsRef<str>,
	{
		let route = stripTrailingSlash(route.as_ref());
		self
			.routes
			.get(method)
			.and_then(|recognizer| recognizer.recognize(route).ok())
	}
}

impl ArcService for Router {
	fn call(&self, req: Request, res: Response) -> Box<Future<Item = Response, Error = Response>> {
		if let Some(routeMatch) = self.matchRoute(req.path(), req.method()) {
			let mut request: Request = req.into();
			request.set(routeMatch.params);

			return box ArcService::call(&*routeMatch.handler, request, res);
		} else {
			if let Some(ref notFound) = self.notFound {
				return notFound.call(req, res);
			}
			return box Ok(Response::new().with_status(StatusCode::NotFound)).into_future();
		}
	}
}