proxy - 有条件地使用 ProxyConnector 或 HTTPConnector
问题描述
我想使用超级板条箱发出 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`
解决这个问题的生锈方法是什么?
解决方案
在 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)
}
}
}
}
推荐阅读
- colorbar - python2.7-colorbar:如何设置色标刻度字体?
- flow-framework - Neos Flow 项目的正确 .gitignore 文件?
- python - 微调的 Resnet-50 模型仅提供 40% 的准确度。怎么提高?
- python-3.x - 分类数据集的 One-hot 编码:如何处理分类数据中的不同值(数量较少)
- python - 使用 Numpy where 条件出现错误
- c# - 当我的 azure 函数应用程序从 blob 存储下载大文件时出现“磁盘空间不足”错误
- ros - 如何使用 ROS usb_cam 包只发布我想要的内容
- java - 使用 IF 和 ELSE 语句设置 Enable 或 Disable 而不是 True 或 False
- shell - Transpose values from multiple files with awk
- mysql - 我收到一个错误 SQL 语句中没有使用所有参数