create a http server and read the request body as json in rust

Below is an example code snippet to create a HTTP server in Rust using the Hyper crate and parse the request body as JSON.

main.rs
use std::collections::HashMap;
use hyper::{Body, Response, Server, Request};
use hyper::rt::Future;
use hyper::service::service_fn_ok;
use serde::{Deserialize};

#[derive(Deserialize, Debug)]
struct RequestBody {
    name: String,
    age: u8,
}

fn main() {
    // set server address
    let addr = "127.0.0.1:8080".parse().unwrap();

    // create server instance
    let server = Server::bind(&addr)
        .serve(|| service_fn_ok(handle_request))
        .map_err(|e| eprintln!("server error: {}", e));

    println!("Listening on http://{}", addr);

    // start server with HTTP request handler
    hyper::rt::run(server);
}

// HTTP request handler function
fn handle_request(req: Request<Body>) -> Response<Body> {
    // read body as bytes
    let whole_body = req.into_body()
        .concat2()
        .and_then(|chunk| {
            let whole_chunk: Vec<u8> = chunk.into_iter().collect();
            Ok(whole_chunk)
        });

    // convert bytes to String and deserialize JSON
    let resp = whole_body.and_then(|body_bytes| {
        let body_string = String::from_utf8(body_bytes.to_vec())
            .expect("error parsing request body to string");
        let request_body: RequestBody = serde_json::from_str(&body_string)
            .expect("error parsing request body as JSON");
        Ok(Response::new(Body::from(format!("Hello, {:?}", request_body))))
    });

    Response::new(Body::from("Server Error"))
}
1438 chars
49 lines

In this example, we create a RequestBody struct, which represents the expected JSON format for the request body. This struct has two fields: name (a String) and age (a u8).

We then define the handle_request() function, which will be called for every incoming request. Inside this function, we read the request body as bytes using the into_body() function of the Request object. Once we have the bytes of the whole request body, we convert these bytes to a String and deserialize the JSON string into a RequestBody struct using the serde_json::from_str() function. Finally, we construct a Response object and return it.

We use the hyper::rt::run() function to start the server with the handle_request() function as the request handler. The server listens for incoming requests at 127.0.0.1:8080.

Note that this is a simple example, and you may need to adapt the code depending on your specific use case.

gistlibby LogSnag