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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use std::collections::hash_map::HashMap;

/// Common HTTP Methods
///
/// If a method is needed, which is not specified here,
/// `Method::UNKNOWN(String)` can be used
#[derive(Debug, PartialEq)]
pub enum Method {
    GET,
    POST,
    PUT,
    PATCH,
    DELETE,
    UNKNOWN(String),
}

/// Represents a HTTP request
#[derive(Debug, PartialEq)]
pub struct Request {
    pub method: Method,
    pub path: String,
    pub version: String,
    pub body: Option<String>,
    pub headers: HashMap<String, String>,
}

impl Request {
    /// takes a request as string and parses all relevant fields
    pub fn from_string(s: String) -> Result<Self, &'static str> {
        let fields = s.split_whitespace().collect::<Vec<_>>();
        Ok(Request {
            method: parse_method(&fields)?,
            path: parse_path(&fields)?,
            version: parse_version(&fields)?,
            body: parse_body(&s),
            headers: parse_headers(&s)?,
        })
    }
}

fn parse_version(fields: &[&str]) -> Result<String, &'static str> {
    fields
        .get(2)
        .map(|&s| String::from(s))
        .ok_or("Could not parse HTTP version")
}

fn parse_path(fields: &[&str]) -> Result<String, &'static str> {
    fields
        .get(1)
        .map(|&s| String::from(s))
        .ok_or("Could not parse HTTP version")
}

fn parse_method(fields: &[&str]) -> Result<Method, &'static str> {
    match fields.get(0).cloned() {
        Some("GET") => Ok(Method::GET),
        Some("POST") => Ok(Method::POST),
        Some("PUT") => Ok(Method::PUT),
        Some("PATCH") => Ok(Method::PATCH),
        Some("DELETE") => Ok(Method::DELETE),
        // FIXME: This will recognize things as HTTP methods that are not.
        Some(method) => Ok(Method::UNKNOWN(method.to_string())),
        None => Err("Could not parse HTTP method"),
    }
}

/// Parses the body of a request
fn parse_body(s: &str) -> Option<String> {
    // RFC 7230 Section 3: Body begins after two CRLF (\r\n) sequences.
    // See: https://tools.ietf.org/html/rfc7230#section-3
    let text = s.split("\r\n\r\n").skip(1).collect::<String>();
    if text.is_empty() {
        None
    } else {
        Some(text)
    }
}

fn parse_headers(s: &str) -> Result<HashMap<String, String>, &'static str> {
    // RFC 7230 Section 3: Header section (start-line) ends, when two CRLF (\r\n) sequences are encountered.
    // See: https://tools.ietf.org/html/rfc7230#section-3
    let raw_header_section = s.split("\r\n\r\n").next().unwrap_or_default();

    // RFC 7230 Section 3.2: Each header is separated by one CRLF.
    // See: https://tools.ietf.org/html/rfc7230#section-3.2
    let raw_headers = raw_header_section.split("\r\n").skip(1).collect::<Vec<_>>();
    let mut map = HashMap::new();

    for header in raw_headers {
        let sections = header.split(':').collect::<Vec<_>>();
        let field_name = sections.get(0);
        let field_value = sections.get(1);

        // RFC 7230 Section 3.2.4: Empty header names or fields render the request invalid.
        // See: https://tools.ietf.org/html/rfc7230#section-3.2.4
        field_name
            .and(field_value)
            .ok_or("Error while parsing request headers")?;

        if let Some(field_name) = field_name {
            // RFC 7230 Section 3.2.4: No whitespace is allowed between the header field-name and colon.
            // See: https://tools.ietf.org/html/rfc7230#section-3.2.4
            if field_name
                .chars()
                .last()
                .filter(|c| c.is_whitespace())
                .is_some()
            {
                return Err("No whitespace is allowed between the header field-name and colon");
            }

            if let Some(field_value) = field_value {
                map.insert(
                    field_name.split_whitespace().collect(),
                    field_value.split_whitespace().collect(),
                );
            }
        }
    }

    Ok(map)
}

/// Represents a HTTP response
#[derive(Debug, PartialEq)]
pub struct Response {
    pub stream: String,
    pub headers: Vec<String>,
    status: u16,
}

impl Default for Response {
    fn default() -> Self {
        Response::new()
    }
}

impl Response {
    pub fn new() -> Self {
        Self {
            stream: String::new(),
            headers: Vec::new(),
            status: 200,
        }
    }

    /// Writes plain text to the response buffer
    pub fn send(&mut self, s: String) {
        self.stream.push_str(&s);
    }

    /// Change the status code of a response
    ///
    /// # Examples
    ///
    /// ```
    /// use express_rs::Express;
    ///
    /// let mut app = Express::new();
    ///
    /// app.get("/", |_, res| {
    ///     res.status(301).send("This route has a custom status code".to_string())
    /// });
    /// ```
    pub fn status(&mut self, status: u16) -> &mut Self {
        self.status = status;
        self
    }
}