Skip to content

Commit f9044a3

Browse files
committed
feat(webapi): 改进静态文件目录查找逻辑
- 添加 find_static_directory 函数以支持多种方式定位 static 目录 - 优先从可执行文件所在目录查找静态文件 - 支持从当前工作目录及子目录查找静态文件 - 移除原有的简单路径检查逻辑- 提供更详细的错误信息以便调试 - 增强程序在不同运行环境下的兼容性
1 parent 03bc7cb commit f9044a3

1 file changed

Lines changed: 38 additions & 9 deletions

File tree

file_classification_webapi/src/bin/file_classification_webapi.rs

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,9 @@ async fn main() -> std::io::Result<()> {
2323

2424
let pool = establish_connection_pool();
2525

26-
// 获取可执行文件的目录
27-
let current_dir = std::env::current_dir()?;
28-
let static_dir = current_dir.join("static");
29-
30-
// 检查 static 目录是否存在
31-
if !Path::new(&static_dir).exists() {
32-
eprintln!("静态文件目录不存在: {:?}", static_dir);
33-
return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "静态文件目录不存在"));
34-
}
26+
// 尝试多种方式定位 static 目录
27+
let static_dir = find_static_directory()?;
28+
println!("使用静态文件目录: {:?}", static_dir);
3529

3630
// 在HttpServer::new中添加新的路由
3731
HttpServer::new(move || {
@@ -101,4 +95,39 @@ async fn main() -> std::io::Result<()> {
10195
.bind("127.0.0.1:8082")?
10296
.run()
10397
.await
98+
}
99+
100+
/// 查找静态文件目录,支持从不同目录运行程序
101+
fn find_static_directory() -> std::io::Result<std::path::PathBuf> {
102+
// 首先尝试从可执行文件所在目录查找
103+
if let Ok(exe_path) = std::env::current_exe() {
104+
if let Some(exe_dir) = exe_path.parent() {
105+
let static_dir = exe_dir.join("static");
106+
if Path::new(&static_dir).exists() {
107+
return Ok(static_dir);
108+
}
109+
}
110+
}
111+
112+
// 然后尝试从当前工作目录查找
113+
if let Ok(current_dir) = std::env::current_dir() {
114+
let static_dir = current_dir.join("static");
115+
if Path::new(&static_dir).exists() {
116+
return Ok(static_dir);
117+
}
118+
119+
// 尝试从当前工作目录的子目录 file_classification_webapi 中查找
120+
let static_dir = current_dir.join("file_classification_webapi").join("static");
121+
if Path::new(&static_dir).exists() {
122+
return Ok(static_dir);
123+
}
124+
}
125+
126+
// 如果都没找到,则返回默认路径并让后续逻辑处理错误
127+
if let Ok(current_dir) = std::env::current_dir() {
128+
let static_dir = current_dir.join("static");
129+
Err(std::io::Error::new(std::io::ErrorKind::NotFound, format!("静态文件目录不存在: {:?}", static_dir)))
130+
} else {
131+
Err(std::io::Error::new(std::io::ErrorKind::NotFound, "无法确定静态文件目录位置"))
132+
}
104133
}

0 commit comments

Comments
 (0)