diff options
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 85 |
1 files changed, 43 insertions, 42 deletions
diff --git a/src/main.rs b/src/main.rs index 1fb0e90..cabff0e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,54 +1,59 @@ +pub mod router; + use std::convert::Infallible; -use std::{include_str, env}; +use rust_embed::RustEmbed; +use std::{env, str}; use std::net::SocketAddr; use hyper::{Body, Request, Response, Server}; use hyper::service::{make_service_fn, service_fn}; -use regex::Regex; use sailfish::TemplateOnce; - +use ::router::Router; #[derive(TemplateOnce)] #[template(path = "index.html")] struct IndexTemplate { - posts: [Post; 2], + posts: Vec<String>, } #[derive(TemplateOnce)] #[template(path = "post.html")] struct PostTemplate { - content: &'static str, + content: String, } +#[derive(RustEmbed)] +#[folder = "content/posts/"] +struct PostAsset; + -struct Post( - u8, - &'static str, - &'static str, -); - -const POSTS: [Post; 2] = [ - Post( - 0, - "K8S private gitlab registry using podman", - include_str!("../assets/post1.html"), - ), - Post( - 1, - "Automation part 1", - include_str!("../assets/post2.html"), - ), -]; - -fn get_path_id(path: &str) -> usize { - let re = Regex::new(r"(?P<id>\d+)").unwrap(); - let caps = re.captures(path).unwrap(); - let id = &caps["id"]; - - return id.parse::<usize>().unwrap(); +fn get_file_content(path: &str) -> String { + let buffer = PostAsset::get(path) + .unwrap() + .data + .into_owned(); + + return String::from_utf8(buffer).unwrap(); } +fn get_post_title() -> Vec<String> { + PostAsset::iter() + .map(|e| format!("{}", e)) + .collect() +} + + +async fn not_found() -> Result<Response<Body>, Infallible> { + let resp: Response<Body> = Response::builder() + .status(404) + .body("Not Found".into()) + .unwrap(); + Ok(resp) +} + + async fn index() -> Result<Response<Body>, Infallible> { - let body = IndexTemplate { posts: POSTS } + let files = get_post_title(); + let body = IndexTemplate { posts: files } .render_once() .unwrap(); @@ -62,8 +67,8 @@ async fn index() -> Result<Response<Body>, Infallible> { } -async fn post(index: usize) -> Result<Response<Body>, Infallible> { - let body = PostTemplate { content: POSTS[index].2 } +async fn post(path: &String) -> Result<Response<Body>, Infallible> { + let body = PostTemplate { content: get_file_content(path) } .render_once() .unwrap(); @@ -78,16 +83,12 @@ async fn post(index: usize) -> Result<Response<Body>, Infallible> { async fn request(req: Request<Body>) -> Result<Response<Body>, Infallible> { let path = req.uri().path(); - if path == "/favicon.ico" { - return index().await - } - if path != "/" { - let index = get_path_id(&path); - return post(index).await; - } - - return index().await; + match Router::new(path) { + Router::Index => index().await, + Router::Post { page } => post(&page).await, + Router::NotFound => not_found().await + } } |