将lambda_http Body对象转换为字符串类型?

问题描述 投票:0回答:2

我是 Rust 的新手。我有一个 lambda_http 请求对象,我想获取 Body 的文本作为字符串。

我正在阅读有关 Body文档,但对 Rust 来说太陌生了,无法理解我在看什么。可能我需要以某种方式使用

Text
属性?

当前代码:

async fn process_request(request: Request) -> Result<impl IntoResponse, std::convert::Infallible> {
    let body = request.body();
    let my_string = body.to_string();
    if let Err(e) = write_to_dynamodb(&my_string).await {
        eprintln!("Error: {}", DisplayErrorContext(e));
    }
}

这给了我错误:

let my_string = body.to_string();
|                          ^^^^^^^^^ method cannot be called on `&lambda_http::Body` due to unsatisfied trait bounds

我做错了什么,我应该如何阅读文档?

rust
2个回答
0
投票

因为

Body
取消对
&[u8]
的引用,使用
std::str::from_utf8()
(如果你想要
to_owned()
而不是
String
,你可以调用
&str
):

let body = request.body();
let my_string = std::str::from_utf8(body).expect("non utf-8");

0
投票

在您链接的文档中,它看起来像 Body 是一个枚举。如果你想要它作为一个字符串,你首先必须检查枚举是否是这样的文本:

    let body = request.body();
    if let lambda_http::Body::Text(my_string) = body {
        println!("{}", my_string);
        // do stuff here with my_string
    }
© www.soinside.com 2019 - 2024. All rights reserved.