Skip to content

Commit d5558b6

Browse files
committed
feat(server): add Response.send to write a sized body
Closes #446
1 parent d294ea5 commit d5558b6

File tree

3 files changed

+20
-13
lines changed

3 files changed

+20
-13
lines changed

examples/hello.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,12 @@
22
extern crate hyper;
33
extern crate env_logger;
44

5-
use std::io::Write;
65
use hyper::server::{Request, Response};
76

87
static PHRASE: &'static [u8] = b"Hello World!";
98

109
fn hello(_: Request, res: Response) {
11-
let mut res = res.start().unwrap();
12-
res.write_all(PHRASE).unwrap();
13-
res.end().unwrap();
10+
res.send(PHRASE).unwrap();
1411
}
1512

1613
fn main() {

examples/server.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@
22
extern crate hyper;
33
extern crate env_logger;
44

5-
use std::io::{Write, copy};
5+
use std::io::copy;
66

77
use hyper::{Get, Post};
8-
use hyper::header::ContentLength;
98
use hyper::server::{Server, Request, Response};
109
use hyper::uri::RequestUri::AbsolutePath;
1110

@@ -22,11 +21,7 @@ fn echo(mut req: Request, mut res: Response) {
2221
match req.uri {
2322
AbsolutePath(ref path) => match (&req.method, &path[..]) {
2423
(&Get, "/") | (&Get, "/echo") => {
25-
let out = b"Try POST /echo";
26-
27-
res.headers_mut().set(ContentLength(out.len() as u64));
28-
let mut res = try_return!(res.start());
29-
try_return!(res.write_all(out));
24+
try_return!(res.send(b"Try POST /echo"));
3025
return;
3126
},
3227
(&Post, "/echo") => (), // fall through, fighting mutable borrows

src/server/response.rs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,6 @@ impl<'a, W: Any> Response<'a, W> {
109109

110110
Ok(body_type)
111111
}
112-
113-
114112
}
115113

116114
impl<'a> Response<'a, Fresh> {
@@ -126,6 +124,23 @@ impl<'a> Response<'a, Fresh> {
126124
}
127125
}
128126

127+
/// Writes the body and ends the response.
128+
///
129+
/// # Example
130+
///
131+
/// ```
132+
/// # use hyper::server::Response;
133+
/// fn handler(res: Response) {
134+
/// res.send(b"Hello World!").unwrap();
135+
/// }
136+
/// ```
137+
pub fn send(mut self, body: &[u8]) -> io::Result<()> {
138+
self.headers.set(header::ContentLength(body.len() as u64));
139+
let mut stream = try!(self.start());
140+
try!(stream.write_all(body));
141+
stream.end()
142+
}
143+
129144
/// Consume this Response<Fresh>, writing the Headers and Status and creating a Response<Streaming>
130145
pub fn start(mut self) -> io::Result<Response<'a, Streaming>> {
131146
let body_type = try!(self.write_head());

0 commit comments

Comments
 (0)