Add Body::from_stream (#1848)

This commit is contained in:
David Pedersen
2023-04-21 17:45:31 +02:00
parent 4e4c29175f
commit 72c1b7a80c
7 changed files with 79 additions and 29 deletions
+12 -18
View File
@@ -1,5 +1,5 @@
use axum::{
body::{self, Bytes, HttpBody, StreamBody},
body::{Body, Bytes, HttpBody},
http::HeaderMap,
response::{IntoResponse, Response},
Error,
@@ -47,28 +47,25 @@ pin_project! {
#[cfg(feature = "async-read-body")]
#[derive(Debug)]
#[must_use]
pub struct AsyncReadBody<R> {
pub struct AsyncReadBody {
#[pin]
read: StreamBody<ReaderStream<R>>,
body: Body,
}
}
impl<R> AsyncReadBody<R> {
impl AsyncReadBody {
/// Create a new `AsyncReadBody`.
pub fn new(read: R) -> Self
pub fn new<R>(read: R) -> Self
where
R: AsyncRead + Send + 'static,
{
Self {
read: StreamBody::new(ReaderStream::new(read)),
body: Body::from_stream(ReaderStream::new(read)),
}
}
}
impl<R> HttpBody for AsyncReadBody<R>
where
R: AsyncRead + Send + 'static,
{
impl HttpBody for AsyncReadBody {
type Data = Bytes;
type Error = Error;
@@ -76,22 +73,19 @@ where
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
self.project().read.poll_data(cx)
self.project().body.poll_data(cx)
}
fn poll_trailers(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
cx: &mut Context<'_>,
) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
Poll::Ready(Ok(None))
self.project().body.poll_trailers(cx)
}
}
impl<R> IntoResponse for AsyncReadBody<R>
where
R: AsyncRead + Send + 'static,
{
impl IntoResponse for AsyncReadBody {
fn into_response(self) -> Response {
Response::new(body::boxed(self))
self.body.into_response()
}
}
+2 -4
View File
@@ -7,7 +7,7 @@ use axum::{
body::{Body, Bytes},
extract::FromRequest,
response::{IntoResponse, Response},
BoxError, RequestExt,
RequestExt,
};
use futures_util::stream::Stream;
use http::{
@@ -410,9 +410,7 @@ impl std::error::Error for InvalidBoundary {}
mod tests {
use super::*;
use crate::test_helpers::*;
use axum::{
body::Body, extract::DefaultBodyLimit, response::IntoResponse, routing::post, Router,
};
use axum::{extract::DefaultBodyLimit, response::IntoResponse, routing::post, Router};
#[tokio::test]
async fn content_type_with_encoding() {
+2 -2
View File
@@ -2,7 +2,7 @@
use axum::{
async_trait,
body::{Body, StreamBody},
body::Body,
extract::FromRequest,
response::{IntoResponse, Response},
BoxError,
@@ -166,7 +166,7 @@ where
buf.write_all(b"\n")?;
Ok::<_, BoxError>(buf.into_inner().freeze())
});
let stream = StreamBody::new(stream);
let stream = Body::from_stream(stream);
// there is no consensus around mime type yet
// https://github.com/wardi/jsonlines/issues/36