loadstar/examples/hello_world.rs
Jan Klattenhoff 91cc658d86
All checks were successful
Cargo Build & Test / Test publish (pull_request) Successful in 32s
Cargo Build & Test / Tests (pull_request) Successful in 36s
Cargo Build & Test / check-cargo-version (pull_request) Successful in 5s
Add example and change some code
2024-08-21 14:55:30 +02:00

86 lines
1.8 KiB
Rust

use std::{collections::HashMap, sync::Arc};
use loadstar::{controller::Controller, entities::request::Url, router::Router, template::Template, utilities::responses::{respond_not_found, respond_template}};
use maud::html;
use tiny_http::Request;
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) {
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);
});
}
}