How to set timeout for HTTP request with hyper, tokio and futures in Rust? -


how set timeout http request using asynchronous hyper (>= 0.11)?

here example of code without timeout:

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)     } } 

answering own question working code example, based on link provided 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)     } } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -