simple_site/
simple_site.rs1use std::time::Duration;
2
3use async_trait::async_trait;
4use ezhttp::{
5 body::Body,
6 headers::Headers,
7 request::HttpRequest,
8 response::{
9 status_code::{NOT_FOUND, OK},
10 HttpResponse
11 },
12 server::{
13 starter::HttpServerStarter,
14 HttpServer
15 }, Sendable
16};
17
18struct EzSite {
19 main_page: String,
20}
21
22impl EzSite {
23 fn new(index_page: &str) -> Self {
24 EzSite {
25 main_page: index_page.to_string(),
26 }
27 }
28
29 fn ok_response(&self, content: String) -> HttpResponse {
30 HttpResponse::new(
31 OK,
32 Headers::from(vec![
33 ("Content-Length", content.len().to_string().as_str()),
34 ("Content-Type", "text/html"),
35 ("Connection", "keep-alive"),
36 ]),
37 Body::from_text(&content),
38 )
39 }
40
41 fn not_found_response(&self, content: String) -> HttpResponse {
42 HttpResponse::new(
43 NOT_FOUND,
44 Headers::from(vec![
45 ("Content-Length", content.len().to_string().as_str()),
46 ("Content-Type", "text/html"),
47 ("Connection", "keep-alive"),
48 ]),
49 Body::from_text(&content),
50 )
51 }
52
53 async fn get_main_page(&self, req: &HttpRequest) -> Option<HttpResponse> {
54 if req.url.path == "/" {
55 Some(self.ok_response(self.main_page.clone()))
56 } else {
57 None
58 }
59 }
60
61 async fn get_unknown_page(&self, req: &HttpRequest) -> Option<HttpResponse> {
62 Some(self.not_found_response(format!("<h1>404 Error</h1>Not Found {}", &req.url.path)))
63 }
64}
65
66#[async_trait]
67impl HttpServer for EzSite {
68 async fn on_request(&self, req: &HttpRequest) -> Option<Box<dyn Sendable>> {
69 println!("{} > {} {}", req.addr, req.method, req.url.to_path_string());
70
71 if let Some(resp) = self.get_main_page(req).await {
72 Some(resp.as_box())
73 } else if let Some(resp) = self.get_unknown_page(req).await {
74 Some(resp.as_box())
75 } else {
76 None }
78 }
79
80 async fn on_start(&self, host: &str) {
81 println!("Http server started on {}", host);
82 }
83
84 async fn on_close(&self) {
85 println!("Http server closed");
86 }
87}
88
89#[tokio::main]
90async fn main() {
91 let site = EzSite::new("<h1>Hello World!</h1>");
92 let host = "localhost:8000";
93
94 HttpServerStarter::new(site, host)
95 .timeout(Some(Duration::from_secs(5)))
96 .threads(5)
97 .start_forever()
98 .await
99 .expect("http server error");
100}