如何使用 Rocket 定义可选子路径?
How can I define an optional subpath with Rocket?
我正在尝试在 Rocket 服务路径下(在 /admin
下)打包 Vue 应用程序。我写了以下匹配器:
#[get("/admin/<path..>")]
fn admin_panel(_admin: AdminUser, path: Option<PathBuf>) -> Option<NamedFile> {
match path {
Some(admin_path) => match NamedFile::open(Path::new("admin/").join(admin_path)).ok() {
Some(admin_file) => Some(admin_file),
// if the file is not found, we fallback onto admin/index.html, so the client routing can kick in
None => NamedFile::open(Path::new("admin/index.html")).ok()
},
None => NamedFile::open(Path::new("admin/index.html")).ok()
}
}
#[get("/admin/<_path..>", rank = 2)]
fn admin_panel_user(_user: AuthenticatedUser, _path: Option<PathBuf>) -> &'static str {
"Sorry, you must be an administrator to access this page."
}
#[get("/admin/<_path..>", rank = 3)]
fn admin_panel_redirect(_path: Option<PathBuf>) -> Redirect {
Redirect::to(uri!(login::login))
}
然而,有了这个,当我尝试访问 /admin
时,我得到了 404。我需要创建一个只有“/admin”的新路由并重定向到 /admin/index.html
,但是这个不理想。
我认为将 PathBuf
定义为 Option
会使它成为可选的,但它似乎不起作用。
当请求既有路径又没有路径时,如何使请求匹配器工作?
这是 Rocket 尚不支持的功能。已经讨论了添加它的可能性 in this PR on Github 以与我预期的方式类似的方式工作。
目前,解决方案是执行类似已发布示例的操作:
#[get("/")]
fn index() -> String {
everything(None)
}
#[get("/<path..>")]
fn everything(path: Option<PathBuf>) -> String {
format!("{:?}", path)
}
我正在尝试在 Rocket 服务路径下(在 /admin
下)打包 Vue 应用程序。我写了以下匹配器:
#[get("/admin/<path..>")]
fn admin_panel(_admin: AdminUser, path: Option<PathBuf>) -> Option<NamedFile> {
match path {
Some(admin_path) => match NamedFile::open(Path::new("admin/").join(admin_path)).ok() {
Some(admin_file) => Some(admin_file),
// if the file is not found, we fallback onto admin/index.html, so the client routing can kick in
None => NamedFile::open(Path::new("admin/index.html")).ok()
},
None => NamedFile::open(Path::new("admin/index.html")).ok()
}
}
#[get("/admin/<_path..>", rank = 2)]
fn admin_panel_user(_user: AuthenticatedUser, _path: Option<PathBuf>) -> &'static str {
"Sorry, you must be an administrator to access this page."
}
#[get("/admin/<_path..>", rank = 3)]
fn admin_panel_redirect(_path: Option<PathBuf>) -> Redirect {
Redirect::to(uri!(login::login))
}
然而,有了这个,当我尝试访问 /admin
时,我得到了 404。我需要创建一个只有“/admin”的新路由并重定向到 /admin/index.html
,但是这个不理想。
我认为将 PathBuf
定义为 Option
会使它成为可选的,但它似乎不起作用。
当请求既有路径又没有路径时,如何使请求匹配器工作?
这是 Rocket 尚不支持的功能。已经讨论了添加它的可能性 in this PR on Github 以与我预期的方式类似的方式工作。
目前,解决方案是执行类似已发布示例的操作:
#[get("/")]
fn index() -> String {
everything(None)
}
#[get("/<path..>")]
fn everything(path: Option<PathBuf>) -> String {
format!("{:?}", path)
}