aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 49815b8088ca761462b7d9aa62f0560ce877d2cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::convert::Infallible;
use std::{include_str, env};
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 {
    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<id>\d+)").unwrap();
    let caps = re.captures(path).unwrap();
    let id = &caps["id"];

    return id.parse::<usize>().unwrap();
}

async fn index() -> Result<Response<Body>, Infallible> {
    let body = IndexTemplate { posts: POSTS }
        .render_once()
        .unwrap();

    let resp: Response<Body> = Response::builder()
        .status(200)
        .header("posts-type", "text/html")
        .body(body.into())
        .unwrap();

    Ok(resp)
}


async fn post(index: usize) -> Result<Response<Body>, Infallible> {
    let body = PostTemplate { content: POSTS[index].2 }
        .render_once()
        .unwrap();

    let resp: Response<Body> = Response::builder()
        .status(200)
        .header("posts-type", "text/html")
        .body(body.into())
        .unwrap();

    Ok(resp)
}

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;
}


#[tokio::main]
async fn main() {
    let port = env::var("PORT").unwrap_or("3000".into()).parse::<u16>().unwrap_or(300);
    let addr = SocketAddr::from(([127, 0, 0, 1], port));

    let make_svc = make_service_fn(|_conn| async {
        Ok::<_, Infallible>(service_fn(request))
    });

    let server = Server::bind(&addr).serve(make_svc);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}