Skip to content

Instantly share code, notes, and snippets.

@jac18281828
Created August 21, 2024 16:59
Show Gist options
  • Save jac18281828/9cfceacf1e60ab26d8672d0a245f50ca to your computer and use it in GitHub Desktop.
Save jac18281828/9cfceacf1e60ab26d8672d0a245f50ca to your computer and use it in GitHub Desktop.
run jsonrpsee RpcServer
pub async fn run_server(host: String, port: u16) -> eyre::Result<SocketAddr> {
// Add a CORS middleware for handling HTTP requests.
// This middleware does affect the response, including appropriate
// headers to satisfy CORS. Because any origins are allowed, the
// "Access-Control-Allow-Origin: *" header is appended to the response.
let cors = CorsLayer::new()
// Allow `POST` when accessing the resource
.allow_methods([Method::POST])
// Allow requests from any origin
.allow_origin(Any)
.allow_headers([hyper::header::CONTENT_TYPE]);
let middleware = tower::ServiceBuilder::new().layer(cors);
let server_host = format!("{}:{}", host, port);
// The RPC exposes the access control for filtering and the middleware for
// modifying requests / responses. These features are independent of one another
// and can also be used separately.
// In this example, we use both features.
let server = Server::builder()
.set_http_middleware(middleware)
.build(server_host)
.await?;
let addr = server.local_addr()?;
let handle = server.start(RpcServerImpl.into_rpc());
// In this example we don't care about doing shutdown so let's it run forever.
// You may use the `ServerHandle` to shut it down or manage it yourself.
handle.stopped().await;
Ok(addr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment