use core::fmt::Write as _;
use std::net::SocketAddr;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;
#[derive(Debug)]
pub struct Host {
pub address: SocketAddr,
serving: JoinHandle<()>,
}
impl Host {
pub async fn serving(content_type: &'static str, body: Vec<u8>) -> Self {
Self::answering("200 OK", content_type, body).await
}
pub async fn answering(
status: &'static str,
content_type: &'static str,
body: Vec<u8>,
) -> Self {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("a loopback port");
let address = listener.local_addr().expect("the bound address");
let serving = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let body = body.clone();
tokio::spawn(async move { respond(stream, status, content_type, body).await });
}
});
Self { address, serving }
}
#[must_use]
pub fn url(&self) -> String {
format!("http://{}/snapshot.jpg", self.address)
}
}
impl Drop for Host {
fn drop(&mut self) {
self.serving.abort();
}
}
pub async fn image_host(body: Vec<u8>) -> Host {
Host::serving("image/jpeg", body).await
}
async fn respond(
mut stream: TcpStream,
status: &'static str,
content_type: &'static str,
body: Vec<u8>,
) {
let mut request = Vec::new();
let mut buffer = [0_u8; 1024];
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
match stream.read(&mut buffer).await {
Ok(0) | Err(_) => return,
Ok(read) => request.extend_from_slice(&buffer[..read]),
}
}
let mut head = format!("HTTP/1.1 {status}\r\n");
let _ = write!(head, "Content-Type: {content_type}\r\n");
let _ = write!(head, "Content-Length: {}\r\n", body.len());
head.push_str("Connection: close\r\n\r\n");
if stream.write_all(head.as_bytes()).await.is_err() {
return;
}
if stream.write_all(&body).await.is_err() {
return;
}
let _ = stream.shutdown().await;
}