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
use std::collections::HashMap;
use std::sync::Arc;

use hyper::http;
use route_recognizer::{Params, Router as PathRouter};

use crate::endpoint::{DynEndpoint, Endpoint, RouterEndpoint};
use crate::middleware::{Middleware, Next};
use crate::register_method;
use crate::{Request, Response};

const NESTED_ROUTER: &str = "--nested-router";

lazy_static::lazy_static! {
    pub static ref METHOD_ANY: http::Method = http::Method::from_bytes(b"__ANY__").unwrap();
}

/// The result of routing a URL
pub(crate) struct Selection<'a> {
    pub(crate) endpoint: &'a DynEndpoint,
    pub(crate) params: Params,
}

pub struct Router {
    middlewares: Vec<Arc<dyn Middleware>>,
    handle_not_found: Box<DynEndpoint>,
    path_map: HashMap<String, HashMap<http::Method, Box<DynEndpoint>>>,
    path_router: PathRouter<HashMap<http::Method, Box<DynEndpoint>>>,
}

impl Router {
    pub fn new() -> Self {
        Router {
            middlewares: Vec::new(),
            handle_not_found: Box::new(&not_found_endpoint),
            path_map: HashMap::new(),
            path_router: PathRouter::new(),
        }
    }

    pub fn register(&mut self, method: http::Method, path: impl AsRef<str>, ep: impl Endpoint) {
        let path = path.as_ref().to_string();

        self.path_map
            .entry(path)
            .or_insert_with(HashMap::new)
            .insert(method, Box::new(ep));
    }

    register_method!(options, http::Method::OPTIONS);
    register_method!(get, http::Method::GET);
    register_method!(head, http::Method::HEAD);
    register_method!(post, http::Method::POST);
    register_method!(put, http::Method::PUT);
    register_method!(delete, http::Method::DELETE);
    register_method!(trace, http::Method::TRACE);
    register_method!(connect, http::Method::CONNECT);
    register_method!(patch, http::Method::PATCH);

    pub fn middleware(&mut self, m: impl Middleware) -> &mut Self {
        self.middlewares.push(Arc::new(m));
        self
    }

    pub fn set_not_found_handler(&mut self, ep: impl Endpoint) {
        self.handle_not_found = Box::new(ep)
    }

    pub fn merge(
        &mut self,
        prefix: impl AsRef<str>,
        router: Router,
    ) -> Result<(), crate::errors::errors::Error> {
        let prefix = prefix.as_ref();
        if !prefix.starts_with('/') || !prefix.ends_with('/') {
            return Err(crate::errors::errors::Error::Message(
                "merge nested route, prefix must be a path, start with / and end with /"
                    .to_string(),
            ));
        }

        let router = router;
        let router = Arc::new(router.finalize());

        let path = prefix.to_string() + "*" + NESTED_ROUTER;

        let mut sub: HashMap<http::Method, Box<DynEndpoint>> = HashMap::new();

        sub.insert(METHOD_ANY.clone(), Box::new(RouterEndpoint::new(router)));

        self.path_router.add(&path, sub);

        Ok(())
    }

    pub(crate) fn find(&self, path: &str, method: http::Method) -> Selection {
        match self.path_router.recognize(path) {
            Ok(m) => {
                if let Some(ep) = m.handler().get(&method) {
                    return Selection {
                        endpoint: &**ep,
                        params: m.params().clone(),
                    };
                }

                if m.handler().is_empty() {
                    Selection {
                        endpoint: &*self.handle_not_found,
                        params: Params::new(),
                    }
                } else {
                    Selection {
                        endpoint: &method_not_allowed,
                        params: Params::new(),
                    }
                }
            }
            Err(_e) => Selection {
                endpoint: &*self.handle_not_found,
                params: Params::new(),
            },
        }
    }

    pub(crate) async fn route(&self, req: Request) -> Response {
        let mut req = req;

        let method = req.method().clone();

        let path = req.route_path();
        let Selection { endpoint, params } = self.find(path, method);

        req.merge_params(&params);
        if let Some(rest) = params.find(NESTED_ROUTER) {
            req.set_route_path(rest);
        }

        let next = Next {
            endpoint,
            next_middleware: &self.middlewares,
        };

        next.run(req).await
    }

    pub(crate) fn finalize(mut self) -> Self {
        let empty: HashMap<String, HashMap<http::Method, Box<DynEndpoint>>> = HashMap::new();
        let path_map = std::mem::replace(&mut self.path_map, empty);

        for (path, method_map) in path_map.into_iter() {
            self.path_router.add(&path, method_map)
        }

        self
    }
}

impl Default for Router {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for Router {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Router{{ middlewares: (length: {}) }}",
            self.middlewares.len()
        )
    }
}

async fn not_found_endpoint(_ctx: Request) -> Response {
    http::StatusCode::NOT_FOUND.into()
}

async fn method_not_allowed(_ctx: Request) -> Response {
    http::StatusCode::METHOD_NOT_ALLOWED.into()
}