23 releases (12 breaking)

0.13.0 Sep 2, 2023
0.12.0 Jul 29, 2023
0.11.0 Mar 22, 2022
0.10.1 May 14, 2021
0.2.1 Feb 7, 2019

#217 in HTTP server

Download history 2026/week @ 2024-02-27 896/week @ 2024-03-05 1218/week @ 2024-03-12 1160/week @ 2024-03-19 557/week @ 2024-03-26 894/week @ 2024-04-02 596/week @ 2024-04-09 499/week @ 2024-04-16 169/week @ 2024-04-23 235/week @ 2024-04-30 500/week @ 2024-05-07 442/week @ 2024-05-14 542/week @ 2024-05-21 337/week @ 2024-05-28 622/week @ 2024-06-04 522/week @ 2024-06-11

2,098 downloads per month
Used in 3 crates

MIT license

57KB
1.5K SLoC

jsonrpc-v2

Docs Crates.io

A very small and very fast JSON-RPC 2.0 server-focused framework.

Provides integrations for both hyper and actix-web (1.x, 2.x, 3.x, 4.x). Enable features actix-web-v3-integration, hyper-integration, etc. as needed.

actix-web-v4-integration is enabled by default. Make sure to add default-features = false if using hyper or other actix-web versions.

Also see the easy-errors feature flag (not enabled by default). Enabling this flag will implement ErrorLike for anything that implements Display, and the display value will be provided in the message field of the JSON-RPC 2.0 Error response.

Otherwise, custom errors should implement ErrorLike to map errors to the JSON-RPC 2.0 Error response.

Individual method handlers are async functions that can take various kinds of args (things that can be extracted from the request, like the Params or Data), and should return a Result<Item, Error> where the Item is serializable. See examples below.

Usage

use jsonrpc_v2::{Data, Error, Params, Server};

#[derive(serde::Deserialize)]
struct TwoNums {
    a: usize,
    b: usize,
}

async fn add(Params(params): Params<TwoNums>) -> Result<usize, Error> {
    Ok(params.a + params.b)
}

async fn sub(Params(params): Params<(usize, usize)>) -> Result<usize, Error> {
    Ok(params.0 - params.1)
}

async fn message(data: Data<String>) -> Result<String, Error> {
    Ok(String::from(&*data))
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    let rpc = Server::new()
        .with_data(Data::new(String::from("Hello!")))
        .with_method("sub", sub)
        .with_method("message", message)
        .finish();

    actix_web::HttpServer::new(move || {
        let rpc = rpc.clone();
        actix_web::App::new().service(
            actix_web::web::service("/api")
                .guard(actix_web::guard::Post())
                .finish(rpc.into_web_service()),
        )
    })
    .bind("0.0.0.0:3000")?
    .run()
    .await
}

Current version: 0.11.0

License: MIT

Dependencies

~2–18MB
~215K SLoC