use crate::http::header::HTTPResponseHeaders;
use crate::http::response::HTTPResponse;
use crate::http::Body;
use crate::http::StatusCode;
use crate::RSWEB_SERVER_STR;
use std::collections::HashMap;
use wildmatch::WildMatch;
#[derive(Debug, PartialEq, Clone)]
pub enum Route {
Route(HTTPResponse),
Alias(String),
}
#[derive(Clone)]
pub struct Router {
routemap: HashMap<String, String>,
aliasmap: HashMap<String, String>,
}
impl Router {
#[allow(unused_variables)]
pub fn new() -> Router {
Router {
routemap: HashMap::new(),
aliasmap: HashMap::new(),
}
}
pub fn route(&mut self, from: String, to: String) {
self.routemap.insert(from, to);
}
pub fn alias(&mut self, key: String, alias: String) {
self.aliasmap.insert(key, alias);
}
pub fn lookup(&self, pattern: &str) -> Option<Route> {
let mut resp: Option<Route> = None;
for key in self.routemap.keys() {
if WildMatch::new(key.as_str()).matches(pattern) {
let body = Body::new(String::new());
let loc = self.routemap.get(key.as_str()).unwrap();
resp = Some(Route::Route(HTTPResponse::new(
StatusCode::Found,
vec![
HTTPResponseHeaders::Location(loc.to_string()),
HTTPResponseHeaders::Server(RSWEB_SERVER_STR.to_string()),
],
body,
)));
break;
}
}
if resp.is_none() {
for alias in self.aliasmap.keys() {
if WildMatch::new(alias.as_str()).matches(pattern) {
resp = Some(Route::Alias(self.aliasmap.get(alias).unwrap().to_string()));
break;
}
}
}
resp
}
}