2 releases

new 0.1.1 Nov 23, 2024
0.1.0 Nov 12, 2024

#327 in HTTP client

Download history 262/week @ 2024-11-10 412/week @ 2024-11-17

682 downloads per month
Used in 3 crates (2 directly)

Apache-2.0

51KB
1K SLoC

Build + Test

Nimiq JSON-RPC

A Rust implementation of the JSON-RPC 2.0 specification.

  • nimiq-jsonrpc-core implements the data structures (using serde) for JSON-RPC.
  • nimiq-jsonrpc-client is a client implementation for a HTTP (using reqwest) and websocket client (using tokio-tungstenite).
  • nimiq-jsonrpc-server is a server implementation for HTTP and websocket (using warp).

Example

use async_trait::async_trait;
use serde::{Serialize, Deserialize};

use nimiq_jsonrpc_server::{Server, Config};
use nimiq_jsonrpc_client::http::HttpClient;


#[nimiq_jsonrpc_derive::proxy]
#[async_trait]
trait Foobar {
    async fn hello(&mut self, name: String) -> String;
}

struct FoobarService;

#[nimiq_jsonrpc_derive::service]
#[async_trait]
impl Foobar for FoobarService {
    async fn hello(&mut self, name: String) -> String {
        println!("Hello, {}", name);
        format!("Hello, {}", name)
    }
}


#[tokio::main]
async fn main() {
    dotenvy::dotenv().ok();
    pretty_env_logger::init();

    let config = Config::default();

    log::info!("Listening on: {}", config.bind_to);

    let server = Server::new(config, FoobarService);
    tokio::spawn(async move {
        server.run().await;
    });

    let client = HttpClient::new("http://localhost:8000/");
    let mut proxy = FoobarProxy::new(client);

    let retval = proxy.hello("World".to_owned()).await;
    log::info!("RPC call returned: {}", retval);
}

TODO

  • Share code between websocket clients.

lib.rs:

This crate implements multiple JSON-RPC clients. Currently available are: http and websocket. Only websocket supports PubSub.

Instead of using a Client implementation and calling Client::send_request directly, you can derive a proxy struct that implements methods for ergonomic RPC calling:

use async_trait::async_trait;

#[nimiq_jsonrpc_derive::proxy]
#[async_trait]
trait Foobar {
    type Error;
    async fn hello(&mut self, name: String) -> Result<String, Self::Error>;
}

TODO

  • Implement PubSub
  • Proper error handling

Dependencies

~3–15MB
~195K SLoC