chore: clean up, rename types.rs to server.rs
This commit is contained in:
parent
a8bc61f40c
commit
0c68399210
9 changed files with 110 additions and 41 deletions
69
src/server.rs
Normal file
69
src/server.rs
Normal file
|
@ -0,0 +1,69 @@
|
|||
use std::error::Error;
|
||||
|
||||
use http_body_util::{Either, Full};
|
||||
use hyper::{
|
||||
Request, Response,
|
||||
body::{Body, Bytes, Incoming},
|
||||
server::conn::http1,
|
||||
service::{HttpService, Service},
|
||||
};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use log::error;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
pub type GeneralResponse = Response<GeneralBody>;
|
||||
pub type GeneralBody = Either<Incoming, Full<Bytes>>;
|
||||
|
||||
pub fn to_general_response(res: Response<Incoming>) -> GeneralResponse {
|
||||
let (parts, body) = res.into_parts();
|
||||
Response::from_parts(parts, GeneralBody::Left(body))
|
||||
}
|
||||
|
||||
pub struct Server<S> {
|
||||
listener: TcpListener,
|
||||
service: S,
|
||||
}
|
||||
|
||||
pub trait TcpIntercept {
|
||||
fn stream(&mut self, stream: &TcpStream);
|
||||
}
|
||||
|
||||
impl<S> Server<S>
|
||||
where
|
||||
S: TcpIntercept,
|
||||
S: Service<Request<Incoming>> + Clone + Send + 'static,
|
||||
S: HttpService<Incoming> + Clone + Send,
|
||||
<S::ResBody as Body>::Error: Into<Box<dyn Error + Send + Sync>>,
|
||||
<S::ResBody as Body>::Data: Send,
|
||||
S::ResBody: Send,
|
||||
<S as HttpService<Incoming>>::Future: Send,
|
||||
{
|
||||
pub async fn handle(&self) {
|
||||
loop {
|
||||
let (stream, _) = self.listener.accept().await.unwrap();
|
||||
|
||||
let mut svc_clone = self.service.clone();
|
||||
svc_clone.stream(&stream);
|
||||
|
||||
let io = TokioIo::new(stream);
|
||||
tokio::task::spawn(async move {
|
||||
if let Err(err) = http1::Builder::new()
|
||||
.writev(false)
|
||||
.serve_connection(io, svc_clone)
|
||||
.await
|
||||
{
|
||||
error!("Error while trying to serve connection: {err}")
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn new(service: S, a: (String, u16)) -> Result<Self, Box<dyn Error>> {
|
||||
Ok(Self {
|
||||
listener: TcpListener::bind(&a).await?,
|
||||
service,
|
||||
})
|
||||
}
|
||||
}
|
||||
/*
|
||||
*/
|
Loading…
Add table
Add a link
Reference in a new issue