Debian Codegraph @

third_party/rust/warp/examples/stream.rs

raw
1 use bytes::Buf;
2 use futures_util::{Stream, StreamExt};
3 use warp::{reply::Response, Filter, Reply};
4
5 #[tokio::main]
6 async fn main() {
7 // Running curl -T /path/to/a/file 'localhost:3030/' should echo back the content of the file,
8 // or an HTTP 413 error if the configured size limit is exceeded.
9 let route = warp::body::content_length_limit(65536)
10 .and(warp::body::stream())
11 .then(handler);
12 warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
13 }
14
15 async fn handler(
16 mut body: impl Stream<Item = Result<impl Buf, warp::Error>> + Unpin + Send + Sync,
17 ) -> Response {
18 let mut collected: Vec<u8> = vec![];
19 while let Some(buf) = body.next().await {
20 let mut buf = buf.unwrap();
21 while buf.remaining() > 0 {
22 let chunk = buf.chunk();
23 let chunk_len = chunk.len();
24 collected.extend_from_slice(chunk);
25 buf.advance(chunk_len);
26 }
27 }
28 println!("Sending {} bytes", collected.len());
29 collected.into_response()
30 }