rust - 找不到原始文件时如何使用 Iron 的静态文件提供后备文件?

标签 rust static-files iron

我正在使用 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,我只会得到一个错误。

是否有重定向(不更改 url)或其他解决方案的方法?

这不是 How to change Iron's default 404 behaviour? 的副本因为我正在尝试处理用户请求的静态 Assets 不存在的情况,而不是未定义路由的情况。

最佳答案

正如在 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
        }
    }
}

关于rust - 找不到原始文件时如何使用 Iron 的静态文件提供后备文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46455009/

相关文章:

json - 如何获取服务器从reqwest http调用发送回的数据?

java - 如何在 java Google App Engine 中将内容处置设置为内联静态文件

function - 无法在有关 iron lib 的 fn 项目中捕获动态环境

rust - 如何在 Iron 中生成指向特定路线的链接?

rust - 如何在 Iron 的 AfterMiddleware 中添加 header ?

rust - 是否可以实现采用格式字符串的方法?

rust - 如何通过使用 reqwest 传递 secret 来添加基本授权 header ?

kotlin - Ktor 无法正确提供静态图像

python - 在 Tornado 中禁用静态文件缓存

rust - 如何使用 structopt 将特殊字符作为字符串参数传递?