Skip to content

Commit

Permalink
Now support Result responses.
Browse files Browse the repository at this point in the history
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 rust-lang/rust#31844.
  • Loading branch information
Sergio Benitez committed Mar 23, 2016
1 parent 1e9c078 commit cddc92f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
5 changes: 3 additions & 2 deletions examples/static_files/src/main.rs
Expand Up @@ -5,15 +5,16 @@ extern crate rocket;

use rocket::Rocket;
use std::fs::File;
use std::io::Error as IOError;

#[route(GET, path = "/")]
fn index() -> File {
File::open("static/index.html").unwrap()
}

#[route(GET, path = "/<file>")]
fn files(file: &str) -> File {
File::open(format!("static/{}", file)).unwrap()
fn files(file: &str) -> Result<File, IOError> {
File::open(format!("static/{}", file))
}

fn main() {
Expand Down
25 changes: 25 additions & 0 deletions lib/src/response.rs
Expand Up @@ -5,6 +5,7 @@ use hyper::status::StatusCode;
use hyper::header;
use std::io::{Read, Write};
use std::fs::File;
use std::fmt;

pub struct Response<'a> {
pub body: Box<Responder + 'a>
Expand Down Expand Up @@ -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.
// const CHUNK_SIZE: u32 = 4096;
// pub struct Stream<T: Read>(T);
Expand Down

0 comments on commit cddc92f

Please sign in to comment.