summaryrefslogtreecommitdiff
path: root/src/request.rs
blob: f3375565ce922cccb61264c24647178bb2078b09 (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::str::FromStr;
use crate::{version::Version, method::Method, uri::URI, header::{HeaderMap, Header}, error::HTTPError, parse::TryParse};

pub struct Request<T: ToString + FromStr> { 
    pub method: Method,
    pub uri: URI,
    pub version: Version,
    pub headers: HeaderMap,
    pub body: Option<T>
}

impl<T: ToString + FromStr> TryParse for Request<T> {
    fn try_parse(s: impl Into<String>) -> Result<Self, HTTPError> {
        let s = s.into();
        let mut lines = s.lines();
        let Some(head) = lines.next() else {
            return Err(HTTPError::MissingHeader)
        };
    
        let mut head_parts = head.split_whitespace();
        let err = HTTPError::InvalidHeader(s.clone());

        let Some(method_str) = head_parts.next() else { return Err(err) };
        let method = method_str.into();
        
        let Some(uri_str) = head_parts.next() else { return Err(err) };
        let uri = uri_str.try_into()?;
        
        let Some(version_str) = head_parts.next() else { return Err(err) };
        let version = version_str.into();
        
        let mut headers = HeaderMap::new();

        loop {
            let Some(next) = lines.next() else {
                return Err(HTTPError::MissingHeaderBreak)
            };

            if next.len() < 1 { break }

            let header = Header::try_parse(next)?;
            headers.insert(header);
        }

        let rest: String = lines.collect();
        let body;
        if rest.len() < 1 {
            body = None
        } else {
            body = match T::from_str(&rest) {
                Ok(body) => Some(body),
                Err(_) => return Err(HTTPError::InvalidBody)
            }
        }

        Ok(Self { method, uri, version, headers, body })
    }
}

impl<T: ToString + FromStr> ToString for Request<T> {
    fn to_string(&self) -> String {
        let mut s = String::new();
       
        s.push_str(&self.method.as_str());
        s.push(' ');
        s.push_str(&self.uri.to_string());
        s.push(' ');
        s.push_str(self.version.as_str());
        s.push_str("\r\n");
        let iter = self.headers.iter();
        for headers in iter {
            for header in headers {
                s.push_str(header.name.as_str());
                s.push_str(": ");
                s.push_str(header.value.as_str());
                s.push_str("\r\n");
            }
        }
        s.push_str("\r\n");
        if let Some(body) = &self.body {
            s.push_str(&body.to_string());
        }
        s
    }
}