From a16e8a21bb83325f8e40c13ef2d052393e2f6489 Mon Sep 17 00:00:00 2001 From: "Gabriel A. Giovanini" Date: Sat, 7 May 2022 00:29:01 +0200 Subject: feat: Add early blog implementation It is just a really crappy implementation to get it running until a figure the pieces of the project out. --- src/main.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 0c3565b..92f51a7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,38 +3,100 @@ use std::{include_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; #[derive(TemplateOnce)] #[template(path = "index.html")] struct IndexTemplate { - pico: &'static str, + posts: [Post; 2], +} + +#[derive(TemplateOnce)] +#[template(path = "post.html")] +struct PostTemplate { + content: &'static str, +} + + +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\d+)").unwrap(); + let caps = re.captures(path).unwrap(); + let id = &caps["id"]; + + return id.parse::().unwrap(); +} + +async fn index() -> Result, Infallible> { + let body = IndexTemplate { posts: POSTS } + .render_once() + .unwrap(); + + let resp: Response = Response::builder() + .status(200) + .header("posts-type", "text/html") + .body(body.into()) + .unwrap(); + + Ok(resp) } -const PICO_CSS: &str = include_str!("../assets/pico.min.css"); -async fn hello_world(_req: Request) -> Result, Infallible> { - let body = IndexTemplate { pico: PICO_CSS } +async fn post(index: usize) -> Result, Infallible> { + let body = PostTemplate { content: POSTS[index].2 } .render_once() .unwrap(); let resp: Response = Response::builder() .status(200) - .header("content-type", "text/html") + .header("posts-type", "text/html") .body(body.into()) .unwrap(); Ok(resp) } +async fn request(req: Request) -> Result, 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; +} + #[tokio::main] async fn main() { let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); let make_svc = make_service_fn(|_conn| async { - Ok::<_, Infallible>(service_fn(hello_world)) + Ok::<_, Infallible>(service_fn(request)) }); let server = Server::bind(&addr).serve(make_svc); -- cgit v1.2.3