rustserdehyper

Return a hyper::Body of serde:Value


In my situation, my function can only have signature:

pub async fn do_something(mut req: Request<Body>) -> Result<Response<Body>, CustomError> {
  .....
}

I know how to return a body of string in my function as follow:

Ok(Response::new(Body::from("some string".to_string())))

However, something like this does not work with serde::Value; it only worked with strings.

What is the proper way to return a serde::Value while maintaining the same method signature?


Solution

  • You can serialize into BytesMut from the bytes crate, then convert into into Body:

    use bytes::{BufMut, BytesMut};
    
    let mut buf = BytesMut::new().writer();
    serde_json::to_writer(&mut buf, &value)
        .expect("serialization of `serde_json::Value` into `BytesMut` cannot fail");
    Ok(Response::new(Body::from(buf.into_inner().freeze())))
    

    If you can afford something less performant, you can serialize into Vec:

    Ok(Response::new(Body::from(
        serde_json::to_vec(&value).expect("serialization of `serde_json::Value` into `Vec` cannot fail"),
    )))