async_http_router 0.0.4

a simple http_router for web server
Documentation
use crate::class_view::HttpWays;
use crate::constraint::NOTFOUND;
use crate::req_enhanced::Req;
use crate::url_match::UrlMatcher;
use hyper::{http::Result, Body, Request, Response, StatusCode};
use regex;
use std::collections::HashMap;
use std::sync::Arc;
//use tokio::sync::rwlock::RwLockReadGuard;
use tokio::sync::{RwLock, RwLockReadGuard};

pub struct Router {
    pub routes: HashMap<&'static str, Box<dyn HttpWays + Send + Sync>>,
    pub matcher: UrlMatcher,
}

pub async fn handle_url<'a>(router: Arc<Router>, req: Request<Body>) -> Result<Response<Body>> {
    let body = Body::from(NOTFOUND);
    Response::builder().status(StatusCode::NOT_FOUND).body(body)
}

impl Router {
    pub async fn handle_url(router: Arc<Router>, req: Request<Body>) -> Result<Response<Body>> {
        let url = req.uri().path();
        let url_matched = router.match_re_url(url);
        match url_matched {
            Ok(matched_pattern) => {
                let req_info = router.parse_url(url, matched_pattern);
                let handler = router.routes.get(&matched_pattern.1);
                match handler {
                    Some(func) => func.dispatch(req, matched_pattern.1).await,
                    None => {
                        let body = Body::from(NOTFOUND);
                        Response::builder().status(StatusCode::NOT_FOUND).body(body)
                    }
                }
            }
            Err(_) => {
                let body = Body::from(NOTFOUND);
                Response::builder().status(StatusCode::NOT_FOUND).body(body)
            }
        }
    }
    pub fn register(&mut self, url: &'static str, p_view: Box<dyn HttpWays + Send + Sync>) {
        self.matcher.add_url(url);
        self.routes.insert(url, p_view);
    }
    pub fn new() -> Router {
        Router {
            routes: HashMap::new(),
            matcher: UrlMatcher::new(),
        }
    }
    pub fn match_re_url<'a>(
        &'a self,
        url: &str,
    ) -> std::result::Result<(&'a regex::Regex, &'static str), &'static str> {
        self.matcher.match_url(url)
    }
    pub fn parse_url<'a>(
        &'a self,
        path: &str,
        matched_pattern: (&'a regex::Regex, &'static str),
    ) -> Req {
        // let now = Instant::now();
        let mut tt = Req::new();
        if let Some(catches) = matched_pattern.0.captures(path) {
            tt.uri = matched_pattern.1;
            for name in matched_pattern.0.capture_names() {
                match name {
                    Some(key) => tt.pram.insert(String::from(key), catches[key].to_owned()),
                    None => None,
                };
            }
        }
        tt
    }
    pub fn middleware<'a>(&'a self, req: &'a mut Request<Body>) {
        let aa = req.extensions_mut().get_mut::<Req>().unwrap();
    }
}