browser-engineering/src/main.rs

46 lines
1.2 KiB
Rust

use std::env::args;
use anyhow::anyhow;
use hyper::Body;
use hyper::{Request, Uri};
use tokio::net::TcpStream;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let arguments: Vec<String> = args().collect();
let url_text = arguments.get(1).ok_or_else(|| anyhow!("Url required"))?;
let url = url_text.parse::<Uri>()?;
let host = url.host().unwrap();
let port = url.port_u16().unwrap_or(80);
let address = format!("{}:{}", host, port);
let stream = TcpStream::connect(address).await?;
let (mut sender, conn) = hyper::client::conn::handshake(stream).await?;
tokio::task::spawn(async move {
if let Err(err) = conn.await {
eprintln!("connection failed: {}", err);
}
});
let authority = url.authority().unwrap().clone();
let req = Request::builder()
.uri(url)
.header(hyper::header::HOST, authority.as_str())
.body(Body::from(""))?;
let res = sender.send_request(req).await?;
let body = res.into_body();
let body_bytes = hyper::body::to_bytes(body).await?;
let body_text = String::from_utf8(body_bytes.to_vec())?;
println!("{}", body_text);
Ok(())
}