Return 在 warp::reply::with_status 中拥有的字符串

Return owned string in warp::reply::with_status

我有一个 warp 服务器 运行,对于每个请求,我都需要计算一个字符串,然后 return 该字符串具有特定的状态代码。

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 取消对 &str 的引用)——但这也不起作用,因为您不能 return 对当前作用域所拥有的变量的引用(将被删除)

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

如何在使用 warp 时 return 一个 String 作为响应?

这个问题最初没有包含完整的代码,但事实证明之前有一个早期的-return,其中包含一个 &str,结果是 reply::with_status returning a WithStatus<&str>,在同一范围内尝试 return a WithStatus<String> 时导致不匹配。

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()) {
            return reply::with_status("Request parameter xyz is invalid", StatusCode::BAD_REQUEST);
//                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type &str
        }

        let computed_string: String = compute_from(buf, header);
        return reply::with_status(
            computed_string,
//          ^^^^^^^^^^^^^^^ type String
            StatusCode::CREATED,
        );
    });