Skip to main content

rns_ctl/
http.rs

1use std::collections::HashMap;
2use std::io::{self, BufRead, BufReader, Read, Write};
3
4/// Parsed HTTP request.
5pub struct HttpRequest {
6    pub method: String,
7    pub path: String,
8    pub query: String,
9    pub headers: HashMap<String, String>,
10    pub body: Vec<u8>,
11}
12
13/// HTTP response.
14pub struct HttpResponse {
15    pub status: u16,
16    pub status_text: &'static str,
17    pub headers: Vec<(String, String)>,
18    pub body: Vec<u8>,
19}
20
21impl HttpResponse {
22    pub fn json(status: u16, status_text: &'static str, body: &serde_json::Value) -> Self {
23        let body_bytes = serde_json::to_vec(body).unwrap_or_default();
24        HttpResponse {
25            status,
26            status_text,
27            headers: vec![
28                ("Content-Type".into(), "application/json".into()),
29                ("Content-Length".into(), body_bytes.len().to_string()),
30                ("Connection".into(), "close".into()),
31            ],
32            body: body_bytes,
33        }
34    }
35
36    pub fn ok(body: serde_json::Value) -> Self {
37        Self::json(200, "OK", &body)
38    }
39
40    pub fn html(body: &str) -> Self {
41        Self::bytes(
42            200,
43            "OK",
44            "text/html; charset=utf-8",
45            body.as_bytes().to_vec(),
46        )
47    }
48
49    pub fn created(body: serde_json::Value) -> Self {
50        Self::json(201, "Created", &body)
51    }
52
53    pub fn bad_request(msg: &str) -> Self {
54        Self::json(400, "Bad Request", &serde_json::json!({"error": msg}))
55    }
56
57    pub fn unauthorized(msg: &str) -> Self {
58        Self::json(401, "Unauthorized", &serde_json::json!({"error": msg}))
59    }
60
61    pub fn conflict(msg: &str) -> Self {
62        Self::json(409, "Conflict", &serde_json::json!({"error": msg}))
63    }
64
65    pub fn not_found() -> Self {
66        Self::json(404, "Not Found", &serde_json::json!({"error": "Not found"}))
67    }
68
69    pub fn internal_error(msg: &str) -> Self {
70        Self::json(
71            500,
72            "Internal Server Error",
73            &serde_json::json!({"error": msg}),
74        )
75    }
76
77    pub fn bytes(
78        status: u16,
79        status_text: &'static str,
80        content_type: &'static str,
81        body: Vec<u8>,
82    ) -> Self {
83        HttpResponse {
84            status,
85            status_text,
86            headers: vec![
87                ("Content-Type".into(), content_type.into()),
88                ("Content-Length".into(), body.len().to_string()),
89                ("Connection".into(), "close".into()),
90            ],
91            body,
92        }
93    }
94}
95
96/// Parse an HTTP/1.1 request from a stream.
97pub fn parse_request(stream: &mut dyn Read) -> io::Result<HttpRequest> {
98    let mut reader = BufReader::new(stream);
99
100    // Read request line
101    let mut request_line = String::new();
102    reader.read_line(&mut request_line)?;
103    let request_line = request_line.trim_end();
104
105    if request_line.is_empty() {
106        return Err(io::Error::new(
107            io::ErrorKind::UnexpectedEof,
108            "Empty request",
109        ));
110    }
111
112    let parts: Vec<&str> = request_line.splitn(3, ' ').collect();
113    if parts.len() < 2 {
114        return Err(io::Error::new(
115            io::ErrorKind::InvalidData,
116            "Invalid request line",
117        ));
118    }
119
120    let method = parts[0].to_string();
121    let full_path = parts[1];
122
123    let (path, query) = if let Some(pos) = full_path.find('?') {
124        (
125            full_path[..pos].to_string(),
126            full_path[pos + 1..].to_string(),
127        )
128    } else {
129        (full_path.to_string(), String::new())
130    };
131
132    // Read headers
133    let mut headers = HashMap::new();
134    loop {
135        let mut line = String::new();
136        reader.read_line(&mut line)?;
137        let line = line.trim_end();
138        if line.is_empty() {
139            break;
140        }
141        if let Some(colon) = line.find(':') {
142            let key = line[..colon].trim().to_lowercase();
143            let value = line[colon + 1..].trim().to_string();
144            headers.insert(key, value);
145        }
146    }
147
148    // Read body based on Content-Length
149    let body = if let Some(len_str) = headers.get("content-length") {
150        if let Ok(len) = len_str.parse::<usize>() {
151            let mut body = vec![0u8; len];
152            reader.read_exact(&mut body)?;
153            body
154        } else {
155            Vec::new()
156        }
157    } else {
158        Vec::new()
159    };
160
161    Ok(HttpRequest {
162        method,
163        path,
164        query,
165        headers,
166        body,
167    })
168}
169
170/// Write an HTTP response to a stream.
171pub fn write_response(stream: &mut dyn Write, response: &HttpResponse) -> io::Result<()> {
172    write!(
173        stream,
174        "HTTP/1.1 {} {}\r\n",
175        response.status, response.status_text
176    )?;
177    for (key, value) in &response.headers {
178        write!(stream, "{}: {}\r\n", key, value)?;
179    }
180    write!(stream, "\r\n")?;
181    stream.write_all(&response.body)?;
182    stream.flush()
183}
184
185/// Parse query string parameters.
186pub fn parse_query(query: &str) -> HashMap<String, String> {
187    let mut params = HashMap::new();
188    if query.is_empty() {
189        return params;
190    }
191    for pair in query.split('&') {
192        if let Some(eq) = pair.find('=') {
193            let key = pair[..eq].to_string();
194            let value = pair[eq + 1..].to_string();
195            params.insert(key, value);
196        } else if !pair.is_empty() {
197            params.insert(pair.to_string(), String::new());
198        }
199    }
200    params
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn parse_query_basic() {
209        let q = parse_query("foo=bar&baz=123&flag");
210        assert_eq!(q.get("foo").unwrap(), "bar");
211        assert_eq!(q.get("baz").unwrap(), "123");
212        assert!(q.contains_key("flag"));
213    }
214
215    #[test]
216    fn parse_query_empty() {
217        let q = parse_query("");
218        assert!(q.is_empty());
219    }
220
221    #[test]
222    fn parse_request_get() {
223        let raw = b"GET /api/info?verbose=true HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer abc\r\n\r\n";
224        let req = parse_request(&mut &raw[..]).unwrap();
225        assert_eq!(req.method, "GET");
226        assert_eq!(req.path, "/api/info");
227        assert_eq!(req.query, "verbose=true");
228        assert_eq!(req.headers.get("authorization").unwrap(), "Bearer abc");
229        assert!(req.body.is_empty());
230    }
231
232    #[test]
233    fn parse_request_post_with_body() {
234        let body = r#"{"key":"value"}"#;
235        let raw = format!(
236            "POST /api/send HTTP/1.1\r\nContent-Length: {}\r\n\r\n{}",
237            body.len(),
238            body
239        );
240        let req = parse_request(&mut raw.as_bytes()).unwrap();
241        assert_eq!(req.method, "POST");
242        assert_eq!(req.path, "/api/send");
243        assert_eq!(req.body, body.as_bytes());
244    }
245
246    #[test]
247    fn response_json() {
248        let resp = HttpResponse::ok(serde_json::json!({"status": "ok"}));
249        assert_eq!(resp.status, 200);
250        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
251        assert_eq!(body["status"], "ok");
252    }
253}