0

我正在尝试使用 Rust Warp API 使用一个小应用程序,但超级坚持构建代码。我在这里尝试遵循此示例,但无法遵循我做错了什么。有人可以帮我弄这个吗?

async fn request_info(item: ItemObj) -> Result<impl warp::Reply, warp::Rejection> {

    let items = ItemConfig::new("data.toml");
    let item_info = items.find_session(&item.id);

    match item_info {
        Some(info) => {
            let json_reply = JsonReply {
                                 ItemId: item.id(),
                                 ItemDetail: item.detail(),
                                 EndPoint: info.get(),
                                 Port: info.get_port(),
                                 WebUrlPath: info.get_path_weburl(),
                            };
            // let json_str = serde_json::to_string(&json_reply);
            // Ok(warp::reply::with_status(json_str,http::StatusCode::OK,))
            Ok(warp::reply::json(&json_reply))

        }
        None => {
            Ok(warp::reply::with_status("", http::StatusCode::OK,))
        }
    }
}

#[tokio::main]
async fn main() {

    let resolver = warp::post()
        .and(warp::path("info_request"))
        .and(warp::path::end())
        .and(port_json()) 
        .and_then(request_info);

    warp::serve(resolver)
        .run(([127, 0, 0, 1], 8081))
        .await;
}

错误:

error[E0308]: mismatched types
  --> src/main.rs:50:16
   |
50 |               Ok(warp::reply::with_status("", 
   |  ________________^
51 | |                                         http::StatusCode::OK,))
   | |______________________________________________________________^ expected struct `Json`, found struct `WithStatus`
   |
   = note: expected struct `Json`
              found struct `WithStatus<&str>`

For more information about this error, try `rustc --explain E0308`.
warning: `resolver` (bin "resolver") generated 2 warnings
error: could not compile `resolver` due to previous error; 2 warnings emitted
4

1 回答 1

0

在匹配中,返回值必须相同。由于您无法确定返回值的大小,您可以编写以下内容:

async fn request_info() -> Result<Box<dyn warp::Reply>, warp::Rejection> {
    let x = Some(5);

    match x {
        Some(x) => {
            let x = format!("{}", x);
            Ok(Box::new(warp::reply::json(&x)))
        }
        None => Ok(Box::new(warp::reply::with_status(
            "",
            warp::http::StatusCode::OK,
        ))),
    }
}
于 2021-11-18T07:48:01.493 回答