rxpress 0.3.1

rxpress is an open-source server library in Rust similar to express in NodeJS. Built from the ground up with a focus on learning and building modern HTTP servers.
Documentation
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! # Request Module
//!
//! The [`Request`] struct represents an incoming HTTP request.  
//! It stores the request line, headers, body, query parameters, and path parameters.
//!
//! ## Example
//! ```no_run
//! use rxpress::Server;
//!
//! fn main() {
//!     let mut app = Server::new("3000");
//!
//!     // header() and header_or()
//!     app.get("/headers", |req, res| {
//!         // header() returns Option<&String>
//!         if let Some(ua) = req.header("user-agent") {
//!             res.send(&format!("Your User-Agent: {}", ua));
//!         } else {
//!             res.send("User-Agent header not found");
//!         }
//!         // header_or() returns default if header missing
//!         let host = req.header_or("host", "localhost");
//!         println!("Host: {}", host);
//!     });
//!
//!     // header_expect()
//!     app.get("/auth", |req, res| {
//!         match req.header_expect("Authorization") {
//!             Ok(token) => res.send(&format!("Token: {}", token)),
//!             Err(err) => res.status(400).send(&err),
//!         }
//!     });
//!
//!     // param() and param_or()
//!     app.get("/users/:id", |req, res| {
//!         // param() returns Option<&String>
//!         if let Some(id) = req.param("id") {
//!             res.send(&format!("User ID: {}", id));
//!         } else {
//!             res.send("Missing user ID");
//!         }
//!         // param_or() returns default if param missing
//!         let user_id = req.param_or("id", "0");
//!         println!("User ID (or default): {}", user_id);
//!     });
//!
//!     // param_expect()
//!     app.get("/secure/:id", |req, res| {
//!         match req.param_expect("id") {
//!             Ok(id) => res.send(&format!("Secure User ID: {}", id)),
//!             Err(err) => res.status(400).send(&err),
//!         }
//!     });
//!
//!     // query() and query_or()
//!     app.get("/search", |req, res| {
//!         // query() returns Option<&String>
//!         if let Some(q) = req.query("q") {
//!             res.send(&format!("Searching for: {}", q));
//!         } else {
//!             res.send("Missing query param `q`");
//!         }
//!         // query_or() returns default if query missing
//!         let query = req.query_or("q", "none");
//!         println!("Query (or default): {}", query);
//!     });
//!
//!     // query_expect()
//!     app.get("/secure_search", |req, res| {
//!         match req.query_expect("q") {
//!             Ok(q) => res.send(&format!("Secure search for: {}", q)),
//!             Err(err) => res.status(400).send(&err),
//!         }
//!     });
//!
//!     app.run();
//! }
//! ```

use std::collections::HashMap;

/// Represents an HTTP request.
///
/// Stores method, path, headers, query parameters, route parameters, and body.
pub struct Request {
    /// HTTP method (e.g., `GET`, `POST`)
    pub method: String,
    /// Path portion of the request (e.g., `/users/123`)
    pub path: String,
    /// Request headers
    pub headers: HashMap<String, String>,
    /// HTTP version (e.g., `HTTP/1.1`)
    pub version: String,
    /// Query parameters parsed into key-value pairs
    pub query: HashMap<String, String>,
    /// Path parameters extracted from route definitions
    pub params: HashMap<String, String>,
    /// Request body as a string
    pub body: String,
}

impl Request {
    /// Creates a new [`Request`] from raw parts.
    ///
    /// # Arguments
    /// * `request_line` - The first line of the HTTP request (`"GET /foo?bar=1 HTTP/1.1"`).
    /// * `headers` - The parsed HTTP headers.
    /// * `body` - The request body as a string.
    ///
    /// # Example
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let headers = HashMap::new();
    /// let req = Request::new("GET /hello?developer=alfaarghy HTTP/1.1", headers, "".to_string());
    /// assert_eq!(req.method, "GET");
    /// assert_eq!(req.path, "/hello");
    /// assert_eq!(req.query("developer"), Some(&"alfaarghy".to_string()));
    /// ```
    pub fn new(request_line: &str, headers: HashMap<String, String>, body: String) -> Request {
        let parts: Vec<&str> = request_line.split_whitespace().collect();

        let (method, full_path, version) = match parts.as_slice() {
            [m, p, v] => (m.to_string(), p.to_string(), v.to_string()),
            _ => ("GET".to_string(), "/".to_string(), "HTTP/1.1".to_string()),
        };

        let (path, query) = if let Some((p, q)) = full_path.split_once('?') {
            (p.to_string(), Self::parse_query(q))
        } else {
            (full_path, HashMap::new())
        };

        Request {
            method,
            path,
            headers,
            version,
            query,
            params: HashMap::new(),
            body,
        }
    }

    /// Gets a header value by key (case-insensitive).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/test", |req, res| {
    ///     if let Some(token) = req.header("Authorization") {
    ///         res.send(&format!("Token: {}", token));
    ///     } else {
    ///         res.status(400).send("Missing Authorization header");
    ///     }
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let mut headers = HashMap::new();
    /// headers.insert("Content-Type".into(), "application/json".into());
    /// let req = Request::new("GET / HTTP/1.1", headers, "".into());
    ///
    /// assert_eq!(req.header("content-type"), Some(&"application/json".to_string()));
    /// assert_eq!(req.header("non-existent"), None);
    /// ```
    pub fn header(&self, key: &str) -> Option<&String> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(key))
            .map(|(_, v)| v)
    }

    /// Gets a header value or returns a default if not present.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/test", |req, res| {
    ///     let content_type = req.header_or("Content-Type", "text/plain");
    ///     res.send(&format!("Content-Type: {}", content_type));
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let req = Request::new("GET / HTTP/1.1", HashMap::new(), "".into());
    /// assert_eq!(req.header_or("Content-Type", "text/plain"), "text/plain");
    /// ```
    pub fn header_or<'a>(&'a self, key: &str, default: &'a str) -> &'a str {
        self.headers
            .get(key)
            .map(|val| val.as_str())
            .unwrap_or(default)
    }

    /// Gets a header value or returns an error message if missing.
    ///
    /// # Example
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/test", |req, res| {
    ///     match req.header_expect("Authorization") {
    ///         Ok(token) => res.send(token),
    ///         Err(err) => res.status(400).send(&err),
    ///     }
    /// });
    /// ```
    /// ---
    /// ## Test
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let mut headers = HashMap::new();
    /// headers.insert("Authorization".into(), "Bearer abc123".into());
    /// let req = Request::new("GET / HTTP/1.1", headers, "".into());
    ///
    /// assert_eq!(req.header_expect("Authorization").unwrap(), "Bearer abc123");
    /// assert!(req.header_expect("X-Token").is_err());
    /// ```
    pub fn header_expect(&self, key: &str) -> Result<&str, String> {
        self.headers.get(key).map(|val| val.as_str()).ok_or(format!(
            "[rxpress error]: Required header `{}` is missing. \
            Please include it in your request, e.g., `{}: value`.",
            key, key
        ))
    }

    /// Gets a route parameter value (set by the router).
    ///
    /// # Example
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/users/:id", |req, res| {
    ///     if let Some(id) = req.param("id") {
    ///         res.send(&format!("User ID: {}", id));
    ///     } else {
    ///         res.status(400).send("Missing user ID");
    ///     }
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let mut req = Request::new("GET /users/42 HTTP/1.1", HashMap::new(), "".into());
    /// req.params.insert("id".into(), "42".into());
    ///
    /// assert_eq!(req.param("id"), Some(&"42".to_string()));
    /// ```
    pub fn param(&self, key: &str) -> Option<&String> {
        self.params.get(key)
    }

    /// Gets a route parameter or returns a default if missing.
    ///
    /// # Example
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/users/:id", |req, res| {
    ///     let id = req.param_or("id", "0");
    ///     res.send(&format!("User ID: {}", id));
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let req = Request::new("GET /users/ HTTP/1.1", HashMap::new(), "".into());
    /// assert_eq!(req.param_or("id", "0"), "0");
    /// ```
    pub fn param_or<'a>(&'a self, key: &str, default: &'a str) -> &'a str {
        self.params
            .get(key)
            .map(|val| val.as_str())
            .unwrap_or(default)
    }

    /// Gets a route parameter or returns an error message if missing.
    ///
    /// # Example
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/users/:id", |req, res| {
    ///     match req.param_expect("id") {
    ///         Ok(id) => res.send(&format!("User ID: {}", id)),
    ///         Err(err) => res.status(400).send(&err),
    ///     }
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let mut req = Request::new("GET /users/42 HTTP/1.1", HashMap::new(), "".into());
    /// req.params.insert("id".into(), "42".into());
    /// assert_eq!(req.param_expect("id").unwrap(), "42");
    /// assert!(req.param_expect("username").is_err());
    /// ```
    pub fn param_expect(&self, key: &str) -> Result<&str, String> {
        self.params.get(key).map(|val| val.as_str()).ok_or(format!(
            "[rxpress error]: Required route parameter `{}` is missing. \
            Ensure your route includes it, e.g., `/route/:{}`.",
            key, key
        ))
    }

    /// Gets a query parameter value.
    ///
    /// # Example
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/search", |req, res| {
    ///     if let Some(q) = req.query("q") {
    ///         res.send(&format!("Searching for: {}", q));
    ///     } else {
    ///         res.status(400).send("Missing query parameter `q`");
    ///     }
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let headers = HashMap::new();
    /// let req = Request::new("GET /search?q=rust HTTP/1.1", headers, "".into());
    /// assert_eq!(req.query("q"), Some(&"rust".to_string()));
    /// ```
    pub fn query(&self, key: &str) -> Option<&String> {
        self.query.get(key)
    }

    /// Gets a query parameter or returns a default if missing.
    ///
    /// # Example
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/search", |req, res| {
    ///     let q = req.query_or("q", "none");
    ///     res.send(&format!("Query: {}", q));
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let req = Request::new("GET /search HTTP/1.1", HashMap::new(), "".into());
    /// assert_eq!(req.query_or("q", "none"), "none");
    /// ````
    pub fn query_or<'a>(&'a self, key: &str, default: &'a str) -> &'a str {
        self.query
            .get(key)
            .map(|val| val.as_str())
            .unwrap_or(default)
    }

    /// Gets a query parameter or returns an error message if missing.
    ///
    /// # Example
    /// ```no_run
    /// use rxpress::Server;
    ///
    /// let mut app = Server::new("8080");
    ///
    /// app.get("/search", |req, res| {
    ///     match req.query_expect("q") {
    ///         Ok(val) => res.send(val),
    ///         Err(err) => res.status(400).send(&err),
    ///     }
    /// });
    /// ```
    /// ---
    /// ## Test
    /// ```
    /// use std::collections::HashMap;
    /// use rxpress::Request;
    ///
    /// let req = Request::new("GET /search?q=rust HTTP/1.1", HashMap::new(), "".into());
    /// assert_eq!(req.query_expect("q").unwrap(), "rust");
    /// assert!(req.query_expect("page").is_err());
    /// ```
    pub fn query_expect(&self, key: &str) -> Result<&str, String> {
        self.query.get(key).map(|val| val.as_str()).ok_or(format!(
            "[rxpress error]: Required query parameter `{}` is missing. \
            Please include it in your request, e.g., `/route?{}=value`.",
            key, key
        ))
    }

    /*---- Private Functions ----*/
    /// Parses query parameters into a [`HashMap`].
    fn parse_query(q: &str) -> HashMap<String, String> {
        let mut map: HashMap<String, String> = HashMap::new();

        for pair in q.split('&') {
            if let Some((k, v)) = pair.split_once('=') {
                map.insert(k.to_string(), v.to_string());
            } else {
                map.insert(pair.to_string(), "".to_string());
            }
        }

        map
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn make_req_line(line: &str) -> Request {
        Request::new(line, HashMap::new(), "".into())
    }

    // TEST - header test
    #[test]
    fn test_header_case_insensitive() {
        let mut headers = HashMap::new();
        headers.insert("Content-Type".into(), "application/json".into());
        let req = Request::new("GET / HTTP/1.1", headers, "".into());

        assert_eq!(
            req.header("content-type"),
            Some(&"application/json".to_string())
        );
    }

    #[test]
    fn test_header_or() {
        let mut headers = HashMap::new();
        headers.insert("Content-Type".into(), "application/json".into());

        let req = Request::new("GET / HTTP/1.1", headers, "".into());

        assert_eq!(
            req.header_or("Content-Type", "text/plain"),
            "application/json"
        );
        assert_eq!(req.header_or("Non-Existent", "default"), "default");
    }

    #[test]
    fn test_header_expect() {
        let mut headers = HashMap::new();
        headers.insert("Authorization".into(), "Bearer abc123".into());

        let req = Request::new("GET / HTTP/1.1", headers, "".into());

        // Existing header
        assert_eq!(req.header_expect("Authorization").unwrap(), "Bearer abc123");

        // Missing header
        let err = req.header_expect("X-Token").unwrap_err();
        assert!(err.contains("Required header `X-Token` is missing"));
    }

    //TEST - params test
    #[test]
    fn test_param_insertion_and_lookup() {
        let mut req = make_req_line("GET /users/1 HTTP/1.1");
        req.params.insert("id".into(), "1".into());
        assert_eq!(req.param("id"), Some(&"1".to_string()));
    }

    #[test]
    fn test_param_or() {
        let mut req = Request::new("GET /users/ HTTP/1.1", HashMap::new(), "".into());
        req.params.insert("id".into(), "42".into());

        assert_eq!(req.param_or("id", "0"), "42");
        assert_eq!(req.param_or("username", "guest"), "guest");
    }

    #[test]
    fn test_param_expect() {
        let mut req = Request::new("GET /users/42 HTTP/1.1", HashMap::new(), "".into());
        req.params.insert("id".into(), "42".into());

        // Existing param
        assert_eq!(req.param_expect("id").unwrap(), "42");

        // Missing param
        let err = req.param_expect("username").unwrap_err();
        assert!(err.contains("Required route parameter `username` is missing"));
    }

    //TEST - query test
    #[test]
    fn test_query_lookup() {
        let req = make_req_line("GET /search?q=rust HTTP/1.1");
        assert_eq!(req.query("q"), Some(&"rust".to_string()));
    }

    #[test]
    fn test_query_or() {
        let req = Request::new("GET /search?q=rust HTTP/1.1", HashMap::new(), "".into());

        assert_eq!(req.query_or("q", "none"), "rust");
        assert_eq!(req.query_or("page", "1"), "1");
    }

    #[test]
    fn test_query_expect() {
        let req = Request::new("GET /search?q=rust HTTP/1.1", HashMap::new(), "".into());

        // Existing query
        assert_eq!(req.query_expect("q").unwrap(), "rust");

        // Missing query
        let err = req.query_expect("page").unwrap_err();
        assert!(err.contains("Required query parameter `page` is missing"));
    }

    //TEST - query parser(Private Method)
    #[test]
    fn test_parse_query_function() {
        let parsed = Request::parse_query("a=1&b=2&empty");
        assert_eq!(parsed.get("a"), Some(&"1".to_string()));
        assert_eq!(parsed.get("b"), Some(&"2".to_string()));
        assert_eq!(parsed.get("empty"), Some(&"".to_string()));
    }
}