1
2use std::convert::Infallible;
3use std::{env};
4use std::net::SocketAddr;
5use hyper::{Body, Request, Response, Server};
6use hyper::service::{make_service_fn, service_fn};
7use macroblog::router::Router;
8use macroblog::blog::{render_index_page, render_post_page};
9
10
11async fn not_found() -> Result<Response<Body>, Infallible> {
12 let resp: Response<Body> = Response::builder()
13 .status(404)
14 .body("Not Found".into())
15 .unwrap();
16 Ok(resp)
17}
18
19
20async fn index() -> Result<Response<Body>, Infallible> {
21 let body = render_index_page();
22
23 let resp: Response<Body> = Response::builder()
24 .status(200)
25 .header("posts-type", "text/html")
26 .body(body.into())
27 .unwrap();
28
29 Ok(resp)
30}
31
32
33async fn post(path: &String) -> Result<Response<Body>, Infallible> {
34 let body = render_post_page(path);
35
36 let resp: Response<Body> = Response::builder()
37 .status(200)
38 .header("posts-type", "text/html")
39 .body(body.into())
40 .unwrap();
41
42 Ok(resp)
43}
44
45async fn request(req: Request<Body>) -> Result<Response<Body>, Infallible> {
46 let path = req.uri().path();
47
48 match Router::new(path) {
49 Router::Index => index().await,
50 Router::Post { page } => post(&page).await,
51 Router::NotFound => not_found().await
52 }
53}
54
55
56#[tokio::main]
57async fn main() {
58 let port = env::var("PORT").unwrap_or("3000".into()).parse::<u16>().unwrap_or(3000);
59 let addr = SocketAddr::from(([0, 0, 0, 0], port));
60
61 let make_svc = make_service_fn(|_conn| async {
62 Ok::<_, Infallible>(service_fn(request))
63 });
64
65 let server = Server::bind(&addr).serve(make_svc);
66
67 if let Err(e) = server.await {
68 eprintln!("server error: {}", e);
69 }
70}