Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get body of request as text with actix?

Tags:

rust

actix-web

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
like image 456
DungeonTiger Avatar asked Feb 01 '26 03:02

DungeonTiger


1 Answers

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"))
}
like image 190
Peter Hall Avatar answered Feb 03 '26 23:02

Peter Hall