macroblog.rs @ 96c2cbe1850f95806cccb6f47a7739eb9c2ac860

 1use crate::assets::PostAsset;
 2use regex::Regex;
 3
 4const ACTION_REGEX: &str = r"/{0,1}(?P<action>\w*)/(?P<id>.+)";
 5
 6pub enum Router {
 7    NotFound,
 8    Index,
 9    Post { page: String },
10}
11
12pub fn blog_post_exists(name: &str) -> bool {
13    PostAsset::iter().any(|x| name.eq(&x.to_string()))
14}
15
16impl Router {
17    pub fn new(path: &str) -> Router {
18        let re = Regex::new(ACTION_REGEX).unwrap();
19        let caps = re.captures(path);
20        let action = match caps {
21            Some(ref value) => &value["action"],
22            None => "index",
23        };
24
25
26        // this 7 means the "/posts/" from the full path
27        let trimmed_path: String = path.chars().skip(7).collect();
28        if action.eq("posts") && !blog_post_exists(&trimmed_path) {
29            return Router::NotFound;
30        }
31
32        match action {
33            "posts" => Router::Post {
34                page: caps.unwrap()["id"].to_string(),
35            },
36            "index" => Router::Index,
37            _ => Router::NotFound,
38        }
39    }
40}