Skip to content

Commit 2214294

Browse files
messenseseanmonstar
authored andcommitted
docs(examples): Update client_json example to use async await
1 parent 2eee793 commit 2214294

File tree

2 files changed

+26
-64
lines changed

2 files changed

+26
-64
lines changed

Cargo.toml

+3-3
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ spmc = "0.2"
5555
url = "1.0"
5656
#tokio-fs = "0.1"
5757
#tokio-mockstream = "1.1.0"
58-
#serde = "1.0"
59-
#serde_derive = "1.0"
60-
#serde_json = "1.0"
58+
serde = "1.0"
59+
serde_derive = "1.0"
60+
serde_json = "1.0"
6161

6262
[features]
6363
default = [

examples/client_json.rs

+23-61
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![feature(async_await)]
12
#![deny(warnings)]
23
extern crate hyper;
34
#[macro_use]
@@ -6,78 +7,39 @@ extern crate serde;
67
extern crate serde_json;
78

89
use hyper::Client;
9-
use hyper::rt::{self, Future, Stream};
10+
use futures_util::TryStreamExt;
1011

11-
fn main() {
12-
let url = "http://jsonplaceholder.typicode.com/users".parse().unwrap();
13-
14-
let fut = fetch_json(url)
15-
// use the parsed vector
16-
.map(|users| {
17-
// print users
18-
println!("users: {:#?}", users);
19-
20-
// print the sum of ids
21-
let sum = users.iter().fold(0, |acc, user| acc + user.id);
22-
println!("sum of ids: {}", sum);
23-
})
24-
// if there was an error print it
25-
.map_err(|e| {
26-
match e {
27-
FetchError::Http(e) => eprintln!("http error: {}", e),
28-
FetchError::Json(e) => eprintln!("json parsing error: {}", e),
29-
}
30-
});
12+
// A simple type alias so as to DRY.
13+
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
3114

32-
// Run the runtime with the future trying to fetch, parse and print json.
33-
//
34-
// Note that in more complicated use cases, the runtime should probably
35-
// run on its own, and futures should just be spawned into it.
36-
rt::run(fut);
15+
#[hyper::rt::main]
16+
async fn main() -> Result<()> {
17+
let url = "http://jsonplaceholder.typicode.com/users".parse().unwrap();
18+
let users = fetch_json(url).await?;
19+
// print users
20+
println!("users: {:#?}", users);
21+
22+
// print the sum of ids
23+
let sum = users.iter().fold(0, |acc, user| acc + user.id);
24+
println!("sum of ids: {}", sum);
25+
Ok(())
3726
}
3827

39-
fn fetch_json(url: hyper::Uri) -> impl Future<Item=Vec<User>, Error=FetchError> {
28+
async fn fetch_json(url: hyper::Uri) -> Result<Vec<User>> {
4029
let client = Client::new();
4130

42-
client
43-
// Fetch the url...
44-
.get(url)
45-
// And then, if we get a response back...
46-
.and_then(|res| {
47-
// asynchronously concatenate chunks of the body
48-
res.into_body().concat2()
49-
})
50-
.from_err::<FetchError>()
51-
// use the body after concatenation
52-
.and_then(|body| {
53-
// try to parse as json with serde_json
54-
let users = serde_json::from_slice(&body)?;
31+
// Fetch the url...
32+
let res = client.get(url).await?;
33+
// asynchronously concatenate chunks of the body
34+
let body = res.into_body().try_concat().await?;
35+
// try to parse as json with serde_json
36+
let users = serde_json::from_slice(&body)?;
5537

56-
Ok(users)
57-
})
58-
.from_err()
38+
Ok(users)
5939
}
6040

6141
#[derive(Deserialize, Debug)]
6242
struct User {
6343
id: i32,
6444
name: String,
6545
}
66-
67-
// Define a type so we can return multiple types of errors
68-
enum FetchError {
69-
Http(hyper::Error),
70-
Json(serde_json::Error),
71-
}
72-
73-
impl From<hyper::Error> for FetchError {
74-
fn from(err: hyper::Error) -> FetchError {
75-
FetchError::Http(err)
76-
}
77-
}
78-
79-
impl From<serde_json::Error> for FetchError {
80-
fn from(err: serde_json::Error) -> FetchError {
81-
FetchError::Json(err)
82-
}
83-
}

0 commit comments

Comments
 (0)