forked from lavina/lavina
1
0
Fork 0
lavina/src/http.rs

84 lines
2.7 KiB
Rust
Raw Normal View History

2023-01-19 17:18:41 +00:00
use crate::prelude::*;
2023-01-25 12:50:14 +00:00
use std::convert::Infallible;
2023-01-26 21:11:28 +00:00
use http_body_util::{Full, BodyExt};
use hyper::{StatusCode, Method};
2023-01-19 17:18:41 +00:00
use hyper::server::conn::http1;
use hyper::{body::Bytes, service::service_fn, Request, Response};
2023-01-25 12:50:14 +00:00
use tokio::sync::oneshot::Sender;
use tokio::task::JoinHandle;
2023-01-19 17:18:41 +00:00
use tokio::net::TcpListener;
2023-01-25 12:50:14 +00:00
mod ws;
2023-01-26 21:11:28 +00:00
type BoxBody = http_body_util::combinators::BoxBody<Bytes, Infallible>;
async fn hello(
_: Request<hyper::body::Incoming>,
) -> std::result::Result<Response<Full<Bytes>>, Infallible> {
Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
}
fn not_found() -> std::result::Result<Response<Full<Bytes>>, Infallible> {
let mut response = Response::new(Full::new(Bytes::from("404")));
*response.status_mut() = StatusCode::NOT_FOUND;
Ok(response)
}
async fn route(request: Request<hyper::body::Incoming>) -> std::result::Result<Response<BoxBody>, Infallible> {
match (request.method(), request.uri().path()) {
(&Method::GET, "/hello") => Ok(hello(request).await?.map(BodyExt::boxed)),
(&Method::GET, "/socket") => Ok(ws::handle_request(request).await?.map(BodyExt::boxed)),
_ => Ok(not_found()?.map(BodyExt::boxed)),
}
}
2023-01-19 17:18:41 +00:00
pub struct HttpServerActor {
terminator: Sender<()>,
fiber: JoinHandle<Result<()>>,
}
impl HttpServerActor {
pub async fn launch(listener: TcpListener) -> Result<HttpServerActor> {
let (terminator, receiver) = tokio::sync::oneshot::channel::<()>();
let fiber = tokio::task::spawn(Self::main_loop(listener, receiver));
Ok(HttpServerActor { terminator, fiber })
}
pub async fn terminate(self) -> Result<()> {
match self.terminator.send(()) {
Ok(_) => {}
Err(_) => failure("wat")?,
}
self.fiber.await??;
Ok(())
}
async fn main_loop(listener: TcpListener, termination: impl Future) -> Result<()> {
log::info!("Starting the http server");
pin!(termination);
loop {
select! {
_ = &mut termination => {
log::info!("Terminating the http server");
return Ok(())
},
result = listener.accept() => {
let (stream, _) = result?;
tokio::task::spawn(async move {
if let Err(err) = http1::Builder::new()
2023-01-26 21:11:28 +00:00
.serve_connection(stream, service_fn(route))
2023-01-25 12:50:14 +00:00
.with_upgrades()
2023-01-19 17:18:41 +00:00
.await
{
tracing::error!("Error serving connection: {:?}", err);
}
});
},
}
}
}
}