add a simple router

This commit is contained in:
Nikita Vilunov 2023-01-27 01:11:28 +04:00
parent 31ffe41929
commit 0b0c432bb8
3 changed files with 27 additions and 13 deletions

View File

@ -2,7 +2,8 @@ use crate::prelude::*;
use std::convert::Infallible; 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::server::conn::http1;
use hyper::{body::Bytes, service::service_fn, Request, Response}; use hyper::{body::Bytes, service::service_fn, Request, Response};
@ -12,6 +13,28 @@ use tokio::net::TcpListener;
mod ws; mod ws;
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)),
}
}
pub struct HttpServerActor { pub struct HttpServerActor {
terminator: Sender<()>, terminator: Sender<()>,
fiber: JoinHandle<Result<()>>, fiber: JoinHandle<Result<()>>,
@ -32,12 +55,6 @@ impl HttpServerActor {
Ok(()) Ok(())
} }
async fn hello(
_: Request<hyper::body::Incoming>,
) -> std::result::Result<Response<Full<Bytes>>, Infallible> {
Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
}
async fn main_loop(listener: TcpListener, termination: impl Future) -> Result<()> { async fn main_loop(listener: TcpListener, termination: impl Future) -> Result<()> {
log::info!("Starting the http server"); log::info!("Starting the http server");
pin!(termination); pin!(termination);
@ -52,7 +69,7 @@ impl HttpServerActor {
let (stream, _) = result?; let (stream, _) = result?;
tokio::task::spawn(async move { tokio::task::spawn(async move {
if let Err(err) = http1::Builder::new() if let Err(err) = http1::Builder::new()
.serve_connection(stream, service_fn(ws::handle_request)) .serve_connection(stream, service_fn(route))
.with_upgrades() .with_upgrades()
.await .await
{ {

View File

@ -103,6 +103,5 @@ pub async fn handle_request(
res.headers_mut().append(UPGRADE, websocket); res.headers_mut().append(UPGRADE, websocket);
res.headers_mut() res.headers_mut()
.append(SEC_WEBSOCKET_ACCEPT, derived.unwrap().parse().unwrap()); .append(SEC_WEBSOCKET_ACCEPT, derived.unwrap().parse().unwrap());
dbg!(&res);
Ok(res) Ok(res)
} }

View File

@ -8,16 +8,14 @@ use tcp::ClientSocketActor;
use std::collections::HashMap; use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::time::Duration;
use figment::providers::Format; use figment::providers::Format;
use tokio::net::{TcpListener, TcpStream}; use tokio::net::{TcpListener, TcpStream};
use figment::{providers::Toml, Figment}; use figment::{providers::Toml, Figment};
use serde::Deserialize; use serde::Deserialize;
use tokio::io::{AsyncWriteExt, BufWriter}; use tokio::io::BufWriter;
use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::mpsc::Sender;
use tokio::task::JoinHandle;
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
struct ServerConfig { struct ServerConfig {