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