我目前正在使用 Axum 框架从头开始实现一个 Web 服务。此服务的目标是访问和读/写目标目录上的文件或目录。
我想要实现的是以下路线:
PUT https://<domain>/<directory>/?some_query=value
PUT https://<domain>/<directory>/<file>?some_other_query=value
基本上,如果路由以“/”结尾,则它是一个目录,否则是一个文件。
我从阅读他们的文档中了解到的是,他们的路线通配符不支持这样的东西,例如我定义了以下路由器:
Router::new()
.route("/*path", get(my_get_handler))
.route("/*path", put(my_put_handler)));
例如:
/dir/sub/sub2/file.txt -> Should be a file
/dir/sub/sub2/sub3/ -> Should be a dir
/dir/sub/sub2/something -> Should be a file
我认为可能的是这样的:
Router::new().route("/*path/*file", put(handler));
如何使用 axum 框架来实现这一点?
您所拥有的一切都可以正常工作,使用 wildcard 模式时会保留完整路径:
.route("/*path", get(file_handler))
use axum::extract::Path;
use axum::response::IntoResponse;
async fn file_handler(Path(path): Path<String>) -> impl IntoResponse {
println!("{path}");
}
GET /dir/sub/sub2/file.txt
将打印 dir/sub/sub2/file.txt
GET /dir/sub/sub2/sub3/
将打印 dir/sub/sub2/sub3/
GET /dir/sub/sub2/something
将打印 dir/sub/sub2/something
因此,如何解释该路径完全取决于您。您想要的与标准
Path
和 PathBuf
的解释方式不同,因为尾随的 /
几乎被忽略。但我没有发现简单的 path.ends_with('/')
检查是否需要文件或目录有什么问题。
如果您想根据尾部斜杠的存在路由到不同的处理程序,那么您是对的,
.route()
模式不直接支持这一点。手动处理区别。