Now support Result responses.

Experimented with the new impl specialization features of Rust. They work! But
they're not quite there yet. Specifically, I was able to specialize on
`Responder`, but when trying to remove the macro in `FromParam`, it didn't work.
See https://github.com/rust-lang/rust/issues/31844.
This commit is contained in:
Sergio Benitez 2016-03-22 17:16:17 -07:00
parent 1e9c0789f6
commit cddc92f870
2 changed files with 28 additions and 2 deletions

View File

@ -5,6 +5,7 @@ extern crate rocket;
use rocket::Rocket; use rocket::Rocket;
use std::fs::File; use std::fs::File;
use std::io::Error as IOError;
#[route(GET, path = "/")] #[route(GET, path = "/")]
fn index() -> File { fn index() -> File {
@ -12,8 +13,8 @@ fn index() -> File {
} }
#[route(GET, path = "/<file>")] #[route(GET, path = "/<file>")]
fn files(file: &str) -> File { fn files(file: &str) -> Result<File, IOError> {
File::open(format!("static/{}", file)).unwrap() File::open(format!("static/{}", file))
} }
fn main() { fn main() {

View File

@ -5,6 +5,7 @@ use hyper::status::StatusCode;
use hyper::header; use hyper::header;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::fs::File; use std::fs::File;
use std::fmt;
pub struct Response<'a> { pub struct Response<'a> {
pub body: Box<Responder + 'a> pub body: Box<Responder + 'a>
@ -89,6 +90,30 @@ impl Responder for File {
} }
} }
// Waiting for RFC #1210: impl specialization. It's not quite stable yet.
// impl<T: Responder, E: fmt::Display + fmt::Debug> Responder for Result<T, E> {
// fn respond<'b>(&mut self, res: HypResponse<'b, HypFresh>) {
// if self.is_err() {
// println!("Response error: {}", self.as_ref().err().unwrap());
// return;
// }
// self.as_mut().unwrap().respond(res);
// }
// }
impl<T: Responder, E: fmt::Debug> Responder for Result<T, E> {
// prepend with `default` when using impl specialization
fn respond<'b>(&mut self, res: HypResponse<'b, HypFresh>) {
if self.is_err() {
println!("Error: {:?}", self.as_ref().err().unwrap());
return;
}
self.as_mut().unwrap().respond(res);
}
}
// TODO: Allow streamed responses. // TODO: Allow streamed responses.
// const CHUNK_SIZE: u32 = 4096; // const CHUNK_SIZE: u32 = 4096;
// pub struct Stream<T: Read>(T); // pub struct Stream<T: Read>(T);