Skip to content

Commit

Permalink
bump to version 0.1.1, and now routers are working with a somewhat mo…
Browse files Browse the repository at this point in the history
…re stable routing system
  • Loading branch information
Waayway committed Mar 15, 2023
1 parent 9fc827f commit 2e54506
Show file tree
Hide file tree
Showing 7 changed files with 192 additions and 78 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "arcanum"
version = "0.1.0"
version = "0.1.1"
authors = ["Waayway"]
description = "A simple library to create web applications with a Django inspired interface"
homepage = "https://github.com/Waayway/arcanum"
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# Arcanum
**THIS PROJECT IS STILL IN DEVELOPMENT SO IT ISN'T DONE YET AND THINGS WILL CHANGE**


This is a side project i've started to create a simple framework for myself.

Expand All @@ -9,6 +11,7 @@ TODO list:
- [ ] Models (DB)
- [ ] docs


## How to use
to use this library add
```toml
Expand Down
14 changes: 14 additions & 0 deletions examples/routing/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use arcanum::{WebServer, Router, Response, ReturnData, Request};

fn main() {
let mut server = WebServer::new("127.0.0.1", 7878);
let mut router = Router::new("/test");
router.add_simple_route("/", test);
router.add_simple_route("/test", test);
server.add_router(router);
server.run();
}

fn test(_req: Request, _res: &mut Response) -> ReturnData {
ReturnData::Text("Hello, World from /test".to_string())
}
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ mod models;
mod request;
mod response;
mod serve_files;
mod templates;
mod templates;
mod router;

pub use router::Router;
pub use webserver::WebServer;
pub use request::{Request};
pub use response::{Response, ReturnData};
Expand Down
114 changes: 114 additions & 0 deletions src/router.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
use std::{collections::HashMap, path::Path};

use crate::{serve_static_file, webserver::RouteHandler, Request, Response, ReturnData};

#[derive(Clone)]
pub struct Router {
basepath: String,
routes: HashMap<String, RouteHandler>,
}

impl Router {
pub fn new(base_path: &str) -> Self {
Self {
basepath: base_path.to_string(),
routes: HashMap::new(),
}
}

pub fn add_simple_route(
&mut self,
route: &str,
function: fn(_: Request, _: &mut Response) -> ReturnData,
) {
self.routes
.insert(route.to_owned(), RouteHandler::Simple(function));
}

pub fn add_route_with_params(
&mut self,
route: &str,
function: fn(Request, &mut Response, HashMap<String, String>) -> ReturnData,
) {
self.routes
.insert(route.to_owned(), RouteHandler::WithRouteParams(function));
}

pub fn add_static_file_route(&mut self, route: &str, path: &str) {
let mut params: HashMap<String, String> = HashMap::new();
params.insert("basepath".to_string(), path.to_string());
self.routes.insert(
route.to_owned(),
RouteHandler::WithRouteAndOptionalParams(
|_req: Request, res: &mut Response, params: HashMap<String, String>| {
if !params.contains_key("basepath") {
res.set_status_code(500);
return ReturnData::Text("Something went wrong!".to_string());
}
if !params.contains_key("path") {
res.set_status_code(403);
return ReturnData::Text("Cannot index folders".to_string());
} else if params["path"].ends_with("/") {
res.set_status_code(403);
return ReturnData::Text("Cannot index folders".to_string());
}
let path = Path::new(&params["basepath"]).join(&params["path"]);
serve_static_file(path.to_str().unwrap(), res)
},
params,
),
);
}



pub fn does_path_exists(
&self,
path: &str,
) -> Option<String> {
let mut current_path = None;
let path_parts: Vec<&str> = path.split("/").filter(|i| !i.is_empty()).collect();
for i in self.routes.clone() {
let mut route_parts: Vec<&str> = i.0.split("/").filter(|i| !i.is_empty()).collect();
let basepath_parts: Vec<&str> = self.basepath.split("/").filter(|i| !i.is_empty()).collect();
route_parts.extend(basepath_parts);
// println!("route_parts: {route_parts:?}\n path_parts: {path_parts:?}\n");
if route_parts.len() != path_parts.len() {
let diff = path_parts.len() as i32 - route_parts.len() as i32;
if diff > 0 {
for _ in 0..diff {
route_parts.push("");
}
}
}
if route_parts == path_parts {
current_path = Some(i.0.to_owned());
continue;
}

for (route_part, path_part) in route_parts.iter().zip(path_parts.iter()) {
// println!("route_part: {route_part}\n path_part: {path_part}\n");
if route_part.starts_with(":") || route_part == path_part || route_part == &"*" {
current_path = Some(i.0.to_owned());
} else if route_part == &"**" {
current_path = Some(i.0.to_owned());
break;
} else if route_part != path_part {
current_path = None;
break;
}
}
if current_path.is_some() {
break;
}
}
// DEBUG: println!("{:?}", current_path);
current_path
}
pub fn RouteHandlerFromPath(&self, path: String) -> Option<RouteHandler> {
if self.routes.keys().any(|i| i == &path) {
return Some(self.routes[&path].clone());
}
None
}
}
Loading

0 comments on commit 2e54506

Please sign in to comment.