1

我正在创建一个投资组合网站,一些项目有静态 HTML 演示,我想根据 URL 中的 ID 提供这些演示。路线如下所示:

#[get("/demo/<id>/<pathbuf..>")]
fn site_demo(id: usize, pathbuf: Option<PathBuf>) -> Option<NamedFile> {
    // set path according to id
    let demo = format!{"static/projects/{:03}/demo/", id};
    // if `pathbuf` is not provided, set file to `index.html`
    let pathbuf = pathbuf.unwrap_or(PathBuf::from("index.html"));

    let path = Path::new(&demo).join(pathbuf);
    NamedFile::open(path).ok()
}

当我localhost:5050/demo/003/index.html在浏览器中输入时,演示(以及演示文件夹中的所有其他内容)都会被加载。但是,一旦我输入,localhost:5050/demo/003/我就会得到这个错误(同样/的结果,最后没有):

GET /demo/003/ text/html:
    => Error: No matching routes for GET /demo/003/ text/html.
    => Warning: Responding with 404 Not Found catcher.
    => Response succeeded.

我希望路由匹配,因为它PathBuf是可选的并且设置为index.html. 对我有意义...

我在某个地方出错了还是应该打开一个问题?

4

1 回答 1

0

A multiple segments path cannot be empty.

A different approach is to use 2 routes :

  • one for the multiple segment /demo/<id>/<pathbuf..>
  • one for the empty segment /demo/<id> that redirect to /demo/<id>/index.html

A sample using rust nightly and rocket 0.4 :

#![feature(proc_macro_hygiene, decl_macro)]  
#[macro_use] extern crate rocket;

use std::path::{Path,PathBuf};
use rocket::response::{Redirect,NamedFile};

#[get("/demo/<id>/<pathbuf..>")]
fn site_demo(id: usize, pathbuf: PathBuf) -> Option<NamedFile> {
    let demo = format!{"static/projects/{:03}/demo/", id};
    NamedFile::open(Path::new(&demo).join(pathbuf)).ok()
}

#[get("/demo/<pathbuf..>", rank=2)]
fn redirect(pathbuf: PathBuf) -> Redirect {
    Redirect::to(format!{"/demo/{}/index.html", pathbuf.display()})
}

fn main() {
    rocket::ignite().mount("/", routes![site_demo,redirect]).launch();
}

A sample using rust stable and rocket 0.5 :

#[macro_use] extern crate rocket;

use std::path::{Path,PathBuf};
use rocket::response::{Redirect,NamedFile};

#[get("/demo/<id>/<pathbuf..>")]
async fn site_demo(id: usize, pathbuf: PathBuf) -> Option<NamedFile> {
    let demo = format!{"static/projects/{:03}/demo/", id};
    NamedFile::open(Path::new(&demo).join(pathbuf)).await.ok()
}

#[get("/demo/<pathbuf..>", rank=2)]
fn redirect(pathbuf: PathBuf) -> Redirect {
    Redirect::to(format!{"/demo/{}/index.html", pathbuf.display()})
}

#[launch]
fn rocket() -> rocket::Rocket {
    rocket::ignite().mount("/", routes![site_demo,redirect])
}

Like this localhost:5050/demo/003/ will be redirect to localhost:5050/demo/003/index.html and then localhost:5050/demo/003/index.html will load static/projects/003/demo/index.html

于 2019-08-10T10:26:11.220 回答