#![deny(warnings)]
use std::net::SocketAddr;
use bytes::Bytes;
use futures_util::TryStreamExt;
use http_body_util::{combinators::BoxBody, BodyExt, Full, StreamBody};
use hyper::body::Frame;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, Result, StatusCode};
use tokio::{fs::File, net::TcpListener};
use tokio_util::io::ReaderStream;
#[path = "../benches/support/mod.rs"]
mod support;
use support::TokioIo;
static INDEX: &str = "examples/send_file_index.html";
static NOTFOUND: &[u8] = b"Not Found";
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
pretty_env_logger::init();
let addr: SocketAddr = "127.0.0.1:1337".parse().unwrap();
let listener = TcpListener::bind(addr).await?;
println!("Listening on http://{}", addr);
loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
tokio::task::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(io, service_fn(response_examples))
.await
{
println!("Failed to serve connection: {:?}", err);
}
});
}
}
async fn response_examples(
req: Request<hyper::body::Incoming>,
) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => simple_file_send(INDEX).await,
(&Method::GET, "/no_file.html") => {
simple_file_send("this_file_should_not_exist.html").await
}
_ => Ok(not_found()),
}
}
fn not_found() -> Response<BoxBody<Bytes, std::io::Error>> {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Full::new(NOTFOUND.into()).map_err(|e| match e {}).boxed())
.unwrap()
}
async fn simple_file_send(filename: &str) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
let file = File::open(filename).await;
if file.is_err() {
eprintln!("ERROR: Unable to open file.");
return Ok(not_found());
}
let file: File = file.unwrap();
let reader_stream = ReaderStream::new(file);
let stream_body = StreamBody::new(reader_stream.map_ok(Frame::data));
let boxed_body = stream_body.boxed();
let response = Response::builder()
.status(StatusCode::OK)
.body(boxed_body)
.unwrap();
Ok(response)
}