http-handle 0.0.5

A fast and lightweight Rust library for handling HTTP requests and responses.
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2023 - 2026 HTTP Handle

// src/request.rs

//! HTTP/1.x request parsing and validation.
//!
//! Use this module to convert raw stream input into typed request data with bounded parsing,
//! header normalization, and explicit malformed-request errors.

use crate::error::ServerError;
use std::fmt;
use std::io::{self, BufRead, BufReader};
use std::net::TcpStream;
use std::time::Duration;

/// Maximum length allowed for the request line (8KB).
/// This includes the method, path, version, and the two spaces between them, but not the trailing \r\n.
const MAX_REQUEST_LINE_LENGTH: usize = 8190;

/// Number of parts expected in a valid HTTP request line.
const REQUEST_PARTS: usize = 3;

/// Timeout duration for reading from the TCP stream (in seconds).
const TIMEOUT_SECONDS: u64 = 30;
/// Maximum number of accepted request headers.
const MAX_HEADER_COUNT: usize = 100;
/// Maximum allowed length for a single header line.
const MAX_HEADER_LINE_LENGTH: usize = 8192;
/// Maximum cumulative bytes for all headers.
const MAX_HEADER_BYTES: usize = 64 * 1024;

fn map_timeout_error(error: io::Error) -> ServerError {
    ServerError::invalid_request(format!(
        "Failed to set read timeout: {}",
        error
    ))
}

fn map_read_error(error: io::Error) -> ServerError {
    ServerError::invalid_request(format!(
        "Failed to read request line: {}",
        error
    ))
}

/// Represents a parsed HTTP/1.x request line and headers.
///
/// You receive this type after successful stream parsing. It is the primary request model
/// used by the synchronous server path and shared response-generation helpers.
///
/// # Examples
///
/// ```rust
/// use http_handle::request::Request;
///
/// let request = Request {
///     method: "GET".to_string(),
///     path: "/".to_string(),
///     version: "HTTP/1.1".to_string(),
///     headers: Vec::new(),
/// };
/// assert_eq!(request.method(), "GET");
/// ```
///
/// # Panics
///
/// This type does not panic on construction.
#[doc(alias = "http request")]
#[derive(Debug, Clone, PartialEq)]
pub struct Request {
    /// HTTP method of the request.
    pub method: String,
    /// Requested path.
    pub path: String,
    /// HTTP version of the request.
    pub version: String,
    /// Parsed request headers (header-name lowercased).
    ///
    /// Stored as `Vec<(String, String)>` rather than a `HashMap` —
    /// realistic request payloads carry well under 32 headers, so a
    /// linear scan in `Request::header` outperforms hashing for both
    /// lookup latency and per-request allocator pressure (no hash table
    /// to grow + rehash).
    pub headers: Vec<(String, String)>,
}

impl Request {
    /// Parses a request line and headers from a `TcpStream`.
    ///
    /// This method reads the first line of an HTTP request from the given TCP stream,
    /// parses it, and constructs a `Request` instance if the input is valid.
    ///
    /// # Arguments
    ///
    /// * `stream` - A reference to the `TcpStream` from which the request will be read.
    ///
    /// # Returns
    ///
    /// * `Ok(Request)` - If the request is valid and successfully parsed.
    /// * `Err(ServerError)` - If the request is malformed, cannot be read, or is invalid.
    ///
    /// # Errors
    ///
    /// This function returns a `ServerError::InvalidRequest` error if:
    /// - The request line is too long (exceeds `MAX_REQUEST_LINE_LENGTH`)
    /// - The request line does not contain exactly three parts
    /// - The HTTP method is not recognized
    /// - The request path does not start with a forward slash (except `OPTIONS *`)
    /// - The HTTP version is not supported (only HTTP/1.0 and HTTP/1.1 are accepted)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use std::net::TcpStream;
    /// use http_handle::request::Request;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").expect("connect");
    /// let parsed = Request::from_stream(&stream);
    /// assert!(parsed.is_ok() || parsed.is_err());
    /// ```
    ///
    /// # Panics
    ///
    /// This function does not intentionally panic.
    #[doc(alias = "parse")]
    #[doc(alias = "from tcp")]
    pub fn from_stream(
        stream: &TcpStream,
    ) -> Result<Self, ServerError> {
        stream
            .set_read_timeout(Some(Duration::from_secs(
                TIMEOUT_SECONDS,
            )))
            .map_err(map_timeout_error)?;

        let mut buf_reader = BufReader::new(stream);
        let mut request_line = String::new();

        let _ = buf_reader
            .read_line(&mut request_line)
            .map_err(map_read_error)?;

        // Trim the trailing \r\n before checking the length
        let trimmed_request_line = request_line.trim_end();

        // Check if the request line exceeds the maximum allowed length
        if request_line.len() > MAX_REQUEST_LINE_LENGTH {
            return Err(ServerError::invalid_request(format!(
                "Request line too long: {} characters (max {})",
                request_line.len(),
                MAX_REQUEST_LINE_LENGTH
            )));
        }

        let mut parts = trimmed_request_line.split_whitespace();
        let Some(method_part) = parts.next() else {
            return Err(ServerError::invalid_request(
                "Invalid request line: missing method",
            ));
        };
        let Some(path_part) = parts.next() else {
            return Err(ServerError::invalid_request(
                "Invalid request line: missing path",
            ));
        };
        let Some(version_part) = parts.next() else {
            return Err(ServerError::invalid_request(
                "Invalid request line: missing HTTP version",
            ));
        };
        if parts.next().is_some() {
            return Err(ServerError::invalid_request(format!(
                "Invalid request line: expected {} parts",
                REQUEST_PARTS
            )));
        }

        let method = method_part.to_string();
        if !Self::is_valid_method(&method) {
            return Err(ServerError::invalid_request(format!(
                "Invalid HTTP method: {}",
                method
            )));
        }

        let path = path_part.to_string();
        let is_options_asterisk =
            method.eq_ignore_ascii_case("OPTIONS") && path == "*";
        if !path.starts_with('/') && !is_options_asterisk {
            return Err(ServerError::invalid_request(
                "Invalid path: must start with '/' (or be '*' for OPTIONS)",
            ));
        }

        let version = version_part.to_string();
        if !Self::is_valid_version(&version) {
            return Err(ServerError::invalid_request(format!(
                "Invalid HTTP version: {}",
                version
            )));
        }

        let headers = Self::read_headers(&mut buf_reader)?;

        Ok(Request {
            method,
            path,
            version,
            headers,
        })
    }

    /// Returns the HTTP method of the request.
    ///
    /// # Returns
    ///
    /// A string slice containing the HTTP method (e.g., "GET", "POST").
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Returns the requested path of the request.
    ///
    /// # Returns
    ///
    /// A string slice containing the requested path.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns the HTTP version of the request.
    ///
    /// # Returns
    ///
    /// A string slice containing the HTTP version (e.g., "HTTP/1.1").
    pub fn version(&self) -> &str {
        &self.version
    }

    /// Returns the value of a header by case-insensitive name.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use http_handle::request::Request;
    ///
    /// let request = Request {
    ///     method: "GET".to_string(),
    ///     path: "/".to_string(),
    ///     version: "HTTP/1.1".to_string(),
    ///     headers: vec![(
    ///         "content-type".to_string(),
    ///         "text/plain".to_string(),
    ///     )],
    /// };
    /// assert_eq!(request.header("Content-Type"), Some("text/plain"));
    /// ```
    ///
    /// # Panics
    ///
    /// This function does not panic.
    #[doc(alias = "header lookup")]
    pub fn header(&self, name: &str) -> Option<&str> {
        // Linear scan: header counts in real traffic are O(10), so a
        // case-insensitive equality check beats hashing the lookup key.
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// Returns all parsed headers.
    pub fn headers(&self) -> &[(String, String)] {
        &self.headers
    }

    /// Checks if the given method is a valid HTTP method.
    ///
    /// # Arguments
    ///
    /// * `method` - A string slice containing the HTTP method to validate.
    ///
    /// # Returns
    ///
    /// `true` if the method is valid, `false` otherwise.
    fn is_valid_method(method: &str) -> bool {
        matches!(
            method.to_ascii_uppercase().as_str(),
            "GET"
                | "POST"
                | "PUT"
                | "DELETE"
                | "HEAD"
                | "OPTIONS"
                | "PATCH"
        )
    }

    /// Checks if the given HTTP version is supported.
    ///
    /// # Arguments
    ///
    /// * `version` - A string slice containing the HTTP version to validate.
    ///
    /// # Returns
    ///
    /// `true` if the version is supported, `false` otherwise.
    fn is_valid_version(version: &str) -> bool {
        version.eq_ignore_ascii_case("HTTP/1.0")
            || version.eq_ignore_ascii_case("HTTP/1.1")
    }

    fn read_headers<R: BufRead>(
        reader: &mut R,
    ) -> Result<Vec<(String, String)>, ServerError> {
        let mut headers: Vec<(String, String)> = Vec::with_capacity(16);
        let mut total_bytes = 0_usize;
        // Reuse a single line buffer across iterations to avoid allocating
        // a fresh String per header line.
        let mut line = String::new();

        loop {
            line.clear();
            let bytes =
                reader.read_line(&mut line).map_err(map_read_error)?;
            if bytes == 0 {
                break;
            }
            total_bytes = total_bytes.saturating_add(bytes);
            if total_bytes > MAX_HEADER_BYTES {
                return Err(ServerError::invalid_request(
                    "Header section too large",
                ));
            }

            let trimmed = line.trim_end();
            if trimmed.is_empty() {
                break;
            }
            if trimmed.len() > MAX_HEADER_LINE_LENGTH {
                return Err(ServerError::invalid_request(
                    "Header line too long",
                ));
            }
            // memchr finds the first ':' via SIMD (NEON on Apple
            // Silicon, AVX2 on x86_64). For typical 12–40 byte header
            // lines the win is small; for longer lines (cookies,
            // user-agent) it's measurable.
            let bytes = trimmed.as_bytes();
            let colon =
                memchr::memchr(b':', bytes).ok_or_else(|| {
                    ServerError::invalid_request(
                        "Malformed header line",
                    )
                })?;
            // SAFETY: `colon` is an index returned by memchr inside
            // `bytes`, which is the byte view of the `&str` `trimmed`.
            // ASCII ':' is exactly one UTF-8 byte, so the split lands
            // on a UTF-8 boundary.
            let (name, value) = trimmed.split_at(colon);
            let value = &value[1..];
            if headers.len() >= MAX_HEADER_COUNT {
                return Err(ServerError::invalid_request(
                    "Too many request headers",
                ));
            }
            headers.push((
                name.trim().to_ascii_lowercase(),
                value.trim().to_string(),
            ));
        }

        Ok(headers)
    }
}

impl fmt::Display for Request {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} {}", self.method, self.path, self.version)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use std::net::TcpListener;

    #[test]
    fn test_valid_request() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream.write_all(b"GET /index.html HTTP/1.1\r\n").unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let request = Request::from_stream(&stream).unwrap();

        assert_eq!(request.method(), "GET");
        assert_eq!(request.path(), "/index.html");
        assert_eq!(request.version(), "HTTP/1.1");
        assert!(request.headers().is_empty());
    }

    #[test]
    fn test_invalid_method() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream
                .write_all(b"INVALID /index.html HTTP/1.1\r\n")
                .unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let result = Request::from_stream(&stream);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ServerError::InvalidRequest(_)
        ));
    }

    #[test]
    fn test_max_length_request() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let long_path = "/".repeat(MAX_REQUEST_LINE_LENGTH - 16); // Account for "GET ", " HTTP/1.1", and "\r\n"
            let request = format!("GET {} HTTP/1.1\r\n", long_path);
            stream.write_all(request.as_bytes()).unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let result = Request::from_stream(&stream);

        assert!(result.is_ok());
        assert_eq!(
            result.unwrap().path().len(),
            MAX_REQUEST_LINE_LENGTH - 16
        );
    }

    #[test]
    fn test_oversized_request() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let long_path = "/".repeat(MAX_REQUEST_LINE_LENGTH - 13); // 13 = len("GET  HTTP/1.1")
            let request = format!("GET {} HTTP/1.1\r\n", long_path);
            stream.write_all(request.as_bytes()).unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let result = Request::from_stream(&stream);

        assert!(
            result.is_err(),
            "Oversized request should be invalid. Request: {:?}",
            result
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("Request line too long:"),
            "Unexpected error message: {}",
            msg
        );
    }

    #[test]
    fn test_invalid_path() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream.write_all(b"GET index.html HTTP/1.1\r\n").unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let result = Request::from_stream(&stream);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ServerError::InvalidRequest(_)
        ));
    }

    #[test]
    fn test_invalid_version() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream.write_all(b"GET /index.html HTTP/2.0\r\n").unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let result = Request::from_stream(&stream);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ServerError::InvalidRequest(_)
        ));
    }

    #[test]
    fn test_head_request() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream.write_all(b"HEAD /index.html HTTP/1.1\r\n").unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let request = Request::from_stream(&stream).unwrap();

        assert_eq!(request.method(), "HEAD");
        assert_eq!(request.path(), "/index.html");
        assert_eq!(request.version(), "HTTP/1.1");
    }

    #[test]
    fn test_options_request() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream.write_all(b"OPTIONS * HTTP/1.1\r\n").unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let request = Request::from_stream(&stream).unwrap();

        assert_eq!(request.method(), "OPTIONS");
        assert_eq!(request.path(), "*");
        assert_eq!(request.version(), "HTTP/1.1");
    }

    #[test]
    fn test_internal_error_mapping_helpers() {
        let timeout_err =
            io::Error::new(io::ErrorKind::TimedOut, "timeout");
        let mapped = map_timeout_error(timeout_err);
        assert!(
            mapped.to_string().contains("Failed to set read timeout")
        );

        let read_err =
            io::Error::new(io::ErrorKind::UnexpectedEof, "eof");
        let mapped = map_read_error(read_err);
        assert!(
            mapped.to_string().contains("Failed to read request line")
        );
    }

    #[test]
    fn test_parses_headers() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            stream
                .write_all(
                    b"GET /index.html HTTP/1.1\r\nHost: localhost\r\nRange: bytes=0-1\r\n\r\n",
                )
                .unwrap();
        });

        let stream = TcpStream::connect(addr).unwrap();
        let request = Request::from_stream(&stream).unwrap();
        assert_eq!(request.header("host"), Some("localhost"));
        assert_eq!(request.header("range"), Some("bytes=0-1"));
    }

    fn run_request_bytes(
        bytes: Vec<u8>,
    ) -> Result<Request, ServerError> {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let _ = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let _ = stream.write_all(&bytes);
        });
        let stream = TcpStream::connect(addr).unwrap();
        Request::from_stream(&stream)
    }

    #[test]
    fn test_missing_method_returns_error() {
        let err = run_request_bytes(b"\r\n".to_vec()).unwrap_err();
        assert!(
            err.to_string().contains("missing method"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_too_many_parts_returns_error() {
        let err =
            run_request_bytes(b"GET / HTTP/1.1 extra\r\n".to_vec())
                .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("expected") && msg.contains("parts"),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn test_malformed_header_returns_error() {
        let err = run_request_bytes(
            b"GET / HTTP/1.1\r\nmissing-colon-line\r\n\r\n".to_vec(),
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("Malformed header line"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_header_line_too_long_returns_error() {
        let mut req = Vec::from("GET / HTTP/1.1\r\nX: ");
        req.extend(std::iter::repeat_n(b'A', MAX_HEADER_LINE_LENGTH));
        req.extend_from_slice(b"\r\n\r\n");
        let err = run_request_bytes(req).unwrap_err();
        assert!(
            err.to_string().contains("Header line too long"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_header_section_too_large_returns_error() {
        // Many moderately sized header lines (each under MAX_HEADER_LINE_LENGTH)
        // whose cumulative byte count exceeds MAX_HEADER_BYTES before the
        // per-line or header-count guards trip.
        let mut req = Vec::from("GET / HTTP/1.1\r\n");
        let filler: String = "A".repeat(8000);
        // Ten ~8KiB headers = ~80 KiB > 64 KiB cap.
        for i in 0..10 {
            req.extend_from_slice(
                format!("H{i}: {filler}\r\n").as_bytes(),
            );
        }
        req.extend_from_slice(b"\r\n");
        let err = run_request_bytes(req).unwrap_err();
        assert!(
            err.to_string().contains("Header section too large"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_too_many_headers_returns_error() {
        let mut req = Vec::from("GET / HTTP/1.1\r\n");
        for i in 0..=MAX_HEADER_COUNT {
            req.extend_from_slice(format!("H{i}: v\r\n").as_bytes());
        }
        req.extend_from_slice(b"\r\n");
        let err = run_request_bytes(req).unwrap_err();
        assert!(
            err.to_string().contains("Too many request headers"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_missing_http_version_returns_error() {
        // Two-token request line: method + path, no version.
        // Triggers the third let-else branch (missing HTTP version).
        let err = run_request_bytes(b"GET /\r\n".to_vec()).unwrap_err();
        assert!(
            err.to_string().contains("missing HTTP version"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_request_display_formats_method_path_version() {
        let request = Request {
            method: "GET".to_string(),
            path: "/index.html".to_string(),
            version: "HTTP/1.1".to_string(),
            headers: Vec::new(),
        };
        assert_eq!(format!("{request}"), "GET /index.html HTTP/1.1");
    }
}