pub fn streaming_body<T>(req: &Request<T>) -> StreamingBodyBuilderExpand description
Creates a response and streaming body writer for the given request.
The streaming body writer is currently Some(writer) for GET requests and
None for HEAD requests. In the future, streaming_body may also support
conditional GET requests.
use std::io::Write as _;
fn respond(req: Request<hyper::Body>) -> std::io::Result<Response<hyper::Body>> {
let (mut resp, stream) = http_serve::streaming_body(&req).build();
if let Some(mut w) = stream {
write!(&mut w, "hello world")?;
}
resp.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
Ok(resp)
}The caller may also continue appending to stream after returning the response to hyper.
The response will end when stream is dropped. The only disadvantage to writing to the stream
after the fact is that there’s no way to report mid-response errors other than abruptly closing
the TCP connection (BodyWriter::abort).
use std::io::Write as _;
fn respond(req: Request<hyper::Body>) -> std::io::Result<Response<hyper::Body>> {
let (mut resp, stream) = http_serve::streaming_body(&req).build();
if let Some(mut w) = stream {
tokio::spawn(async move {
for i in 0..10 {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
write!(&mut w, "write {}\n", i)?;
}
Ok::<_, std::io::Error>(())
});
}
resp.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
Ok(resp)
}