Markdown (.md) support
This commit is contained in:
38
src/main.rs
38
src/main.rs
@@ -4,6 +4,7 @@ mod index;
|
||||
|
||||
use std::{collections::HashMap, fs, io::ErrorKind, path::PathBuf, str::FromStr, sync::LazyLock};
|
||||
|
||||
use index::render_markdown;
|
||||
use mlua::{
|
||||
Lua, Number, Table,
|
||||
Value::{self as LuaValue},
|
||||
@@ -97,8 +98,43 @@ async fn file_handler(request: Request) -> impl IntoResponse {
|
||||
}
|
||||
}
|
||||
|
||||
if request_uri_path.to_lowercase().ends_with(".md") {
|
||||
let mut path = base_dir.clone();
|
||||
|
||||
let uri = urlencoding::decode(&request_uri_path[1..]).map_err(|e| {
|
||||
println!("{:?}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
|
||||
})?;
|
||||
|
||||
path.push(&*uri);
|
||||
let full_path = fs::canonicalize(&path).map_err(|e| {
|
||||
println!("{:?}", e);
|
||||
(StatusCode::NOT_FOUND, "404: Not Found".to_string())
|
||||
})?;
|
||||
|
||||
let full_base_path = fs::canonicalize(&base_dir).map_err(|e| {
|
||||
println!("{:?}", e);
|
||||
(StatusCode::NOT_FOUND, "404: Not Found".to_string())
|
||||
})?;
|
||||
|
||||
if !full_path.starts_with(&full_base_path) {
|
||||
return Err((StatusCode::BAD_REQUEST, "400: Bad Request".to_string()));
|
||||
}
|
||||
|
||||
let script = fs::read_to_string(&full_path).map_err(|e| {
|
||||
eprintln!("Lua Read Error: {:?}", e);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
|
||||
})?;
|
||||
|
||||
let filename = full_path.file_name().unwrap_or_default().to_string_lossy();
|
||||
|
||||
if let Ok(md) = markdown::to_html_with_options(&script, &markdown::Options::gfm()) {
|
||||
return Ok(Html(render_markdown(&filename, &md).unwrap()).into_response());
|
||||
}
|
||||
}
|
||||
|
||||
if !request_uri_path.ends_with(".lua") {
|
||||
return ServeDir::new(base_dir)
|
||||
return ServeDir::new(&base_dir)
|
||||
.fallback(get(handler))
|
||||
.try_call(request)
|
||||
.await
|
||||
|
Reference in New Issue
Block a user