diff --git a/src/routing/mod.rs b/src/routing/mod.rs index d3fa15ff5030dccc4162756be7c3e0f264472775..8638aa198c483512c2c82bdb8436c8cd8af9c973 100644 --- a/src/routing/mod.rs +++ b/src/routing/mod.rs @@ -2,3 +2,7 @@ pub mod mock_upload; pub mod request; pub mod scripting; pub mod core; + +mod request_rewriter; + +pub use self::request_rewriter::{ScriptMap, RedirectScripts}; diff --git a/src/routing/request_rewriter.rs b/src/routing/request_rewriter.rs new file mode 100644 index 0000000000000000000000000000000000000000..eaa43706e9ea37a49c1e97208d3f5acd403ca5b7 --- /dev/null +++ b/src/routing/request_rewriter.rs @@ -0,0 +1,56 @@ +use rocket::fairing::{Fairing, Info, Kind}; +use rocket::{Request, Data, Rocket, State}; +use cli::SwerveConfig; +use std::collections::HashMap; +use routing::request::path::MatchablePath; + +pub struct ScriptMap(pub HashMap<MatchablePath, String>); +impl ScriptMap { + pub fn from_config(conf: &SwerveConfig) -> Self { + let mut map: HashMap<MatchablePath, String> = HashMap::new(); + + for handler in &conf.routes { + if let Some(ref script) = handler.script { + map.insert(MatchablePath::from(handler.route.clone()), script.clone()); + } + } + + ScriptMap(map) + } +} + +pub struct RedirectScripts; +impl Fairing for RedirectScripts { + fn info(&self) -> Info { + Info { + name: "Redirect Scripts To Handler", + kind: Kind::Request, + } + } + + fn on_request(&self, request: &mut Request, _: &Data) { + let script_map_container = request.guard::<State<ScriptMap>>().unwrap(); + let script_map: &HashMap<MatchablePath, String> = &script_map_container.0; + for path in script_map.keys() { + let matches = path.matches(request.uri().path()); + if let Some(values) = matches { + let script_name = script_map.get(path).unwrap(); + + let mut value_buffer = String::new(); + value_buffer.push_str("script_path="); + value_buffer.push_str(script_name); + + for (ref param, ref val) in values { + value_buffer.push_str("&"); + value_buffer.push_str(param); + value_buffer.push_str("="); + value_buffer.push_str(val); + } + + let path = format!("/__run_script__/?{}", value_buffer); + request.set_uri(path); + break; + } + } + } +} \ No newline at end of file