0

I'm reading the examples of actix-web, but as I am quite new to Rust I am having some issues understanding how to adapt the code to my needs.

Given an actix-web HttpRequest, I want to parse the payload and return a JsonValue. I can't figure out how to change this function to return the JsonValue rather than a HttpResponse.

fn index_mjsonrust(req: &HttpRequest, ) -> Box<Future<Item = HttpResponse, Error = Error>> {
    req.payload()
        .concat2()
        .from_err()
        .and_then(|body| {
            // body is loaded, now we can deserialize json-rust
            let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
            let injson: JsonValue = match result {
                Ok(v) => v,
                Err(e) => object!{"err" => e.to_string() },
            };
            Ok(HttpResponse::Ok()
                .content_type("application/json")
                .body(injson.dump()))
        })
        .responder()
}

Would it be better to just return the JsonValue rather than a Future?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Simen Russnes
  • 2,002
  • 2
  • 26
  • 56
  • 2
    Please review how to create a [MCVE] and then [edit] your question to include it. We cannot tell what crates (and versions), types, traits, fields, etc. are present in the code. Showing all the imported types is important. Questions seeking debugging help must include **a specific error** and the **shortest code necessary to reproduce it**. Try to produce something that reproduces your error on the [Rust Playground](https://play.rust-lang.org) or you can reproduce it in a brand new Cargo project. There are [Rust-specific MCVE tips](//stackoverflow.com/tags/rust/info) as well. – Shepmaster Sep 15 '18 at 17:18

1 Answers1

2

You have to convert JsonValue to a string or bytes, then you can set it as the HttpResponse body. You can not directly return a JsonValue instead of box because the request body reading process is asynchronous.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Nikolay Kim
  • 144
  • 1