0

我有一个经纱服务器正在运行,对于每个请求,我都需要计算一个字符串,然后返回带有特定状态代码的字符串。

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

4

1 回答 1

1

该问题最初并未包含完整的代码,但事实证明之前有一个包含 a 的提前返回&str,这导致reply::with_status返回 a WithStatus<&str>,这在尝试WithStatus<String>在相同范围内返回 a 时导致不匹配。

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,
        );
    });
于 2021-04-12T14:15:04.677 回答