gpt4 book ai didi

rest - rust + 火箭 : How I do read POST body from request as string?

转载 作者:行者123 更新时间:2023-12-03 11:42:54 27 4
gpt4 key购买 nike

我正在使用 Rust 和 Rocket 构建一个简单的 REST API。其中一个端点接受 POST 方法请求,并从请求正文中读取一个大字符串。我不知道如何用 Rocket 做到这一点。

文档描述了如何从 POST 请求的正文中读取 JSON 对象,以及如何读取多部分表单数据,但不是原始字符串。有谁知道如何做到这一点?


更新:

按照下面 Dave 的回答中的建议,我实现了 FromDataSimple 特征来尝试解析请求正文。这是我已经实现的,但它只导致获得“404 Not Found”响应:

struct Store {
contents: String,
}

impl FromDataSimple for Store {
type Error = String;

fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> {
let mut contents = String::new();

if let Err(e) = data.open().take(256).read_to_string(&mut contents) {
return Failure((Status::InternalServerError, format!("{:?}", e)));
}

Success(Store { contents })
}
}

#[post("/process", format = "application/json", data = "<input>")]
fn process_store(input: Store) -> &'static str {
"200 Okey Dokey"
}

不幸的是,当我运行它然后使用以下请求对它执行 ping 操作时,我只收到 404 Not Found 响应:-(

curl -X POST -H "Content-Type: application/json" --data "{ \"contents\": \"testytest\"}"  http://localhost:8080/process

更新 2:

实际上这确实有效,我只是忘记了将方法挂载到路由处理程序中:

fn main() {
rocket::ignite().mount("/", routes![index, process_store]).launch();
}

最佳答案

Body data processing, like much of Rocket, is type directed. To indicate that a handler expects body data, annotate it with data = "", where param is an argument in the handler. The argument's type must implement the FromData trait. It looks like this, where T is assumed to implement FromData:

#[post("/", data = "<input>")]
fn new(input: T) { /* .. */ }

所以你只需要创建一个实现 FromDataSimple 的类型或 FromData

关于rest - rust + 火箭 : How I do read POST body from request as string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63301943/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com