server rewrite

This commit is contained in:
MeexReay 2024-11-27 20:30:05 +03:00
parent 1ae196d322
commit 24db811c57
18 changed files with 947 additions and 786 deletions

View file

@ -1,69 +0,0 @@
use ezhttp::{Headers, HttpRequest, HttpResponse, HttpServer, HttpServerStarter};
use std::{
io::{stdin, stdout, Error, Write},
time::Duration,
};
struct EzSite {
index_page: String,
}
impl EzSite {
fn new(index_page: &str) -> Self {
EzSite {
index_page: index_page.to_string(),
}
}
}
impl HttpServer for EzSite {
async fn on_request(&self, req: &HttpRequest) -> Option<HttpResponse> {
// println!("{} > {} {}", req.addr, req.method, req.page);
if req.page == "/" {
Some(HttpResponse::from_string(
Headers::from(vec![("Content-Type", "text/html")]), // response headers
"200 OK", // response status code
&self.index_page, // response body
))
} else {
None // close connection
}
}
async fn on_start(&self, _: &str) {
// println!("Http server started on {}", host);
}
async fn on_close(&self) {
// println!("Http server closed");
}
}
fn input(prompt: &str) -> Result<String, Error> {
stdout().write_all(prompt.as_bytes())?;
stdout().flush()?;
let mut buf = String::new();
stdin().read_line(&mut buf)?;
Ok(buf)
}
fn main() {
let site_1 = HttpServerStarter::new(EzSite::new("Hello World! site_1"), "localhost:8080")
.timeout(Some(Duration::from_secs(5))) // read & write timeout
.threads(5) // threadpool size
.start();
let site_2 = HttpServerStarter::new(EzSite::new("Hello World! site_2"), "localhost:8081")
.timeout(Some(Duration::from_secs(5))) // read & write timeout
.threads(5) // threadpool size
.start();
input("enter to close site_1").unwrap();
site_1.close();
input("enter to close site_2").unwrap();
site_2.close();
}

View file

@ -1,6 +1,19 @@
use ezhttp::{Headers, HttpRequest, HttpResponse, HttpServer, HttpServerStarter};
use std::time::Duration;
use ezhttp::{
body::Body,
headers::Headers,
request::HttpRequest,
response::{
status_code::{NOT_FOUND, OK},
HttpResponse
},
server::{
starter::HttpServerStarter,
HttpServer
}
};
struct EzSite {
main_page: String,
}
@ -13,23 +26,31 @@ impl EzSite {
}
fn ok_response(&self, content: String) -> HttpResponse {
HttpResponse::from_string(
Headers::from(vec![("Content-Type", "text/html")]),
"200 OK".to_string(),
content,
HttpResponse::new(
OK,
Headers::from(vec![
("Content-Length", content.len().to_string().as_str()),
("Content-Type", "text/html"),
("Connection", "keep-alive"),
]),
Body::from_text(&content),
)
}
fn not_found_response(&self, content: String) -> HttpResponse {
HttpResponse::from_string(
Headers::from(vec![("Content-Type", "text/html")]),
"404 Not Found".to_string(),
content,
HttpResponse::new(
NOT_FOUND,
Headers::from(vec![
("Content-Length", content.len().to_string().as_str()),
("Content-Type", "text/html"),
("Connection", "keep-alive"),
]),
Body::from_text(&content),
)
}
async fn get_main_page(&self, req: &HttpRequest) -> Option<HttpResponse> {
if req.page == "/" {
if req.url.path == "/" {
Some(self.ok_response(self.main_page.clone()))
} else {
None
@ -37,20 +58,20 @@ impl EzSite {
}
async fn get_unknown_page(&self, req: &HttpRequest) -> Option<HttpResponse> {
Some(self.not_found_response(format!("<h1>404 Error</h1>Not Found {}", &req.page)))
Some(self.not_found_response(format!("<h1>404 Error</h1>Not Found {}", &req.url.path)))
}
}
impl HttpServer for EzSite {
async fn on_request(&self, req: &HttpRequest) -> Option<HttpResponse> {
println!("{} > {} {}", req.addr, req.method, req.page);
println!("{} > {} {}", req.addr, req.method, req.url.to_path_string());
if let Some(resp) = self.get_main_page(req).await {
Some(resp)
} else if let Some(resp) = self.get_unknown_page(req).await {
Some(resp)
} else {
None // shutdown socket
None // shutdown connection
}
}
@ -66,7 +87,7 @@ impl HttpServer for EzSite {
#[tokio::main]
async fn main() {
let site = EzSite::new("<h1>Hello World!</h1>");
let host = "localhost:8080";
let host = "localhost:8000";
HttpServerStarter::new(site, host)
.timeout(Some(Duration::from_secs(5)))

34
examples/small_site.rs Normal file
View file

@ -0,0 +1,34 @@
use ezhttp::prelude::*;
struct EzSite(String);
impl HttpServer for EzSite {
async fn on_request(&self, req: &HttpRequest) -> Option<HttpResponse> {
println!("{} > {} {}", req.addr, req.method, req.url.to_path_string());
if req.url.path == "/" {
Some(HttpResponse::new(
OK, // response status code
Headers::from(vec![ // response headers
("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
))
} else {
None // close connection
}
}
async fn on_start(&self, host: &str) {
println!("Http server started on {}", host);
}
async fn on_close(&self) {
println!("Http server closed");
}
}
#[tokio::main]
async fn main() {
start_server(EzSite("Hello World!".to_string()), "localhost:8080").await.expect("http server error");
}