【发布时间】:2015-09-20 05:57:06
【问题描述】:
我正在探索Iron web framework for Rust 并创建了一个小型处理程序,它将读取从请求 URL 派生的图像,调整其大小,然后传递结果。据我所知,Iron Response 可以由多种不同类型构建,包括实现Read trait 的类型。
image crate 中的save function 采用实现Write trait 的类型。
感觉这两个函数应该能够连接起来,这样作者就可以写入一个缓冲区,读者可以从中读取。我找到了pipe crate,它似乎实现了这种行为,但我无法将管道的Read 末端变成 Iron 可以接受的东西。
我的函数的一个稍微简化的版本:
fn artwork(req: &mut Request) -> IronResult<Response> {
let mut filepath = PathBuf::from("artwork/sample.png");
let img = match image::open(&filepath) {
Ok(img) => img,
Err(e) => return Err(IronError::new(e, status::InternalServerError))
};
let (mut read, mut write) = pipe::pipe();
thread::spawn(move || {
let thumb = img.resize(128, 128, image::FilterType::Triangle);
thumb.save(&mut write, image::JPEG).unwrap();
});
let mut res = Response::new();
res.status = Some(iron::status::Ok);
res.body = Some(Box::new(read));
Ok(res)
}
我收到的错误:
src/main.rs:70:21: 70:35 error: the trait `iron::response::WriteBody` is not implemented for the type `pipe::PipeReader` [E0277]
src/main.rs:70 res.body = Some(Box::new(read));
^~~~~~~~~~~~~~
PipeReader 实现 Read 和 WriteBody 是为 Read 实现的,所以我觉得这应该可行。我也试过了:
let reader: Box<Read> = Box::new(read);
let mut res = Response::new();
res.status = Some(iron::status::Ok);
res.body = Some(reader);
但这给出了错误:
src/main.rs:72:21: 72:27 error: mismatched types:
expected `Box<iron::response::WriteBody + Send>`,
found `Box<std::io::Read>`
(expected trait `iron::response::WriteBody`,
found trait `std::io::Read`) [E0308]
src/main.rs:72 res.body = Some(reader);
^~~~~~
如何将save 函数连接到 Iron 响应主体?
【问题讨论】: