Rust + Rocket:我如何从请求中读取 POST 正文作为字符串?

Rust + Rocket: How I do read POST body from request as string?

我正在使用 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

更新二:

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

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 or FromData

的类型