如何使用 hyper 添加多个 RPC 端点?

How do I add multiple RPC endpoints using hyper?

我想使用 hyper. This is their example code 创建多个 RPC 方法。如何添加多个方法并启动 returns a BoxFuture?

的服务

下面,我有两个方法,如何合并这两个方法并创建服务?

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

async fn gas_Price(_: Request<Body>) -> Result<Response<Body>, Infallible> {
    Ok(Response::new(Body::from("{id:1,jsonrpc:2.0,result:0x0}")))
}


async fn eth_Transaction(_: Request<Body>) -> Result<Response<Body>, Infallible> {
    Ok(Response::new(Body::from("eth_Transcation!")))
}

#[tokio::main]
pub async fn Start() {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3030));

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

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

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

我过去采用的一种方法是让一项服务充当路由 table。 我编写的服务仅包含匹配路径和 http 方法的匹配项,然后在每个 arm 中调用适当的函数。

例如:

pub async fn route(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    let mut response = Response::new(Body::empty());


    let method = req.method().clone();
    let uri = req.uri().clone();
    let path = uri.path();
    let full_body = hyper::body::to_bytes(req.into_body()).await?;
    let val = serde_json::from_slice::<Value>(&full_body)?;

    match (method,  path) {
        (Method::POST, "/some-enpoint") => {
            let new_body = appropriate_function(&val);
            *response.body_mut() = Body::from(new_body);
        },

        (_method, _path) => {
            *response.status_mut() = StatusCode::NOT_FOUND;
        }
    }
    Ok(response)
}

我不知道这是否是在 Hyper 中处理事情的推荐方法,但它适用于我构建的东西。