I'm building a simple REST server with Actix. I can't seem to figure out how to get the body of the request as text. The request will be arbitrary JSON so I don't want to convert it to a type. I just want to dump the text to disk.
async fn create_process(req: HttpRequest) -> impl Responder {
// how do I get the body here?
}
This is how I am starting the server:
HttpServer::new(|| {
App::new()
.route("/api/1/0/create_process", web::post().to(create_process))
})
.bind("127.0.0.1:8080")?
.run()
.await
You can use the Bytes extractor, which provides the request body as a slice of bytes, and save directly to a file:
use actix_web::{web, App, Error, HttpResponse, HttpServer};
use std::{
fs::OpenOptions,
io::{self, Write},
};
async fn create_process(body: web::Bytes) -> Result<HttpResponse, Error> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open("file.json")?;
file.write_all(&body)?;
Ok(HttpResponse::Ok().body("Successful"))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With