From cddc92f870e07bbdb377c95aee9a3685eecf2d74 Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Tue, 22 Mar 2016 17:16:17 -0700 Subject: [PATCH] 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. --- examples/static_files/src/main.rs | 5 +++-- lib/src/response.rs | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/examples/static_files/src/main.rs b/examples/static_files/src/main.rs index 3a55d065..9a5fae68 100644 --- a/examples/static_files/src/main.rs +++ b/examples/static_files/src/main.rs @@ -5,6 +5,7 @@ extern crate rocket; use rocket::Rocket; use std::fs::File; +use std::io::Error as IOError; #[route(GET, path = "/")] fn index() -> File { @@ -12,8 +13,8 @@ fn index() -> File { } #[route(GET, path = "/")] -fn files(file: &str) -> File { - File::open(format!("static/{}", file)).unwrap() +fn files(file: &str) -> Result { + File::open(format!("static/{}", file)) } fn main() { diff --git a/lib/src/response.rs b/lib/src/response.rs index d38a15c7..dc9c31dd 100644 --- a/lib/src/response.rs +++ b/lib/src/response.rs @@ -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 @@ -89,6 +90,30 @@ impl Responder for File { } } +// Waiting for RFC #1210: impl specialization. It's not quite stable yet. +// impl Responder for Result { +// 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 Responder for Result { + // 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);