Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 20, 2018 17:02
Show Gist options
  • Save rust-play/48da41959be3a1c95ce85d7b535ed676 to your computer and use it in GitHub Desktop.
Save rust-play/48da41959be3a1c95ce85d7b535ed676 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
extern crate futures;
extern crate hyper;
extern crate tokio;
extern crate tokio_threadpool; // 0.1.4
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use futures::sync::oneshot;
use hyper::Client;
use hyper::rt::{self, Future, Stream};
use tokio_threadpool::*;
#[derive(Deserialize, Debug)]
struct User {
id: i32,
name: String,
}
// Define a type so we can return multile types of errors
enum FetchError {
Http(hyper::Error),
Json(serde_json::Error),
}
impl From<hyper::Error> for FetchError {
fn from(err: hyper::Error) -> FetchError {
FetchError::Http(err)
}
}
impl From<serde_json::Error> for FetchError {
fn from(err: serde_json::Error) -> FetchError {
FetchError::Json(err)
}
}
fn fetch_json(url: hyper::Uri) -> impl Future<Item=Vec<User>, Error=FetchError> {
let client = Client::new();
client
// Fetch the url...
.get(url)
// And then, if we get a response back...
.and_then(|res| {
// asynchronously concatenate chunks of the body
res.into_body().concat2()
})
.from_err::<FetchError>()
// use the body after concatenation
.and_then(|body| {
// try to parse as json with serde_json
let users = serde_json::from_slice(&body)?;
Ok(users)
})
.from_err()
}
fn main(){
let url = "https://provision.threatx.io/tx_api/v1/login".parse().unwrap();
let pool = ThreadPool::new();
let tx = pool.sender().clone();
let fut = fetch_json(url)
// if there was an error print it
.map_err(|e| {
match e {
FetchError::Http(e) => eprintln!("http error: {}", e),
FetchError::Json(e) => eprintln!("json parsing error: {}", e),
}
});
let result = oneshot::spawn(fut, &tx);
let myresult = result.wait(); // WAIT not receive
println!("{:?}", myresult);
// Run the runtime with the future trying to fetch, parse and print json.
//
// Note that in more complicated use cases, the runtime should probably
// run on its own, and futures should just be spawned into it.
//rt::run(fut);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment