gpt4 book ai didi

http - 如何在 Rust 中使用 hyper、tokio 和 futures 为 HTTP 请求设置超时?

转载 作者:可可西里 更新时间:2023-11-01 15:27:00 24 4
gpt4 key购买 nike

如何使用异步 Hyper (>= 0.11) 为 HTTP 请求设置超时?

下面是没有超时的代码示例:

extern crate hyper;
extern crate tokio_core;
extern crate futures;

use futures::Future;
use hyper::Client;
use tokio_core::reactor::Core;

fn main() {
let mut core = Core::new().unwrap();
let client = Client::new(&core.handle());

let uri = "http://stackoverflow.com".parse().unwrap();
let work = client.get(uri).map(|res| {
res.status()
});

match core.run(work) {
Ok(status) => println!("Status: {}", status),
Err(e) => println!("Error: {:?}", e)
}
}

最佳答案

根据 seanmonstar 提供的指向 Hyper Guide / General Timeout 的链接,用工作代码示例回答我自己的问题:

extern crate hyper;
extern crate tokio_core;
extern crate futures;

use futures::Future;
use futures::future::Either;
use hyper::Client;
use tokio_core::reactor::Core;
use std::time::Duration;
use std::io;

fn main() {
let mut core = Core::new().unwrap();
let handle = core.handle();
let client = Client::new(&handle);

let uri: hyper::Uri = "http://stackoverflow.com".parse().unwrap();
let request = client.get(uri.clone()).map(|res| res.status());

let timeout = tokio_core::reactor::Timeout::new(Duration::from_millis(170), &handle).unwrap();

let work = request.select2(timeout).then(|res| match res {
Ok(Either::A((got, _timeout))) => Ok(got),
Ok(Either::B((_timeout_error, _get))) => {
Err(hyper::Error::Io(io::Error::new(
io::ErrorKind::TimedOut,
"Client timed out while connecting",
)))
}
Err(Either::A((get_error, _timeout))) => Err(get_error),
Err(Either::B((timeout_error, _get))) => Err(From::from(timeout_error)),
});

match core.run(work) {
Ok(status) => println!("OK: {:?}", status),
Err(e) => println!("Error: {:?}", e)
}
}

关于http - 如何在 Rust 中使用 hyper、tokio 和 futures 为 HTTP 请求设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45313119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com