small_site/
small_site.rs

1use async_trait::async_trait;
2use ezhttp::{prelude::*, Sendable};
3
4struct EzSite(String);
5
6#[async_trait]
7impl HttpServer for EzSite {
8    async fn on_request(&self, req: &HttpRequest) -> Option<Box<dyn Sendable>> {
9        println!("{} > {} {}", req.addr, req.method, req.url.to_path_string());
10
11        if req.url.path == "/" {
12            Some(HttpResponse::new(
13                OK,                                                    // response status code
14                Headers::from(vec![                                                // response headers
15                    ("Content-Type", "text/html"),                                 // - content type
16                    ("Content-Length", self.0.len().to_string().as_str())          // - content length
17                ]), Body::from_text(&self.0.clone()),                              // response body
18            ).as_box())
19        } else {
20            None // close connection
21        }
22    }
23
24    async fn on_start(&self, host: &str) {
25        println!("Http server started on {}", host);
26    }
27
28    async fn on_close(&self) {
29        println!("Http server closed");
30    }
31}
32
33#[tokio::main]
34async fn main() {
35    start_server(EzSite("Hello World!".to_string()), "localhost:8080").await.expect("http server error");
36}