blogit/src/main.rs

64 lines
2.0 KiB
Rust

use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use pulldown_cmark::{html, Options, Parser};
async fn hello_world(req: Request<Body>) -> Result<Response<Body>, Infallible> {
println!("New request to '{}'", req.uri());
let path = &req
.uri()
.path()[1..] // Remove the first "/". We don't need it
.replace("..", "") // Don't allow to go up in the hierarchy
;
// Get the first part so we can route it
let until = path.find('/').unwrap_or(path.len());
let mut response = Response::new(Body::empty());
match (req.method(), &path[..until]) {
(&Method::GET, "") => {
*response.body_mut() = Body::from("You shouldn't be reading this.");
}
(&Method::GET, "blog") => {
*response.body_mut() = Body::from(file_to_md(path));
}
(_, path) => {
*response.body_mut() = Body::from(format!("Path {path} not found."));
*response.status_mut() = StatusCode::NOT_FOUND;
}
}
Ok(response)
}
fn file_to_md(path: &str) -> String {
let file = std::fs::read_to_string(path).unwrap_or("File not found.".to_string());
//let mut options = Options::empty();
//options.insert(Options::ENABLE_STRIKETHROUGH);
let parser = Parser::new_ext(file.as_str(), Options::ENABLE_STRIKETHROUGH);
// Write to String buffer.
let mut html_output: String = String::with_capacity(file.len() * 3 / 2);
html::push_html(&mut html_output, parser);
html_output
}
#[tokio::main]
async fn main() {
let addr = ([127, 0, 0, 1], 3000).into();
let make_svc = make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(hello_world)) });
let server = Server::bind(&addr).serve(make_svc);
println!("Server listening on: http://{}", addr);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}