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

main.rs
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct RequestBody {
    message: String,
}

#[derive(Serialize)]
struct ResponseBody {
    status: String,
    message: String,
}

async fn index(info: web::Json<RequestBody>) -> impl Responder {
    let response_body = ResponseBody {
        status: "success".to_string(),
        message: format!("Received message: {}", info.message),
    };
    HttpResponse::Ok().json(response_body)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::post().to(index))
    })
    .bind("localhost:8080")?
    .run()
    .await
}
738 chars
33 lines

In the above code snippet, a HttpServer is created using the actix-web crate. A route is created for the root path ("/") which accepts only HTTP POST method. The incoming JSON request is deserialized using serde and stored in a struct called RequestBody. A JSON response is then sent back with the message received in the request body.

gistlibby LogSnag