loadstar/examples/hello_world.rs

90 lines
2.0 KiB
Rust
Raw Permalink Normal View History

use std::{collections::HashMap, sync::Arc, thread::sleep, time::Duration};
2024-08-21 12:55:30 +00:00
use loadstar::{controller::Controller, entities::request::Url, router::Router, template::Template, utilities::{async_block::run_async, responses::{respond_not_found, respond_template}}};
2024-08-21 12:55:30 +00:00
use maud::html;
use tiny_http::Request;
async fn example_async() {
sleep(Duration::from_secs(1));
}
2024-08-21 12:55:30 +00:00
struct MainRouter {
routes: HashMap<String, fn(Request)>
}
impl Router for MainRouter {
fn new() -> Self {
MainRouter {
routes: HashMap::new(),
}
}
fn route(&self, request: Request) {
match self.routes.get(&request.get_url_without_parameters()) {
Some(handler) => handler(request),
None => respond_not_found(request),
}
}
fn add_route(&mut self, route: &str, route_function: fn(Request)) {
self.routes.insert(route.to_string(), route_function as fn(Request));
}
}
struct MainTemplate;
impl Template for MainTemplate {
fn render(&self) -> maud::Markup {
html! {
h1 {"Hello World"}
}
}
}
struct MainController;
impl MainController {
fn index_route(request: Request) {
run_async(example_async());
2024-08-21 12:55:30 +00:00
respond_template(request, MainTemplate {})
}
}
impl Controller for MainController {
fn register_routes(&self, router: &mut impl Router) {
router.add_route("/", MainController::index_route)
}
}
#[tokio::main]
async fn main() {
let server = tiny_http::Server::http("0.0.0.0:8000").unwrap();
let mut main_router = MainRouter::new();
main_router.add_controller(MainController {});
let router = Arc::new(main_router);
loop {
let request = match server.recv() {
Ok(rq) => rq,
Err(e) => {
println!("error: {}", e);
break;
}
};
let router_clone = Arc::clone(&router);
tokio::spawn(async move {
router_clone.route(request);
});
}
}