diff --git a/src/http.rs b/src/http.rs index 0757cdc..c8c9efc 100644 --- a/src/http.rs +++ b/src/http.rs @@ -2,7 +2,8 @@ use crate::prelude::*; use std::convert::Infallible; -use http_body_util::Full; +use http_body_util::{Full, BodyExt}; +use hyper::{StatusCode, Method}; use hyper::server::conn::http1; use hyper::{body::Bytes, service::service_fn, Request, Response}; @@ -12,6 +13,28 @@ use tokio::net::TcpListener; mod ws; +type BoxBody = http_body_util::combinators::BoxBody; + +async fn hello( + _: Request, +) -> std::result::Result>, Infallible> { + Ok(Response::new(Full::new(Bytes::from("Hello World!")))) +} + +fn not_found() -> std::result::Result>, Infallible> { + let mut response = Response::new(Full::new(Bytes::from("404"))); + *response.status_mut() = StatusCode::NOT_FOUND; + Ok(response) +} + +async fn route(request: Request) -> std::result::Result, 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)), + } +} + pub struct HttpServerActor { terminator: Sender<()>, fiber: JoinHandle>, @@ -32,12 +55,6 @@ impl HttpServerActor { Ok(()) } - async fn hello( - _: Request, - ) -> std::result::Result>, Infallible> { - Ok(Response::new(Full::new(Bytes::from("Hello World!")))) - } - async fn main_loop(listener: TcpListener, termination: impl Future) -> Result<()> { log::info!("Starting the http server"); pin!(termination); @@ -52,7 +69,7 @@ impl HttpServerActor { let (stream, _) = result?; tokio::task::spawn(async move { if let Err(err) = http1::Builder::new() - .serve_connection(stream, service_fn(ws::handle_request)) + .serve_connection(stream, service_fn(route)) .with_upgrades() .await { diff --git a/src/http/ws.rs b/src/http/ws.rs index a0d71c6..dada0c7 100644 --- a/src/http/ws.rs +++ b/src/http/ws.rs @@ -103,6 +103,5 @@ pub async fn handle_request( res.headers_mut().append(UPGRADE, websocket); res.headers_mut() .append(SEC_WEBSOCKET_ACCEPT, derived.unwrap().parse().unwrap()); - dbg!(&res); Ok(res) } diff --git a/src/main.rs b/src/main.rs index 71f8188..7d72c5b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,16 +8,14 @@ use tcp::ClientSocketActor; use std::collections::HashMap; use std::future::Future; use std::net::SocketAddr; -use std::time::Duration; use figment::providers::Format; use tokio::net::{TcpListener, TcpStream}; use figment::{providers::Toml, Figment}; use serde::Deserialize; -use tokio::io::{AsyncWriteExt, BufWriter}; -use tokio::sync::mpsc::{Receiver, Sender}; -use tokio::task::JoinHandle; +use tokio::io::BufWriter; +use tokio::sync::mpsc::Sender; #[derive(Deserialize, Debug)] struct ServerConfig {