86 lines
1.8 KiB
Rust
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);
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|