【问题标题】:How to serve a fallback file using Iron's staticfile when the original file is not found?找不到原始文件时,如何使用 Iron 的静态文件提供后备文件?
【发布时间】:2017-09-27 18:38:58
【问题描述】:

我正在使用 Iron 为 React 站点提供服务。如果文件或目录不存在,我试图让它为 index.html 提供服务。

fn staticHandler(req: &mut Request) -> IronResult<Response> {
    let url = Url::parse("http://localhost:1393").unwrap();
    let getFile_result = Static::handle(&Static::new(Path::new("../html")), req);

    match getFile_result {
        Ok(_) => getFile_result,
        Err(err) => {
            Static::handle(
                // returns 404 error - ../html/index.html returns 500
                &Static::new(Path::new("localhost:1393/index.html")),
                req,
            )
        }
    }
}

如果我去 localhost:1393 我会得到我的索引页面 如果我去 localhost:1393/not-a-directory 我只是得到一个错误。

有没有办法重定向(不更改网址)或其他解决方案?

这不是How to change Iron's default 404 behaviour? 的重复,因为我试图在用户请求的静态资产不存在时进行处理,而不是在未定义路由时进行处理。

【问题讨论】:

标签: rust static-files iron


【解决方案1】:

正如staticfile issue #78 titled "Static with fallback" 所讨论的,您可以包装处理程序,检查 404,然后提供文件:

struct Fallback;

impl AroundMiddleware for Fallback {
    fn around(self, handler: Box<Handler>) -> Box<Handler> {
        Box::new(FallbackHandler(handler))
    }
}

struct FallbackHandler(Box<Handler>);

impl Handler for FallbackHandler {
    fn handle(&self, req: &mut Request) -> IronResult<Response> {
        let resp = self.0.handle(req);

        match resp {
            Err(err) => {
                match err.response.status {
                    Some(status::NotFound) => {
                        let file = File::open("/tmp/example").unwrap();
                        Ok(Response::with((status::Ok, file)))
                    }
                    _ => Err(err),
                }
            }
            other => other
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
  • 2017-05-24
  • 2018-09-21
  • 2016-11-13
  • 2014-01-12
  • 2013-06-10
  • 1970-01-01
相关资源
最近更新 更多