webframework_core/
router.rs

1use crate::response::Response;
2use crate::request::Request;
3
4use std::collections::HashMap;
5
6use failure::{Error, Context};
7use futures::Future;
8use http;
9
10pub type RouterFuture = Box<dyn Future<Item = Response, Error = Error> + Send>;
11
12#[derive(Debug, Clone)]
13pub struct RouteDetail {
14    pub filters: Vec<String>,
15    pub method: Option<http::Method>,
16    pub specialisation: Vec<String>,
17}
18
19#[derive(Debug, Clone)]
20pub enum Route {
21    Route(RouteDetail),
22    Map(Box<RouterMap>),
23}
24
25pub type RouterMap = HashMap<String, Route>;
26
27pub enum RouterResult {
28    Handled(RouterFuture),
29    Unhandled(Request, HashMap<String, String>)
30}
31
32pub trait Router: Clone {
33    fn handle(&self, req: Request, path: Option<String>, params: HashMap<String, String>) -> RouterResult;
34    /// Returns a tree of routes by filters
35    fn router_map(&self) -> Option<RouterMap> {
36        None
37    }
38}
39
40impl RouterResult {
41    pub fn is_handled(&self) -> bool {
42        match self {
43            RouterResult::Handled(_) => true,
44            _ => false,
45        }
46    }
47
48    pub fn is_unhandled(&self) -> bool {
49        match self {
50            RouterResult::Unhandled(_,_) => true,
51            _ => false,
52        }
53    }
54}
55
56#[derive(Clone, Eq, PartialEq, Debug, Fail)]
57pub enum RouterErrorKind {
58    #[fail(display="an error occured while handling request")]
59    InnerError,
60}
61
62#[derive(Debug)]
63pub struct RouterError {
64    inner: Context<RouterErrorKind>,
65}
66
67impl_fail_boilerplate!(RouterErrorKind, RouterError);