as_box method and some fixes

This commit is contained in:
MeexReay 2025-01-14 15:53:37 +03:00
parent fb9c4c97c5
commit 6e57913905
7 changed files with 24 additions and 6 deletions

View File

@ -1,5 +1,6 @@
use std::time::Duration;
use async_trait::async_trait;
use ezhttp::{
body::Body,
headers::Headers,
@ -62,14 +63,15 @@ impl EzSite {
}
}
#[async_trait]
impl HttpServer for EzSite {
async fn on_request(&self, req: &HttpRequest) -> Option<impl Sendable> {
async fn on_request(&self, req: &HttpRequest) -> Option<Box<dyn Sendable>> {
println!("{} > {} {}", req.addr, req.method, req.url.to_path_string());
if let Some(resp) = self.get_main_page(req).await {
Some(resp)
Some(resp.as_box())
} else if let Some(resp) = self.get_unknown_page(req).await {
Some(resp)
Some(resp.as_box())
} else {
None // shutdown connection
}

View File

@ -1,9 +1,11 @@
use async_trait::async_trait;
use ezhttp::{prelude::*, Sendable};
struct EzSite(String);
#[async_trait]
impl HttpServer for EzSite {
async fn on_request(&self, req: &HttpRequest) -> Option<impl Sendable> {
async fn on_request(&self, req: &HttpRequest) -> Option<Box<dyn Sendable>> {
println!("{} > {} {}", req.addr, req.method, req.url.to_path_string());
if req.url.path == "/" {
@ -13,7 +15,7 @@ impl HttpServer for EzSite {
("Content-Type", "text/html"), // - content type
("Content-Length", self.0.len().to_string().as_str()) // - content length
]), Body::from_text(&self.0.clone()), // response body
))
).as_box())
} else {
None // close connection
}

View File

@ -160,6 +160,9 @@ impl Sendable for Body {
) -> Result<(), HttpError> {
stream.write_all(&self.as_bytes()).await.map_err(|_| HttpError::WriteHeadError)
}
fn as_box(self) -> Box<dyn Sendable> {
Box::new(self)
}
}
impl Default for Body {

View File

@ -144,4 +144,7 @@ impl Sendable for Headers {
}
stream.write_all(head.as_bytes()).await.map_err(|_| HttpError::WriteHeadError)
}
fn as_box(self) -> Box<dyn Sendable> {
Box::new(self)
}
}

View File

@ -16,7 +16,8 @@ pub mod prelude {
pub use super::server::*;
pub use super::server::handler::*;
pub use super::server::starter::*;
pub use super::client::*;
// pub use super::client::*;
pub use super::*;
}
use error::HttpError;
@ -113,6 +114,7 @@ pub trait Sendable: Send + Sync {
&self,
stream: &mut (dyn AsyncWrite + Unpin + Send + Sync),
) -> Result<(), HttpError>;
fn as_box(self) -> Box<dyn Sendable>;
}
pub type Stream = TimeoutStream<TcpStream>;

View File

@ -216,4 +216,7 @@ impl Sendable for HttpRequest {
Ok(())
}
fn as_box(self) -> Box<dyn Sendable> {
Box::new(self)
}
}

View File

@ -93,4 +93,7 @@ impl Sendable for HttpResponse {
Ok(())
}
fn as_box(self) -> Box<dyn Sendable> {
Box::new(self)
}
}