英文:
Convert lambda_http Body object to string type?
问题
以下是您要翻译的内容:
"I'm new to Rust. I have a lambda_http Request object and I would like to obtain the text of the Body as a string.
I'm reading the docs on Body but am too new to Rust to understand what I'm looking at. Possibly I need to use the Text
attribute somehow?
Current code:
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));
}
}
This gives me the error:
let my_string = body.to_string();
| ^^^^^^^^^ method cannot be called on `&lambda_http::Body` due to unsatisfied trait bounds
What am I doing wrong, and how should I be reading the docs?"
<details>
<summary>英文:</summary>
I'm new to Rust. I have a lambda_http Request object and I would like to obtain the text of the Body as a string.
I'm reading the (https://docs.rs/lambda_http/0.1.1/lambda_http/enum.Body.html) but am too new to Rust to understand what I'm looking at. Possibly I need to use the `Text` attribute somehow?
Current code:
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));
}
}
This gives me the error:
let my_string = body.to_string();
| ^^^^^^^^^ method cannot be called on `&lambda_http::Body` due to unsatisfied trait bounds
What am I doing wrong, and how should I be reading the docs?
</details>
# 答案1
**得分**: 1
请看以下翻译:
自 [`Body` 解引用为 `&[u8]`](https://docs.rs/aws_lambda_events/0.7.3/src/aws_lambda_events/encodings.rs.html#253-260) ,请使用 [`std::str::from_utf8()`](https://doc.rust-lang.org/stable/std/str/fn.from_utf8.html)(如果你需要 `String` 而不是 `&str`,可以调用 `to_owned()`):
```rust
let body = request.body();
let my_string = std::str::from_utf8(body).expect("非 UTF-8 字符串");
英文:
Since Body
derefs to &[u8]
, use std::str::from_utf8()
(you can call to_owned()
if you want String
and not &str
):
let body = request.body();
let my_string = std::str::from_utf8(body).expect("non utf-8");
答案2
得分: 1
在你提供的文档中,看起来"Body"是一个枚举类型。如果你想将它作为一个字符串处理,你首先需要检查枚举是否是文本类型,如下所示:
let body = request.body();
if let lambda_http::Body::Text(my_string) = body {
println!("{}", my_string);
// 在这里使用 my_string 进行操作
}
英文:
in the docs you linked, it looks like the Body is an enum. If you want it as a string, you'd first have to check if the enum is Text like this:
let body = request.body();
if let lambda_http::Body::Text(my_string) = body {
println!("{}", my_string);
// do stuff here with my_string
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论