我正在使用 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/