我有一个经纱服务器正在运行,对于每个请求,我都需要计算一个字符串,然后返回带有特定状态代码的字符串。
use warp::{http::StatusCode, reply, Filter};
let creator = warp::post()
.and(warp::path("mypath"))
.and(warp::body::bytes())
.and(warp::header("myheader"))
.map(move |buf: warp::hyper::body::Bytes, header: String| {
if (is_request_invalid()) {
reply::with_status("Request parameter xyz is invalid", StatusCode::BAD_REQUEST);
}
let computed_string: String = compute_from(buf, header);
return reply::with_status(
computed_string,
StatusCode::CREATED,
);
});
但是,这不起作用,因为 reply::with_status 需要一种&str
.
error[E0308]: mismatched types
--> lib.rs:54:33
|
54 | ... computed_string,
| ^^^^^^^^^^^^^^^
| |
| expected `&str`, found struct `std::string::String`
| help: consider borrowing here: `&computed_string`
所以我尝试了:
// -- SNIP --
return reply::with_status(
&computed_string,
StatusCode::CREATED,
);
// -- SNIP --
(因为 &String derefs to &str)——但这也不起作用,因为你不能返回对当前作用域拥有的变量的引用(将被删除)
error[E0597]: `computed_string` does not live long enough
--> lib.rs:54:33
|
53 | return reply::with_status(
| ____________________________________-
54 | | &computed_string,
| | ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
55 | | StatusCode::CREATED,
56 | | );
| |_____________________________- argument requires that `computed_string` is borrowed for `'static`
57 | }
| - `computed_string` dropped here while still borrowed
使用时如何返回 aString
作为响应warp
?