aboutsummaryrefslogtreecommitdiff
path: root/src/bin/hyper.rs
blob: f24cbe46b848319154fbfdacb7eff5bf00d45968 (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
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use macroblog::blog::{render_index_page, render_post_page, render_projects};
use macroblog::router::Router;
use std::convert::Infallible;
use std::env;
use std::net::SocketAddr;

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 = render_index_page();

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

    Ok(resp)
}

async fn projects() -> Result<Response<Body>, Infallible> {
    let body = render_projects();

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

    Ok(resp)
}

async fn post(path: &String) -> Result<Response<Body>, Infallible> {
    let body = render_post_page(path);

    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();

    match Router::new(path) {
        Router::Index => index().await,
        Router::Projects => projects().await,
        Router::Post { page } => post(&page).await,
        Router::NotFound => not_found().await,
    }
}

#[tokio::main]
async fn main() {
    let port = env::var("PORT")
        .unwrap_or("3000".into())
        .parse::<u16>()
        .unwrap_or(3000);
    let addr = SocketAddr::from(([0, 0, 0, 0], 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);
    }
}