ilmen_http/http/router/structs/
request_handler.rs1use std::collections::HashMap;
2
3use crate::{http::HTTPRequest, Route};
4
5pub struct RequestHandler {
6 request: HTTPRequest,
7 path_params: PathParams
8}
9
10type PathParams = HashMap<String, String>;
11type QueryParams = HashMap<String, String>;
12
13impl RequestHandler {
14 pub fn query_params(&self) -> Option<QueryParams> {
15 self.request.query_params.clone()
16 }
17
18 pub fn path_params(&self) -> PathParams {
19 self.path_params.clone()
20 }
21
22 pub fn body(&self) -> Option<String> {
23 self.request.body.clone()
24 }
25}
26
27impl From<(&HTTPRequest, &Route)> for RequestHandler {
28 fn from(value: (&HTTPRequest, &Route)) -> Self {
29 RequestHandler {
30 request: value.0.clone(),
31 path_params: extract_path_params(&value.0.resource, &value.1.route)
32 }
33 }
34}
35
36fn extract_path_params(request: &String, template: &String) -> PathParams {
37 let split_request = request.split("/").collect::<Vec<&str>>();
38 template.split("/").enumerate()
39 .filter(|(_, key)| key.starts_with("{") && key.ends_with("}"))
40 .map(|(index, key)| (key.to_string().drain(1..key.len()-1).collect(), split_request.get(index).unwrap().to_string()))
41 .collect::<PathParams>()
42}
43
44
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn extract_path_params_multiple_params() {
52 let request = "base/3/another/tata";
53 let template = "base/{id}/another/{name}";
54 let mut expected = HashMap::new();
55 expected.insert("id".to_string(), "3".to_string());
56 expected.insert("name".to_string(), "tata".to_string());
57
58 let result = extract_path_params(&request.to_string(),&template.to_string());
59 assert_eq!(result,expected)
60 }
61
62}