Skip to content

Commit cddc92f

Browse files
author
Sergio Benitez
committed
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 rust-lang/rust#31844.
1 parent 1e9c078 commit cddc92f

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

examples/static_files/src/main.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@ extern crate rocket;
55

66
use rocket::Rocket;
77
use std::fs::File;
8+
use std::io::Error as IOError;
89

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

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

1920
fn main() {

lib/src/response.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use hyper::status::StatusCode;
55
use hyper::header;
66
use std::io::{Read, Write};
77
use std::fs::File;
8+
use std::fmt;
89

910
pub struct Response<'a> {
1011
pub body: Box<Responder + 'a>
@@ -89,6 +90,30 @@ impl Responder for File {
8990
}
9091
}
9192

93+
// Waiting for RFC #1210: impl specialization. It's not quite stable yet.
94+
// impl<T: Responder, E: fmt::Display + fmt::Debug> Responder for Result<T, E> {
95+
// fn respond<'b>(&mut self, res: HypResponse<'b, HypFresh>) {
96+
// if self.is_err() {
97+
// println!("Response error: {}", self.as_ref().err().unwrap());
98+
// return;
99+
// }
100+
101+
// self.as_mut().unwrap().respond(res);
102+
// }
103+
// }
104+
105+
impl<T: Responder, E: fmt::Debug> Responder for Result<T, E> {
106+
// prepend with `default` when using impl specialization
107+
fn respond<'b>(&mut self, res: HypResponse<'b, HypFresh>) {
108+
if self.is_err() {
109+
println!("Error: {:?}", self.as_ref().err().unwrap());
110+
return;
111+
}
112+
113+
self.as_mut().unwrap().respond(res);
114+
}
115+
}
116+
92117
// TODO: Allow streamed responses.
93118
// const CHUNK_SIZE: u32 = 4096;
94119
// pub struct Stream<T: Read>(T);

0 commit comments

Comments
 (0)