Markdown (.md) support

This commit is contained in:
2025-05-04 22:12:49 +02:00
parent 1b27506149
commit deaad74dc8
2 changed files with 52 additions and 1 deletions

View File

@@ -17,6 +17,11 @@ pub static TERA: LazyLock<Tera> = LazyLock::new(|| {
include_str!("../templates/index.html.jinja"),
)
.unwrap();
tera.add_raw_template(
"markdown.html.jinja",
include_str!("../templates/markdown.html.jinja"),
)
.unwrap();
tera.register_filter("iconize", iconize);
tera.register_filter("from_ico", from_ico);
tera.register_filter("size", size);
@@ -63,6 +68,16 @@ pub async fn render_index(path: &PathBuf, time: Instant) -> AResult<String> {
Ok(tera.render("index.html.jinja", &context)?)
}
pub fn render_markdown(filename: &str, content: &str) -> AResult<String> {
let tera = &*TERA;
let mut context = Context::new();
context.insert("filename", &filename);
context.insert("content", &content);
Ok(tera.render("markdown.html.jinja", &context)?)
}
async fn get_directories(path: &PathBuf) -> AResult<Vec<FileInfo>> {
let mut contents = ReadDirStream::new(tokio::fs::read_dir(&path).await?);

View File

@@ -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