How to store a "generic" hyper::Client in a struct?

Hi :wave:

I'm having some challenges with the following (simplified) example:

use anyhow::{Context, Result};
use hyper::client::connect::Connect;
use hyper_proxy::{Intercept, Proxy, ProxyConnector};
use hyper_tls::HttpsConnector;
use url::Url;

#[derive(Clone, Debug)]
pub struct Client<C> {
    base_url: Url,
    http_client: hyper::Client<C>,
}

impl<C> Client<C>
where
    C: Connect + Clone + Send + Sync + 'static,
{
    pub fn new(endpoint: &str) -> Result<Self> {
        let base_url = Url::parse(endpoint).context("error parsing API endpoint")?;

        if let Ok(http_proxy) = std::env::var("http_proxy") {
            let proxy = Proxy::new(Intercept::All, http_proxy.parse()?);
            let proxy_connector = ProxyConnector::from_proxy(HttpsConnector::new(), proxy)?;
            return Ok(Self {
                base_url,
                http_client: hyper::Client::builder().build::<_, hyper::Body>(proxy_connector),
            });
        };

        let https_connector = HttpsConnector::new();
        Ok(Self {
            base_url,
            http_client: hyper::Client::builder().build::<_, hyper::Body>(https_connector),
        })
    }
}

My goal is to be able to return a new Client that contains either a hyper::Client<ProxyConnector<HttpsConnector<HttpConnector>>> or hyper::Client<HttpsConnector<HttpConnector>> as its http_client. The example clearly uses a wrong approach, but I think I need some help to get me on the right track for how to achieve this.

Sound like you want an enum with two variants, one for each type of Client

Was hoping for something more "generic" :wink: but guess this could indeed be a straight forward solution. Will have a look at it, thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.