rust-web-server 17.40.0

An HTTP web framework, reverse proxy, and server for Rust supporting HTTP/1.1, HTTP/2, and HTTP/3. Config-driven proxy mode (rws.config.toml with [[route]] / [[upstream]]) or library crate. No third-party HTTP dependencies.
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! Outbound HTTP/1.1 client.
//!
//! A minimal synchronous HTTP/1.1 + HTTPS client with no third-party HTTP
//! dependency.  TLS is backed by `rustls` (the same crate used by the server's
//! inbound TLS stack).
//!
//! # Plain HTTP (always available)
//!
//! ```rust,no_run
//! use rust_web_server::http_client::Client;
//!
//! let resp = Client::new()
//!     .get("http://httpbin.org/get")
//!     .header("X-Request-Id", "abc123")
//!     .timeout_ms(5_000)
//!     .send()
//!     .unwrap();
//!
//! assert!(resp.is_success());
//! println!("{}", resp.text().unwrap());
//! ```
//!
//! # HTTPS
//!
//! Requires the `http-client` feature (or `http2`/`http3`, which already pull
//! in `rustls`):
//!
//! ```toml
//! [dependencies]
//! rust-web-server = { version = "17", features = ["http-client"] }
//! ```
//!
//! Then use exactly the same API — the scheme in the URL selects the transport.
//!
//! # Async client
//!
//! Gated on the `http2` feature:
//!
//! ```rust,no_run
//! # #[cfg(feature = "http2")]
//! # async fn example() -> Result<(), rust_web_server::http_client::HttpClientError> {
//! use rust_web_server::http_client::AsyncClient;
//!
//! let resp = AsyncClient::new()
//!     .get("https://api.example.com/users")
//!     .header("Authorization", "Bearer tok_…")
//!     .send()
//!     .await?;
//!
//! println!("{}", resp.text()?);
//! # Ok(())
//! # }
//! ```

#[cfg(test)]
mod tests;

use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Duration;

#[cfg(any(feature = "http-client", feature = "http2"))]
use std::sync::Arc;

// ── Error type ────────────────────────────────────────────────────────────────

/// Error returned by the HTTP client.
#[derive(Debug)]
pub struct HttpClientError(pub String);

impl std::fmt::Display for HttpClientError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for HttpClientError {}

// ── URL parser ────────────────────────────────────────────────────────────────

struct ParsedUrl {
    scheme: String,
    host: String,
    port: u16,
    path_and_query: String,
}

impl ParsedUrl {
    fn parse(url: &str) -> Result<Self, HttpClientError> {
        // Expect "scheme://rest"
        let rest = if let Some(r) = url.strip_prefix("https://") {
            ("https", r)
        } else if let Some(r) = url.strip_prefix("http://") {
            ("http", r)
        } else {
            return Err(HttpClientError(format!(
                "unsupported or missing URL scheme in '{url}'"
            )));
        };

        let (scheme, authority_and_path) = rest;
        let default_port: u16 = if scheme == "https" { 443 } else { 80 };

        // Split authority from path at the first '/'
        let (authority, path_and_query) = match authority_and_path.find('/') {
            Some(idx) => {
                let (a, p) = authority_and_path.split_at(idx);
                (a, p.to_string())
            }
            None => (authority_and_path, "/".to_string()),
        };

        // Split host and optional port
        let (host, port) = if let Some(bracket_end) = authority.find(']') {
            // IPv6 literal: [::1]:port
            let host = &authority[..=bracket_end];
            let port_part = &authority[bracket_end + 1..];
            let port = if let Some(p) = port_part.strip_prefix(':') {
                p.parse::<u16>().map_err(|_| {
                    HttpClientError(format!("invalid port in URL '{url}'"))
                })?
            } else {
                default_port
            };
            (host.to_string(), port)
        } else {
            match authority.rfind(':') {
                Some(idx) => {
                    let port_str = &authority[idx + 1..];
                    let port = port_str.parse::<u16>().map_err(|_| {
                        HttpClientError(format!("invalid port in URL '{url}'"))
                    })?;
                    (authority[..idx].to_string(), port)
                }
                None => (authority.to_string(), default_port),
            }
        };

        if host.is_empty() {
            return Err(HttpClientError(format!("missing host in URL '{url}'")));
        }

        Ok(ParsedUrl {
            scheme: scheme.to_string(),
            host,
            port,
            path_and_query,
        })
    }
}

/// Resolve `location` against `base_url`.  If `location` is already absolute
/// it is returned as-is.  A path starting with '/' is resolved against the
/// origin of `base_url`.
fn resolve_url(base_url: &str, location: &str) -> String {
    if location.starts_with("http://") || location.starts_with("https://") {
        return location.to_string();
    }
    // relative — reconstruct origin from base
    if let Ok(base) = ParsedUrl::parse(base_url) {
        let default_port = if base.scheme == "https" { 443 } else { 80 };
        let port_str = if base.port == default_port {
            String::new()
        } else {
            format!(":{}", base.port)
        };
        if location.starts_with('/') {
            return format!("{}://{}{}{}", base.scheme, base.host, port_str, location);
        }
        // relative path — resolve against directory of current path
        let base_path = base.path_and_query;
        let dir = match base_path.rfind('/') {
            Some(i) => &base_path[..=i],
            None => "/",
        };
        return format!(
            "{}://{}{}{}{}",
            base.scheme, base.host, port_str, dir, location
        );
    }
    location.to_string()
}

// ── Response ──────────────────────────────────────────────────────────────────

/// HTTP response from the outbound client.
#[derive(Debug)]
pub struct Response {
    status: u16,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
}

impl Response {
    /// HTTP status code.
    pub fn status(&self) -> u16 {
        self.status
    }

    /// `true` if the status code is in the 200–299 range.
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }

    /// `true` if the status code is 301, 302, 303, 307, or 308.
    pub fn is_redirect(&self) -> bool {
        matches!(self.status, 301 | 302 | 303 | 307 | 308)
    }

    /// Look up a response header by name (case-insensitive).
    pub fn header(&self, name: &str) -> Option<&str> {
        let lower = name.to_lowercase();
        self.headers
            .iter()
            .find(|(k, _)| k.to_lowercase() == lower)
            .map(|(_, v)| v.as_str())
    }

    /// Raw response body bytes.
    pub fn bytes(&self) -> &[u8] {
        &self.body
    }

    /// Decode the body as UTF-8.
    pub fn text(&self) -> Result<String, HttpClientError> {
        String::from_utf8(self.body.clone())
            .map_err(|e| HttpClientError(format!("body is not valid UTF-8: {e}")))
    }

    /// Parse the body as JSON.
    #[cfg(feature = "serde")]
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, HttpClientError> {
        serde_json::from_slice(&self.body)
            .map_err(|e| HttpClientError(format!("JSON parse error: {e}")))
    }
}

// ── Wire-level helpers ────────────────────────────────────────────────────────

/// Build the HTTP/1.1 request bytes.
fn build_request_bytes(
    method: &str,
    path_and_query: &str,
    host: &str,
    headers: &[(String, String)],
    body: &Option<Vec<u8>>,
) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::new();

    // Status line
    let _ = write!(
        out,
        "{method} {path_and_query} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: rust-web-server/{}\r\n",
        env!("CARGO_PKG_VERSION"),
    );

    // Content-Length (before custom headers, so callers can override)
    if let Some(b) = body {
        if !b.is_empty() {
            let _ = write!(out, "Content-Length: {}\r\n", b.len());
        }
    }

    // Custom headers
    for (k, v) in headers {
        let _ = write!(out, "{k}: {v}\r\n");
    }

    out.extend_from_slice(b"\r\n");

    if let Some(b) = body {
        out.extend_from_slice(b);
    }

    out
}

/// Parse an HTTP/1.1 response from any `Read` source.
fn read_response(stream: &mut dyn Read, is_head: bool) -> Result<Response, HttpClientError> {
    let mut buf: Vec<u8> = Vec::with_capacity(8192);
    let mut tmp = [0u8; 4096];

    // Read until we find the end of headers (\r\n\r\n)
    let header_end = loop {
        let n = stream
            .read(&mut tmp)
            .map_err(|e| HttpClientError(format!("read error: {e}")))?;
        if n == 0 {
            if buf.is_empty() {
                return Err(HttpClientError(
                    "server closed connection without sending a response".into(),
                ));
            }
            // EOF before \r\n\r\n — try to parse whatever we got
            break buf.len();
        }
        buf.extend_from_slice(&tmp[..n]);
        if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
            break pos + 4;
        }
    };

    // Split header block
    let header_block = std::str::from_utf8(&buf[..header_end])
        .map_err(|_| HttpClientError("response headers are not valid UTF-8".into()))?;

    let mut lines = header_block.lines();

    // Status line
    let status_line = lines
        .next()
        .ok_or_else(|| HttpClientError("empty response".into()))?;
    let status = parse_status(status_line)?;

    // Headers
    let response_headers: Vec<(String, String)> = lines
        .filter_map(|line| {
            let mut parts = line.splitn(2, ':');
            let name = parts.next()?.trim().to_string();
            let value = parts.next()?.trim().to_string();
            if name.is_empty() {
                None
            } else {
                Some((name, value))
            }
        })
        .collect();

    // Body — already-buffered bytes beyond the header block
    let mut body = buf[header_end..].to_vec();

    if !is_head {
        // Determine body reading strategy from headers
        let transfer_encoding = response_headers
            .iter()
            .find(|(k, _)| k.to_lowercase() == "transfer-encoding")
            .map(|(_, v)| v.to_lowercase());

        let content_length: Option<usize> = response_headers
            .iter()
            .find(|(k, _)| k.to_lowercase() == "content-length")
            .and_then(|(_, v)| v.trim().parse().ok());

        if transfer_encoding
            .as_deref()
            .map(|te| te.contains("chunked"))
            .unwrap_or(false)
        {
            // Read remaining chunked data then decode
            loop {
                let n = stream
                    .read(&mut tmp)
                    .map_err(|e| HttpClientError(format!("read error: {e}")))?;
                if n == 0 {
                    break;
                }
                body.extend_from_slice(&tmp[..n]);
            }
            body = decode_chunked(&body)?;
        } else if let Some(len) = content_length {
            while body.len() < len {
                let n = stream
                    .read(&mut tmp)
                    .map_err(|e| HttpClientError(format!("read error: {e}")))?;
                if n == 0 {
                    break;
                }
                body.extend_from_slice(&tmp[..n]);
            }
            body.truncate(len);
        } else {
            // Read until EOF (Connection: close)
            loop {
                let n = stream
                    .read(&mut tmp)
                    .map_err(|e| HttpClientError(format!("read error: {e}")))?;
                if n == 0 {
                    break;
                }
                body.extend_from_slice(&tmp[..n]);
            }
        }
    } else {
        body.clear();
    }

    Ok(Response {
        status,
        headers: response_headers,
        body,
    })
}

fn parse_status(line: &str) -> Result<u16, HttpClientError> {
    // "HTTP/1.x 200 Reason ..."
    let mut parts = line.splitn(3, ' ');
    let _version = parts
        .next()
        .ok_or_else(|| HttpClientError("malformed status line".into()))?;
    let code_str = parts
        .next()
        .ok_or_else(|| HttpClientError("missing status code".into()))?;
    code_str
        .parse::<u16>()
        .map_err(|_| HttpClientError(format!("invalid status code '{code_str}'")))
}

/// Decode chunked transfer encoding.
fn decode_chunked(data: &[u8]) -> Result<Vec<u8>, HttpClientError> {
    let mut out = Vec::new();
    let mut pos = 0;

    while pos < data.len() {
        // Find end of chunk-size line
        let line_end = data[pos..]
            .windows(2)
            .position(|w| w == b"\r\n")
            .ok_or_else(|| HttpClientError("invalid chunked encoding: missing CRLF".into()))?;
        let size_line = std::str::from_utf8(&data[pos..pos + line_end])
            .map_err(|_| HttpClientError("chunked size is not ASCII".into()))?
            .trim();
        // Strip optional chunk extensions (;ext)
        let size_str = size_line.split(';').next().unwrap_or("").trim();
        let chunk_size = usize::from_str_radix(size_str, 16)
            .map_err(|_| HttpClientError(format!("invalid chunk size '{size_str}'")))?;
        pos += line_end + 2; // skip size line + CRLF

        if chunk_size == 0 {
            break; // last chunk
        }

        let end = pos + chunk_size;
        if end > data.len() {
            return Err(HttpClientError("chunked body truncated".into()));
        }
        out.extend_from_slice(&data[pos..end]);
        pos = end + 2; // skip trailing CRLF after chunk data
    }

    Ok(out)
}

// ── TLS connector (sync) ──────────────────────────────────────────────────────

#[cfg(any(feature = "http-client", feature = "http2"))]
fn tls_connect(
    host: &str,
    tcp: TcpStream,
) -> Result<rustls::StreamOwned<rustls::ClientConnection, TcpStream>, HttpClientError> {
    use rustls::pki_types::ServerName;
    use rustls::ClientConfig;

    let root_store =
        rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    let config = Arc::new(
        ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth(),
    );
    let server_name = ServerName::try_from(host.to_string())
        .map_err(|e| HttpClientError(format!("invalid hostname '{host}': {e}")))?;
    let conn = rustls::ClientConnection::new(config, server_name)
        .map_err(|e| HttpClientError(e.to_string()))?;
    Ok(rustls::StreamOwned::new(conn, tcp))
}

// ── Core send (one hop, no redirect) ─────────────────────────────────────────

fn send_once(
    method: &str,
    parsed: &ParsedUrl,
    headers: &[(String, String)],
    body: &Option<Vec<u8>>,
    timeout_ms: u64,
) -> Result<Response, HttpClientError> {
    let addr = format!("{}:{}", parsed.host, parsed.port);
    let timeout = Duration::from_millis(timeout_ms);

    // Resolve + connect
    let sock_addr = addr
        .parse::<std::net::SocketAddr>()
        .or_else(|_| {
            use std::net::ToSocketAddrs;
            addr.to_socket_addrs()
                .map_err(|e| HttpClientError(format!("DNS lookup for '{addr}' failed: {e}")))?
                .next()
                .ok_or_else(|| HttpClientError(format!("no address for '{addr}'")))
        })
        .map_err(|e: HttpClientError| e)?;

    let tcp = TcpStream::connect_timeout(&sock_addr, timeout)
        .map_err(|e| HttpClientError(format!("connect to '{addr}' failed: {e}")))?;
    tcp.set_read_timeout(Some(timeout))
        .map_err(|e| HttpClientError(e.to_string()))?;
    tcp.set_write_timeout(Some(timeout))
        .map_err(|e| HttpClientError(e.to_string()))?;

    let request_bytes =
        build_request_bytes(method, &parsed.path_and_query, &parsed.host, headers, body);

    let is_head = method.eq_ignore_ascii_case("HEAD");

    // Dispatch on scheme
    #[cfg(any(feature = "http-client", feature = "http2"))]
    if parsed.scheme == "https" {
        let mut tls_stream = tls_connect(&parsed.host, tcp)?;
        tls_stream
            .write_all(&request_bytes)
            .map_err(|e| HttpClientError(format!("write error: {e}")))?;
        return read_response(&mut tls_stream, is_head);
    }

    // Plain HTTP
    let mut stream = tcp;
    stream
        .write_all(&request_bytes)
        .map_err(|e| HttpClientError(format!("write error: {e}")))?;
    read_response(&mut stream, is_head)
}

// ── Client ────────────────────────────────────────────────────────────────────

/// Synchronous HTTP/1.1 client.
///
/// Construct with [`Client::new()`], then call one of the method helpers
/// (`.get()`, `.post()`, …) to get a [`RequestBuilder`], configure it, and
/// call `.send()`.
pub struct Client {
    timeout_ms: u64,
    max_redirects: u8,
}

impl Client {
    /// Create a client with default settings:
    /// - `timeout_ms`: 30 000 (30 seconds)
    /// - `max_redirects`: 10
    pub fn new() -> Self {
        Self {
            timeout_ms: 30_000,
            max_redirects: 10,
        }
    }

    /// Override the per-request timeout (connect + read combined).
    pub fn timeout_ms(mut self, ms: u64) -> Self {
        self.timeout_ms = ms;
        self
    }

    /// Maximum number of redirects to follow (default: 10).
    pub fn max_redirects(mut self, n: u8) -> Self {
        self.max_redirects = n;
        self
    }

    /// Start building a GET request.
    pub fn get(&self, url: &str) -> RequestBuilder<'_> {
        self.request("GET", url)
    }

    /// Start building a POST request.
    pub fn post(&self, url: &str) -> RequestBuilder<'_> {
        self.request("POST", url)
    }

    /// Start building a PUT request.
    pub fn put(&self, url: &str) -> RequestBuilder<'_> {
        self.request("PUT", url)
    }

    /// Start building a PATCH request.
    pub fn patch(&self, url: &str) -> RequestBuilder<'_> {
        self.request("PATCH", url)
    }

    /// Start building a DELETE request.
    pub fn delete(&self, url: &str) -> RequestBuilder<'_> {
        self.request("DELETE", url)
    }

    /// Start building a HEAD request.
    pub fn head(&self, url: &str) -> RequestBuilder<'_> {
        self.request("HEAD", url)
    }

    /// Start building a request with an arbitrary HTTP method.
    pub fn request(&self, method: &str, url: &str) -> RequestBuilder<'_> {
        RequestBuilder {
            client: self,
            method: method.to_uppercase(),
            url: url.to_string(),
            headers: Vec::new(),
            body: None,
            timeout_ms: None,
        }
    }
}

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

// ── RequestBuilder ────────────────────────────────────────────────────────────

/// Builder for a single HTTP request.
pub struct RequestBuilder<'a> {
    client: &'a Client,
    method: String,
    url: String,
    headers: Vec<(String, String)>,
    body: Option<Vec<u8>>,
    timeout_ms: Option<u64>,
}

impl<'a> RequestBuilder<'a> {
    /// Add a request header.
    pub fn header(mut self, name: &str, value: &str) -> Self {
        self.headers.push((name.to_string(), value.to_string()));
        self
    }

    /// Set a raw byte body.
    pub fn body(mut self, bytes: Vec<u8>) -> Self {
        self.body = Some(bytes);
        self
    }

    /// Set a plain-text body (also sets `Content-Type: text/plain`).
    pub fn body_text(mut self, s: &str) -> Self {
        self.headers
            .push(("Content-Type".to_string(), "text/plain".to_string()));
        self.body = Some(s.as_bytes().to_vec());
        self
    }

    /// Set a JSON body (also sets `Content-Type: application/json`).
    pub fn body_json(mut self, s: &str) -> Self {
        self.headers.push((
            "Content-Type".to_string(),
            "application/json".to_string(),
        ));
        self.body = Some(s.as_bytes().to_vec());
        self
    }

    /// Override the timeout for this request.
    pub fn timeout_ms(mut self, ms: u64) -> Self {
        self.timeout_ms = Some(ms);
        self
    }

    /// Send the request and return the response.
    ///
    /// Automatically follows redirects up to the client's `max_redirects`
    /// limit.
    pub fn send(self) -> Result<Response, HttpClientError> {
        let timeout = self.timeout_ms.unwrap_or(self.client.timeout_ms);
        let max_redirects = self.client.max_redirects;

        let mut method = self.method;
        let mut url = self.url;
        let headers = self.headers;
        let mut body = self.body;
        let mut redirects = 0u8;

        loop {
            let parsed = ParsedUrl::parse(&url)?;
            let resp = send_once(&method, &parsed, &headers, &body, timeout)?;

            if resp.is_redirect() && redirects < max_redirects {
                let location = resp
                    .header("location")
                    .ok_or_else(|| HttpClientError("redirect with no Location header".into()))?
                    .to_string();
                url = resolve_url(&url, &location);
                redirects += 1;
                if matches!(resp.status(), 301 | 302 | 303) {
                    method = "GET".to_string();
                    body = None;
                }
                continue;
            }

            return Ok(resp);
        }
    }
}

// ── Async client (`http2` feature) ───────────────────────────────────────────

#[cfg(feature = "http2")]
pub use async_impl::{AsyncClient, AsyncRequestBuilder};

#[cfg(feature = "http2")]
mod async_impl {
    use super::{
        build_request_bytes, decode_chunked, parse_status, resolve_url, HttpClientError,
        ParsedUrl, Response,
    };
    use std::sync::Arc;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    async fn async_tls_connect(
        host: &str,
        stream: tokio::net::TcpStream,
    ) -> Result<tokio_rustls::client::TlsStream<tokio::net::TcpStream>, HttpClientError> {
        use rustls::pki_types::ServerName;
        use rustls::ClientConfig;
        use tokio_rustls::TlsConnector;

        let root_store = rustls::RootCertStore::from_iter(
            webpki_roots::TLS_SERVER_ROOTS.iter().cloned(),
        );
        let config = Arc::new(
            ClientConfig::builder()
                .with_root_certificates(root_store)
                .with_no_client_auth(),
        );
        let connector = TlsConnector::from(config);
        let server_name = ServerName::try_from(host.to_string())
            .map_err(|e| HttpClientError(format!("invalid hostname '{host}': {e}")))?;
        connector
            .connect(server_name, stream)
            .await
            .map_err(|e| HttpClientError(format!("TLS handshake failed: {e}")))
    }

    async fn async_read_response(
        stream: &mut (impl AsyncReadExt + Unpin),
        is_head: bool,
    ) -> Result<Response, HttpClientError> {
        let mut buf: Vec<u8> = Vec::with_capacity(8192);
        let mut tmp = vec![0u8; 4096];

        let header_end = loop {
            let n = stream
                .read(&mut tmp)
                .await
                .map_err(|e| HttpClientError(format!("read error: {e}")))?;
            if n == 0 {
                if buf.is_empty() {
                    return Err(HttpClientError(
                        "server closed connection without a response".into(),
                    ));
                }
                break buf.len();
            }
            buf.extend_from_slice(&tmp[..n]);
            if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
                break pos + 4;
            }
        };

        let header_block = std::str::from_utf8(&buf[..header_end])
            .map_err(|_| HttpClientError("response headers not UTF-8".into()))?;

        let mut lines = header_block.lines();
        let status_line = lines
            .next()
            .ok_or_else(|| HttpClientError("empty response".into()))?;
        let status = parse_status(status_line)?;

        let response_headers: Vec<(String, String)> = lines
            .filter_map(|line| {
                let mut parts = line.splitn(2, ':');
                let name = parts.next()?.trim().to_string();
                let value = parts.next()?.trim().to_string();
                if name.is_empty() { None } else { Some((name, value)) }
            })
            .collect();

        let mut body = buf[header_end..].to_vec();

        if !is_head {
            let transfer_encoding = response_headers
                .iter()
                .find(|(k, _)| k.to_lowercase() == "transfer-encoding")
                .map(|(_, v)| v.to_lowercase());

            let content_length: Option<usize> = response_headers
                .iter()
                .find(|(k, _)| k.to_lowercase() == "content-length")
                .and_then(|(_, v)| v.trim().parse().ok());

            if transfer_encoding
                .as_deref()
                .map(|te| te.contains("chunked"))
                .unwrap_or(false)
            {
                loop {
                    let n = stream.read(&mut tmp).await
                        .map_err(|e| HttpClientError(format!("read error: {e}")))?;
                    if n == 0 { break; }
                    body.extend_from_slice(&tmp[..n]);
                }
                body = decode_chunked(&body)?;
            } else if let Some(len) = content_length {
                while body.len() < len {
                    let n = stream.read(&mut tmp).await
                        .map_err(|e| HttpClientError(format!("read error: {e}")))?;
                    if n == 0 { break; }
                    body.extend_from_slice(&tmp[..n]);
                }
                body.truncate(len);
            } else {
                loop {
                    let n = stream.read(&mut tmp).await
                        .map_err(|e| HttpClientError(format!("read error: {e}")))?;
                    if n == 0 { break; }
                    body.extend_from_slice(&tmp[..n]);
                }
            }
        } else {
            body.clear();
        }

        Ok(Response { status, headers: response_headers, body })
    }

    async fn async_send_once(
        method: &str,
        parsed: &ParsedUrl,
        headers: &[(String, String)],
        body: &Option<Vec<u8>>,
        timeout_ms: u64,
    ) -> Result<Response, HttpClientError> {
        use std::time::Duration;
        use tokio::net::TcpStream;
        use tokio::time::timeout;

        let addr = format!("{}:{}", parsed.host, parsed.port);
        let dur = Duration::from_millis(timeout_ms);
        let request_bytes =
            build_request_bytes(method, &parsed.path_and_query, &parsed.host, headers, body);
        let is_head = method.eq_ignore_ascii_case("HEAD");

        let tcp = timeout(dur, TcpStream::connect(&addr))
            .await
            .map_err(|_| HttpClientError(format!("connect to '{addr}' timed out")))?
            .map_err(|e| HttpClientError(format!("connect to '{addr}' failed: {e}")))?;

        if parsed.scheme == "https" {
            let tls_stream = timeout(dur, async_tls_connect(&parsed.host, tcp))
                .await
                .map_err(|_| HttpClientError("TLS handshake timed out".into()))??;
            let mut stream = tls_stream;
            timeout(dur, stream.write_all(&request_bytes))
                .await
                .map_err(|_| HttpClientError("write timed out".into()))?
                .map_err(|e| HttpClientError(format!("write error: {e}")))?;
            return timeout(dur, async_read_response(&mut stream, is_head))
                .await
                .map_err(|_| HttpClientError("read timed out".into()))?;
        }

        let mut stream = tcp;
        timeout(dur, stream.write_all(&request_bytes))
            .await
            .map_err(|_| HttpClientError("write timed out".into()))?
            .map_err(|e| HttpClientError(format!("write error: {e}")))?;
        timeout(dur, async_read_response(&mut stream, is_head))
            .await
            .map_err(|_| HttpClientError("read timed out".into()))?
    }

    /// Asynchronous HTTP/1.1 client (`http2` feature required).
    pub struct AsyncClient {
        timeout_ms: u64,
        max_redirects: u8,
    }

    impl AsyncClient {
        /// Create with default settings (30 s timeout, 10 redirects).
        pub fn new() -> Self {
            Self {
                timeout_ms: 30_000,
                max_redirects: 10,
            }
        }

        /// Override the per-request timeout.
        pub fn timeout_ms(mut self, ms: u64) -> Self {
            self.timeout_ms = ms;
            self
        }

        /// Maximum redirects to follow.
        pub fn max_redirects(mut self, n: u8) -> Self {
            self.max_redirects = n;
            self
        }

        /// Start a GET request.
        pub fn get(&self, url: &str) -> AsyncRequestBuilder<'_> {
            self.request("GET", url)
        }

        /// Start a POST request.
        pub fn post(&self, url: &str) -> AsyncRequestBuilder<'_> {
            self.request("POST", url)
        }

        /// Start a PUT request.
        pub fn put(&self, url: &str) -> AsyncRequestBuilder<'_> {
            self.request("PUT", url)
        }

        /// Start a PATCH request.
        pub fn patch(&self, url: &str) -> AsyncRequestBuilder<'_> {
            self.request("PATCH", url)
        }

        /// Start a DELETE request.
        pub fn delete(&self, url: &str) -> AsyncRequestBuilder<'_> {
            self.request("DELETE", url)
        }

        /// Start a request with an arbitrary method.
        pub fn request(&self, method: &str, url: &str) -> AsyncRequestBuilder<'_> {
            AsyncRequestBuilder {
                client: self,
                method: method.to_uppercase(),
                url: url.to_string(),
                headers: Vec::new(),
                body: None,
                timeout_ms: None,
            }
        }
    }

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

    /// Builder for an async HTTP request.
    pub struct AsyncRequestBuilder<'a> {
        client: &'a AsyncClient,
        method: String,
        url: String,
        headers: Vec<(String, String)>,
        body: Option<Vec<u8>>,
        timeout_ms: Option<u64>,
    }

    impl<'a> AsyncRequestBuilder<'a> {
        /// Add a request header.
        pub fn header(mut self, name: &str, value: &str) -> Self {
            self.headers.push((name.to_string(), value.to_string()));
            self
        }

        /// Set a raw byte body.
        pub fn body(mut self, bytes: Vec<u8>) -> Self {
            self.body = Some(bytes);
            self
        }

        /// Set a plain-text body (sets `Content-Type: text/plain`).
        pub fn body_text(mut self, s: &str) -> Self {
            self.headers
                .push(("Content-Type".to_string(), "text/plain".to_string()));
            self.body = Some(s.as_bytes().to_vec());
            self
        }

        /// Set a JSON body (sets `Content-Type: application/json`).
        pub fn body_json(mut self, s: &str) -> Self {
            self.headers.push((
                "Content-Type".to_string(),
                "application/json".to_string(),
            ));
            self.body = Some(s.as_bytes().to_vec());
            self
        }

        /// Override the timeout for this request.
        pub fn timeout_ms(mut self, ms: u64) -> Self {
            self.timeout_ms = Some(ms);
            self
        }

        /// Send the request asynchronously.
        pub async fn send(self) -> Result<Response, HttpClientError> {
            let timeout = self.timeout_ms.unwrap_or(self.client.timeout_ms);
            let max_redirects = self.client.max_redirects;

            let mut method = self.method;
            let mut url = self.url;
            let headers = self.headers;
            let mut body = self.body;
            let mut redirects = 0u8;

            loop {
                let parsed = ParsedUrl::parse(&url)?;
                let resp = async_send_once(&method, &parsed, &headers, &body, timeout).await?;

                if resp.is_redirect() && redirects < max_redirects {
                    let location = resp
                        .header("location")
                        .ok_or_else(|| {
                            HttpClientError("redirect with no Location header".into())
                        })?
                        .to_string();
                    url = resolve_url(&url, &location);
                    redirects += 1;
                    if matches!(resp.status(), 301 | 302 | 303) {
                        method = "GET".to_string();
                        body = None;
                    }
                    continue;
                }

                return Ok(resp);
            }
        }
    }
}