1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-09-02 17:46:38 +02:00

drop hyper

This commit is contained in:
Nikolay Kim
2017-10-09 23:07:32 -07:00
parent 994a9e907e
commit 676347d7f6
11 changed files with 218 additions and 192 deletions

View File

@@ -16,6 +16,7 @@ use httpmessage::HttpRequest;
pub struct Application<S=()> {
state: S,
default: Resource<S>,
handlers: HashMap<String, Box<RouteHandler<S>>>,
resources: HashMap<String, Resource<S>>,
}
@@ -23,6 +24,7 @@ impl<S> Application<S> where S: 'static
{
pub(crate) fn prepare(self, prefix: String) -> Box<Handler> {
let mut router = Router::new();
let mut handlers = HashMap::new();
let prefix = if prefix.ends_with('/') {prefix } else { prefix + "/" };
for (path, handler) in self.resources {
@@ -30,10 +32,16 @@ impl<S> Application<S> where S: 'static
router.add(path.as_str(), handler);
}
for (path, mut handler) in self.handlers {
let path = prefix.clone() + path.trim_left_matches('/');
handler.set_prefix(path.clone());
handlers.insert(path, handler);
}
Box::new(
InnerApplication {
state: Rc::new(self.state),
default: self.default,
handlers: handlers,
router: router }
)
}
@@ -46,6 +54,7 @@ impl Default for Application<()> {
Application {
state: (),
default: Resource::default(),
handlers: HashMap::new(),
resources: HashMap::new(),
}
}
@@ -60,6 +69,7 @@ impl<S> Application<S> where S: 'static {
Application {
state: state,
default: Resource::default(),
handlers: HashMap::new(),
resources: HashMap::new(),
}
}
@@ -77,6 +87,20 @@ impl<S> Application<S> where S: 'static {
self.resources.get_mut(&path).unwrap()
}
/// Add path handler
pub fn add_handler<H, P>(&mut self, path: P, h: H)
where H: RouteHandler<S> + 'static, P: ToString
{
let path = path.to_string();
// add resource
if self.handlers.contains_key(&path) {
panic!("Handler already registered: {:?}", path);
}
self.handlers.insert(path, Box::new(h));
}
/// Default resource is used if no matches route could be found.
pub fn default_resource(&mut self) -> &mut Resource<S> {
&mut self.default
@@ -88,6 +112,7 @@ pub(crate)
struct InnerApplication<S> {
state: Rc<S>,
default: Resource<S>,
handlers: HashMap<String, Box<RouteHandler<S>>>,
router: Router<Resource<S>>,
}
@@ -98,6 +123,11 @@ impl<S: 'static> Handler for InnerApplication<S> {
if let Ok(h) = self.router.recognize(req.path()) {
h.handler.handle(req.with_params(h.params), payload, Rc::clone(&self.state))
} else {
for (prefix, handler) in &self.handlers {
if req.path().starts_with(prefix) {
return handler.handle(req, payload, Rc::clone(&self.state))
}
}
self.default.handle(req, payload, Rc::clone(&self.state))
}
}