I have some working code with hyper 0.14 that looks roughly like this – very simplified code but basically I need the sender end of this channel to be able to data into the body:
let (sender, body) = Body::channel();
let request = Request::builder()
.method(Method::POST)
.uri("http://localhost:3000/")
.header("content-type", "text")
.body(body)
.unwrap();
let client = Client::new();
let response = client.request(request);
tokio::spawn(async move {
let mut sender = sender;
println!(
"Body: {:?}",
sender.send_data(hyper::body::Bytes::from("test\n")).await
);
println!(
"Body: {:?}",
sender.send_data(hyper::body::Bytes::from("test2\n")).await
);
});
println!("{:?}", response.await);
I am trying to upgrade the code to hyper 1.0 and not quite sure how to do the equivalent – I'm attempting to create an mpsc channel. The code below is not working but I'm not even sure if I'm on the correct track of trying to use StreamBody
with ReceiverStream
let (tx, rx) = mpsc::channel::<Frame<Bytes>>(100);
let stream: ReceiverStream<hyper::body::Frame<bytes::Bytes>> = ReceiverStream::new(rx);
let body: StreamBody<ReceiverStream<hyper::body::Frame<bytes::Bytes>>> =
StreamBody::new(stream);
let boxed_body = body.boxed(); //compile errors here
let request = Request::builder()
.method(Method::POST)
.uri("http://localhost/test")
.body(boxed_body)
.unwrap();
let response = client.request(request);
tokio::spawn(async move {
let mut sender = sender;
println!(
"Body: {:?}",
sender.send(Frame::data(Bytes::from("test\n"))).await
);
println!(
"Body: {:?}",
sender.send(Frame::data(Bytes::from("test2\n"))).await
);
});
println!("{:?}", response.await);
I found that by referring to the official example, this code can be compiled.
Refer to hyper official example
//change channel Item type to MyResult<Bytes>
type MyResult<T> = std::result::Result<T,std::io::Error>;
let (mut tx, rx) = mpsc::channel::<MyResult<Bytes>>(100);
//convert to match BoxBody
let stream_body = StreamBody::new(stream.map_ok(Frame::data));
let boxed_body = stream_body.boxed();