如何使用actix将请求正文作为文本获取?
How to get body of request as text with actix?
我正在使用 Actix 构建一个简单的 REST 服务器。我似乎无法弄清楚如何将请求的正文作为文本获取。该请求将是任意的 JSON 所以我不想将其转换为类型。我只想将文本转储到磁盘。
async fn create_process(req: HttpRequest) -> impl Responder {
// how do I get the body here?
}
这就是我启动服务器的方式:
HttpServer::new(|| {
App::new()
.route("/api/1/0/create_process", web::post().to(create_process))
})
.bind("127.0.0.1:8080")?
.run()
.await
您可以使用 Bytes
提取器,它以字节片的形式提供请求正文,并直接保存到文件中:
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"))
}
我正在使用 Actix 构建一个简单的 REST 服务器。我似乎无法弄清楚如何将请求的正文作为文本获取。该请求将是任意的 JSON 所以我不想将其转换为类型。我只想将文本转储到磁盘。
async fn create_process(req: HttpRequest) -> impl Responder {
// how do I get the body here?
}
这就是我启动服务器的方式:
HttpServer::new(|| {
App::new()
.route("/api/1/0/create_process", web::post().to(create_process))
})
.bind("127.0.0.1:8080")?
.run()
.await
您可以使用 Bytes
提取器,它以字节片的形式提供请求正文,并直接保存到文件中:
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"))
}