fix: auto index file path

This commit is contained in:
xfy
2025-06-22 23:10:23 +08:00
parent 7ffc681825
commit d905af58f5

View File

@ -169,7 +169,6 @@ pub async fn serve(
None => {
// 生成自动目录索引
if host_route.auto_index {
let list = list_dir(&req_path).await?;
// HTML 中的标题路径,需要移除掉配置文件中的 root = "./html" 字段
let host_root = if let Some(root) = &host_route.root {
root
@ -179,6 +178,7 @@ pub async fn serve(
let req_path_str = req_path.to_string_lossy();
debug!("req_path_str: {:?}", req_path_str);
let host_root = &req_path_str.strip_prefix(host_root).unwrap_or(host_root);
let list = list_dir(&req_path_str, &req_path).await?;
let list_html = render_list_html(host_root, list);
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("text/html"));
@ -394,7 +394,7 @@ fn render_list_html(root_path: &str, list: Vec<DirList>) -> String {
.map(|dist| {
format!(
r#"<tr><td><a href="{}">{}</a></td><td>{}</td><td>{}</td></tr>"#,
dist.path.display(),
dist.path,
dist.name,
dist.last_modified,
dist.size,
@ -480,7 +480,7 @@ fn render_list_html(root_path: &str, list: Vec<DirList>) -> String {
#[derive(Debug, Clone)]
pub struct DirList {
pub name: String, // 文件或目录名称
pub path: PathBuf, // 文件或目录的完整路径
pub path: String, // 文件或目录的完整路径
pub is_dir: bool, // 是否为目录
pub size: u64, // 文件大小(字节)
pub last_modified: String, // 最后修改时间的字符串表示
@ -496,7 +496,7 @@ pub struct DirList {
///
/// # 错误
/// 可能返回与文件系统操作相关的错误,如目录不存在、权限不足等
async fn list_dir(path: &PathBuf) -> anyhow::Result<Vec<DirList>> {
async fn list_dir(host_root_str: &str, path: &PathBuf) -> anyhow::Result<Vec<DirList>> {
use chrono::{Local, TimeZone};
use std::time::UNIX_EPOCH;
@ -515,6 +515,7 @@ async fn list_dir(path: &PathBuf) -> anyhow::Result<Vec<DirList>> {
.await
.with_context(|| format!("读取目录条目失败: {}", path.display()))?
{
let host_root_str = host_root_str.to_string();
// 为每个条目创建异步任务,并行获取元数据
let task = tokio::task::spawn(async move {
// 获取文件元数据
@ -550,10 +551,17 @@ async fn list_dir(path: &PathBuf) -> anyhow::Result<Vec<DirList>> {
let is_dir = metadata.is_dir();
let name = entry.file_name().to_string_lossy().to_string();
let path = entry
.path()
.to_string_lossy()
.strip_prefix(&host_root_str)
.ok_or(anyhow!("strip prefix failed"))?
.to_string();
let path = format!("./{path}");
// 创建并返回目录条目信息
let dir = DirList {
name,
path: entry.path(),
path,
is_dir,
size,
last_modified,