我似乎无法弄清楚如何让 Rust 在同一个变量中接受客户端和代理客户端。虽然我还是 Rust 的新手,但我对编程有基本的了解。到目前为止,我已经尝试过结构(但没有 impl)、类型转换、未初始化的变量,但没有任何效果。
extern crate futures;
extern crate hyper;
extern crate hyper_proxy;
extern crate stopwatch;
extern crate tokio_core;
use futures::{Future, Stream};
use hyper::client::HttpConnector;
use hyper::Client;
use hyper_proxy::{Intercept, Proxy, ProxyConnector};
use tokio_core::reactor::Core;
fn main() {
let use_proxy = true;
let proxy_uri: Option<String> = Some("http://localhost:8118".to_owned());
let mut core = Core::new().unwrap();
let handle = core.handle();
let mut proxy = None;
// looking for polymorphic variable that works with both proxyed and unproxyed hyper clients
let mut client: hyper::Client<hyper::client::HttpConnector, hyper::Body>;
if use_proxy && proxy_uri.is_some() {
println!("Using proxy: {}", proxy_uri.unwrap().as_str());
proxy = Some({
let proxy_uri = proxy_uri.unwrap().parse().unwrap();
let mut proxy = Proxy::new(Intercept::All, proxy_uri);
let connector = HttpConnector::new(4, &handle);
let proxy_connector = ProxyConnector::from_proxy(connector, proxy).unwrap();
proxy_connector
});
client = Client::configure()
.connector(proxy.clone().unwrap())
.build(&handle);
} else {
client = Client::configure()
.connector(HttpConnector::new(4, &handle))
.build(&handle);
}
// use hyper client below
}
[dependencies]
futures = "0.1.21"
hyper = "0.11.27"
tokio-core = "0.1.17"
hyper-proxy = "0.4.1"
stopwatch = "0.0.7"
我已经制作了所有文件的 GitHub 存储库。
尝试编译时出现此错误:
error[E0308]: mismatched types
--> src/main.rs:32:18
|
32 | client = Client::configure()
| __________________^
33 | | .connector(proxy.clone().unwrap())
34 | | .build(&handle);
| |___________________________^ expected struct `hyper::client::HttpConnector`, found struct `hyper_proxy::ProxyConnector`
|
= note: expected type `hyper::Client<hyper::client::HttpConnector, _>`
found type `hyper::Client<hyper_proxy::ProxyConnector<hyper::client::HttpConnector>, _>`
如果有更好的方法,我也想知道。