Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 28, 2018 13:51
Show Gist options
  • Save rust-play/6d720f7277937a4b83fc45be4b628fe1 to your computer and use it in GitHub Desktop.
Save rust-play/6d720f7277937a4b83fc45be4b628fe1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![allow(warnings)] // remove when error_chain is fixed
extern crate futures;
extern crate reqwest;
extern crate tokio_core;
#[macro_use]
extern crate error_chain;
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
use std::mem;
use std::io::{self, Cursor};
use futures::{Future, Stream};
use reqwest::unstable::async::{Client, Decoder};
use futures::future::lazy;
use futures::future::{join_all, ok, err};
use futures::AndThen;
use futures::future::FutureResult;
use reqwest::StatusCode;
use reqwest::unstable::async::Response;
use reqwest::unstable::async::Chunk;
error_chain! {
foreign_links {
ReqError(reqwest::Error);
IoError(io::Error);
}
}
#[derive(Deserialize, Debug)]
struct Slideshow {
title: String,
author: String,
}
fn run() -> Result<()> {
let mut core = tokio_core::reactor::Core::new()?;
let client = Client::new(&core.handle());
let map_error = |e| Error::from(e);
let get_body = |mut res : Response | {
println!("{}", res.status());
let body = mem::replace(res.body_mut(), Decoder::empty());
body.concat2().map_err(Into::into)
};
let print_body = |body : Chunk | {
let mut body = Cursor::new(body);
io::copy(&mut body, &mut io::stdout()).map_err(Into::into)
};
let work1 =
client
.get("https://httpbin.org/json")
.send()
.map_err(map_error)
.and_then(get_body)
.and_then(print_body);
let work2 =
client
.get("https://httpbin.org/json")
.send()
.map_err(map_error)
.and_then(get_body)
.and_then(print_body);
let work = join_all(vec![work1, work2]);
for response in core.run(work)?.into_iter() {
println!("{:?}", response);
}
Ok(())
}
quick_main!(run);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment