Skip to content

Commit

Permalink
Add example (and doc reference) for warp::body::stream() (#1061)
Browse files Browse the repository at this point in the history
* Add example (and doc reference) for warp::body::stream()

As of right now it didn't look like there was example usage for this functionality. It took me some trial and error to figure out the typing for the Stream so that I could pass it into a handler function like this. This example hopefully avoids similar headaches for others.

* cargo fmt
  • Loading branch information
nickbp authored Aug 6, 2023
1 parent 376c805 commit 149913f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
30 changes: 30 additions & 0 deletions examples/stream.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use bytes::Buf;
use futures_util::{Stream, StreamExt};
use warp::{reply::Response, Filter, Reply};

#[tokio::main]
async fn main() {
// Running curl -T /path/to/a/file 'localhost:3030/' should echo back the content of the file,
// or an HTTP 413 error if the configured size limit is exceeded.
let route = warp::body::content_length_limit(65536)
.and(warp::body::stream())
.then(handler);
warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
}

async fn handler(
mut body: impl Stream<Item = Result<impl Buf, warp::Error>> + Unpin + Send + Sync,
) -> Response {
let mut collected: Vec<u8> = vec![];
while let Some(buf) = body.next().await {
let mut buf = buf.unwrap();
while buf.remaining() > 0 {
let chunk = buf.chunk();
let chunk_len = chunk.len();
collected.extend_from_slice(chunk);
buf.advance(chunk_len);
}
}
println!("Sending {} bytes", collected.len());
collected.into_response()
}
2 changes: 2 additions & 0 deletions src/filters/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ pub fn content_length_limit(limit: u64) -> impl Filter<Extract = (), Error = Rej
/// If other filters have already extracted the body, this filter will reject
/// with a `500 Internal Server Error`.
///
/// For example usage, please take a look at [examples/stream.rs](https://github.com/seanmonstar/warp/blob/master/examples/stream.rs).
///
/// # Warning
///
/// This does not have a default size limit, it would be wise to use one to
Expand Down

0 comments on commit 149913f

Please sign in to comment.