Skip to content

Commit f1664c9

Browse files
committed
Switch response from Box<Read> to Box<WriteBody>
This inverts the flow in a way that makes streaming responses far simpler to write. You otherwise have to do an annoying intermediate buffering dance that's a pain.
1 parent 22a6372 commit f1664c9

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/lib.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
extern crate semver;
22

33
use std::io::prelude::*;
4+
use std::io;
45
use std::collections::HashMap;
56
use std::error::Error;
67
use std::net::SocketAddr;
@@ -109,7 +110,7 @@ pub struct Response {
109110
pub headers: HashMap<String, Vec<String>>,
110111

111112
/// A Writer for body of the response
112-
pub body: Box<Read + Send>
113+
pub body: Box<WriteBody + Send>
113114
}
114115

115116
/// A Handler takes a request and returns a response or an error.
@@ -126,3 +127,18 @@ impl<F, E> Handler for F
126127
(*self)(request).map_err(|e| Box::new(e) as Box<Error+Send>)
127128
}
128129
}
130+
131+
/// A trait which writes the response body out to a `Write`r.
132+
///
133+
/// This is implemented for all `Read`ers.
134+
pub trait WriteBody {
135+
fn write_body(&mut self, out: &mut Write) -> io::Result<u64>;
136+
}
137+
138+
impl<R> WriteBody for R
139+
where R: Read
140+
{
141+
fn write_body(&mut self, out: &mut Write) -> io::Result<u64> {
142+
io::copy(self, out)
143+
}
144+
}

0 commit comments

Comments
 (0)