Search code examples
rusthyper

How do I add multiple RPC endpoints using hyper?


I want to create multiple RPC methods using hyper. This is their example code. How do I add multiple methods and start the service which returns a BoxFuture?

Below, I have two methods, how do I merge the two methods and create the service?

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);
    }
}

Solution

  • One approach I've taken in the past is to make one service act as a routing table. I've written the service containing nothing but a match that matches the path and http method which then calls the appropriate function in each arm.

    E.g:

    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)
    }
    

    Whether or not this is the recommended way to go about things in Hyper I don't know but it works well for the things I've built.