Skip to main content

io_http/client/
connect.rs

1//! End-to-end connect for the std client, the half that needs a TLS
2//! provider.
3//!
4//! The module is gated once where it is declared, so nothing inside
5//! repeats the feature list.
6
7use alloc::{boxed::Box, string::ToString};
8
9use pimalaya_stream::{std::stream::StreamStd, tls::Tls};
10use url::Url;
11
12use crate::client::{HttpClientError, HttpClientStd};
13
14impl HttpClientStd {
15    /// Connects to `url` (TLS handshake on `https`), reading ALPN from
16    /// `tls.rustls.alpn` (see [`Self::default_alpn`]).
17    pub fn connect(url: &Url, tls: &Tls) -> Result<Self, HttpClientError> {
18        let host = url
19            .host_str()
20            .ok_or_else(|| HttpClientError::UrlMissingHost(url.to_string()))?;
21
22        let stream = match url.scheme() {
23            "http" => StreamStd::connect_tcp(host, url.port_or_known_default().unwrap_or(80))?,
24            "https" => {
25                StreamStd::connect_tls(host, url.port_or_known_default().unwrap_or(443), tls)?
26            }
27            scheme => {
28                return Err(HttpClientError::UrlUnsupportedScheme(
29                    url.to_string(),
30                    scheme.to_string(),
31                ));
32            }
33        };
34
35        Ok(Self {
36            stream: Box::new(stream),
37        })
38    }
39}