proxy - 有条件地使用ProxyConnector或HTTPConnector

标签 proxy rust hyper

我想使用 super 包装箱发出HTTP请求。如果用户提供了代理服务器设置,则该请求必须通过代理服务器,否则将在没有代理服务器的情况下发送请求。

这是我的方法:-


use hyper::Client;
use hyper::client::HttpConnector;
use hyper_proxy::Intercept;
use hyper_proxy::Proxy;
use hyper_proxy::ProxyConnector;

fn main(){
    let proxy_url_opt:Option<String> = Some(String::from("http://ip-address:port"))

    let client = match proxy_url_opt { // Line 68
        Some(proxy_url)=>{
            let uri_str = &proxy_url;
            let proxy_uri = uri_str.parse().unwrap();
            let mut proxy = Proxy::new(Intercept::All, proxy_uri);

            let connector = HttpConnector::new();
            let proxy_connector = ProxyConnector::from_proxy(connector, proxy).unwrap();

            let client = Client::builder().build(proxy_connector);

            client // Line 80
        }
        None=>{
            Client::new() // Line 83
        }
    };   

    // while condition {

      let response = client.request(request).await?; 

    // }
}


但是这段代码给了我错误。
match arms have incompatible types

expected struct `hyper_proxy::ProxyConnector`, found struct `hyper::client::connect::http::HttpConnector`

note: expected type `hyper::client::Client<hyper_proxy::ProxyConnector<hyper::client::connect::http::HttpConnector>, _>`
       found struct `hyper::client::Client<hyper::client::connect::http::HttpConnector, hyper::body::body::Body>`rustc(E0308)
main.rs(68, 18): `match` arms have incompatible types
main.rs(80, 13): this is found to be of type `hyper::client::Client<hyper_proxy::ProxyConnector<hyper::client::connect::http::HttpConnector>, _>`
main.rs(83, 13): expected struct `hyper_proxy::ProxyConnector`, found struct `hyper::client::connect::http::HttpConnector`


解决此问题的防 rust 方法是什么?

最佳答案

在yorodm的支持下,我已经使用枚举解决了它。这是我解决的方法:-

enum Client {
    Proxy(HyperClient<ProxyConnector<HttpConnector>>),
    Http(HyperClient<HttpConnector>)
}

impl Client {
    pub fn request(&self, mut req: Request<Body>) -> ResponseFuture{
        match self {
            Client::Proxy(client)=>{
                client.request(req)
            }
            Client::Http(client)=>{
                client.request(req)
            }
        }
    }
}

关于proxy - 有条件地使用ProxyConnector或HTTPConnector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60551350/

相关文章:

http-headers - 如何在 Hyper 中正确处理多个 Set-Cookie header ?

ios - 使用Jmeter代理记录来自iOS模拟器的HTTP调用

apache - 构建位于反向代理后面的应用程序时处理URI的策略

apache-flex - 使用代理克服跨域限制

ubuntu - 如何在 Ubuntu 虚拟机上的 Minikube 中使用代理?

websocket - tokio_tungstenite::WebSocketStream 的 split() 方法在哪里实现?

iterator - 共享借用的 Vec 上 iter() 和 into_iter() 的区别?

rust - 使用 Hyper 为 GET 请求传递数据

collections - Rust - 如何将数据添加到三重嵌套 HashMap

rust - 如何使用 hyper 下载大文件并在出错时恢复?