gpt4 book ai didi

rust - 无法将闭包传递给 `Hyper::service_fn`

转载 作者:行者123 更新时间:2023-12-03 11:35:39 27 4
gpt4 key购买 nike

我想用hyper编写一个简单的微服务:

use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use hyper::{Method, StatusCode};
use std::{convert::Infallible, net::SocketAddr};

struct ApiServer {}

impl ApiServer {
pub async fn route(&mut self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
let mut response = Response::new(Body::empty());
*response.body_mut() = req.into_body();

Ok(response)
}
}

#[tokio::main]
async fn main() {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let mut api = ApiServer {};

let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(|req| async { api.route(req) }))
});

let server = Server::bind(&addr).serve(make_svc);

if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}

我收到编译器错误:

error[E0271]: type mismatch resolving `<impl std::future::Future as std::future::Future>::Output == std::result::Result<http::response::Response<_>, _>`
--> src/master/bin/main.rs:46:38
|
46 | let server = Server::bind(&addr).serve(make_svc);
| ^^^^^ expected opaque type, found enum `std::result::Result`
|

如何重写代码,让 route函数成为 ApiServer的成员函数?

最佳答案

Rust错误消息与您期望的相反:serve()期望Result,但是找到了opaque类型。您需要等待api.route(req)的返回值。修复其他编译错误,最终代码为:

use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use std::{convert::Infallible, net::SocketAddr};

#[derive(Clone, Copy)]
struct ApiServer {}

impl ApiServer {
pub async fn route(&mut self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
let mut response = Response::new(Body::empty());
*response.body_mut() = req.into_body();

Ok(response)
}
}

#[tokio::main]
async fn main() {
let mut api = ApiServer {};

let make_svc = make_service_fn(move |_conn| async move {
Ok::<_, Infallible>(service_fn(move |req| async move { api.route(req).await }))
});

let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

let server = Server::bind(&addr).serve(make_svc);

if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}

看:
  • Return Type Errors
  • 关于rust - 无法将闭包传递给 `Hyper::service_fn`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61503490/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com