This removes the `tcp` feature from hyper's `Cargo.toml`, and the code it enabled: - `HttpConnector` - `GaiResolver` - `AddrStream` And parts of `Client` and `Server` that used those types. Alternatives will be available in the `hyper-util` crate. Closes #2856 Co-authored-by: MrGunflame <mrgunflame@protonmail.com>
58 lines
1.5 KiB
Rust
58 lines
1.5 KiB
Rust
#![deny(warnings)]
|
|
#![warn(rust_2018_idioms)]
|
|
|
|
use hyper::Body;
|
|
use hyper::{body::Buf, Request};
|
|
use serde::Deserialize;
|
|
use tokio::net::TcpStream;
|
|
|
|
// A simple type alias so as to DRY.
|
|
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<()> {
|
|
let url = "http://jsonplaceholder.typicode.com/users".parse().unwrap();
|
|
let users = fetch_json(url).await?;
|
|
// print users
|
|
println!("users: {:#?}", users);
|
|
|
|
// print the sum of ids
|
|
let sum = users.iter().fold(0, |acc, user| acc + user.id);
|
|
println!("sum of ids: {}", sum);
|
|
Ok(())
|
|
}
|
|
|
|
async fn fetch_json(url: hyper::Uri) -> Result<Vec<User>> {
|
|
let host = url.host().expect("uri has no host");
|
|
let port = url.port_u16().unwrap_or(80);
|
|
let addr = format!("{}:{}", host, port);
|
|
|
|
let stream = TcpStream::connect(addr).await?;
|
|
|
|
let (mut sender, conn) = hyper::client::conn::handshake(stream).await?;
|
|
tokio::task::spawn(async move {
|
|
if let Err(err) = conn.await {
|
|
println!("Connection failed: {:?}", err);
|
|
}
|
|
});
|
|
|
|
// Fetch the url...
|
|
let req = Request::builder().uri(url).body(Body::empty()).unwrap();
|
|
let res = sender.send_request(req).await?;
|
|
|
|
// asynchronously aggregate the chunks of the body
|
|
let body = hyper::body::aggregate(res).await?;
|
|
|
|
// try to parse as json with serde_json
|
|
let users = serde_json::from_reader(body.reader())?;
|
|
|
|
Ok(users)
|
|
}
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
struct User {
|
|
id: i32,
|
|
#[allow(unused)]
|
|
name: String,
|
|
}
|