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" 
1
  • Please write a minimal reproducible example. 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?). Commented Mar 24, 2020 at 10:58

1 Answer 1

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.