Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating an HTTPS connection using HttpsConnectorBuilder does not allow you to obtain the website's URL. #223

Closed
zonglin-hub opened this issue Sep 30, 2023 · 1 comment

Comments

@zonglin-hub
Copy link

What is the difference between creating an HTTPS connection using HttpsConnector::with_native_roots() and HttpsConnectorBuilder?

use anyhow::*;
use hyper::service::{make_service_fn, service_fn};
use hyper::Request;
use hyper::{Body, Client, Server};
use hyper_rustls::HttpsConnector;
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use std::sync::Arc;

pub fn proxy_create(req: &mut Request<Body>) -> Result<()> {
    for key in &[
        "content-length",
        "accept_encoding",
        "content-encoding",
        "transfer-encoding",
    ] {
        req.headers_mut().remove(*key);
    }
    let uri = req.uri();
    let uri_string = match uri.query() {
        Some(query_item) => {
            format!("https://lib.rs{}?{}", uri.path(), query_item)
        }
        None => format!("https://lib.rs{}", uri.path()),
    };
    *req.uri_mut() = uri_string.parse().context("parsing URI Error")?;
    Ok(())
}

pub async fn init() -> Result<()> {
   // use hyper-rustls = "0.22"
    // let https = HttpsConnector::with_native_roots();

    // use hyper-rustls = "0.24.1"
    let https = hyper_rustls::HttpsConnectorBuilder::new()
        .with_native_roots()
        .https_only()
        .enable_http1()
        .build();
    let client = Client::builder().build(https);
    let client = Arc::new(client);
    let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
    let make_svc = make_service_fn(move |_| {
        let client = Arc::clone(&client);
        async move {
            Ok::<_>(service_fn(move |mut req| {
                let client = Arc::clone(&client);
                async move {
                    println!("proxy:{}", req.uri().path());
                    proxy_create(&mut req)?;
                    client.request(req).await.context("proxy request")
                }
            }))
        }
    });

    let _server = Server::bind(&addr)
        .serve(make_svc)
        .await
        .context("run server");

    Ok::<()>(())
}
@zonglin-hub
Copy link
Author

Resolved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant