0

I've managed to extract data from a POST method in hyper using the following:

use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server};
use std::convert::Infallible;
use std::net::SocketAddr;
use tokio;

async fn handle(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    match (_req.method(), _req.uri().path()) {
        (&Method::GET, "/") => Ok(Response::new(Body::from("this is a get"))),

        (&Method::POST, "/") => {
            let byte_stream = hyper::body::to_bytes(_req).await?;
            let _params = form_urlencoded::parse(&byte_stream)
                .into_owned()
                .collect::<HashMap<String, String>>();

However, the whole JSON body is just one key in the HashMap now. How do I split it up so I have a hashmap with multiple keys and values as opposed to one key that's the entire body?

[dependencies]
futures = "0.1"
hyper = "0.13"
pretty_env_logger = "0.3.1"
url = "2.1.1"
tokio = { version = "0.2", features = ["macros", "tcp"] }
bytes = "0.5"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
max89
  • 443
  • 5
  • 18
  • Please write a [reprex]. Your code does not compile, so a potential answerer cannot easily see the same problem that you are facing: the function just stops in the middle and there are missing imports (`form_urlencoded` I _guess_ comes from the `url` crate?). – Peter Hall Mar 24 '20 at 10:58

1 Answers1

2

There is a discrepancy between your description:

However, the whole JSON body

And your code:

let _params = form_urlencoded::parse(&byte_stream)

If your data is JSON then parse it as JSON, using the serde_json crate:

let _params: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Peter Hall
  • 53,120
  • 14
  • 139
  • 204