titan_http/request/
parser_from_str.rs

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
use std::str::FromStr as _;

use super::Request;
use http::{Error, HeaderMap, HeaderValue, Method, Uri};

pub struct HttpRequestExt(pub Request);

impl From<String> for HttpRequestExt {
  fn from(value: String) -> Self {
    HttpRequestExt(from_string(value).unwrap())
  }
}

fn format_headers(
  iter: impl Iterator<Item = String>,
) -> HeaderMap<HeaderValue> {
  let formated = iter.filter_map(|line| {
    let mut parts: Vec<&str> = line.split(": ").collect();
    let key = parts.remove(0);

    match key.parse() {
      Ok(key) => Some((key, parts[0].to_string().parse().unwrap())),
      Err(_err) => None,
    }
  });

  HeaderMap::from_iter(formated)
}

fn from_string(str_request: String) -> Result<Request, Error> {
  let mut http_req: Vec<String> =
    str_request.split('\n').map(|v| v.to_string()).collect();

  let http_meta = http_req.swap_remove(0);
  let parts: Vec<&str> = http_meta.split_whitespace().collect();

  let method = Method::from_str(parts[0]).unwrap();
  let uri = Uri::from_str(parts[1]).unwrap();

  let headers = format_headers(http_req.into_iter());

  let mut req_builder = http::Request::builder().uri(uri).method(method);

  *req_builder.headers_mut().unwrap() = headers;

  req_builder.body([].into())
}