jsonrpc_v2_awc/lib.rs
1//! JSON RPC Client
2//!
3//! This library provides a way to send JSON RPC requests, there are 2 options,
4//! without api_key and with api_key which sets request header API_KEY
5//!
6//! Examples
7//! ``` no_run
8//! // call to remote function `mul` taking 2 numbers, they can be u8, f32, etc
9//! println!(
10//! "2 + 3 = {:?}",
11//! jsonrpc_v2_awc::Request::new("mul", jsonrpc_v2_awc::Params([2, 3]), 0)
12//! .send("http://localhost:8082/api")
13//! .await?
14//! .body()
15//! .await?
16//! );
17//!
18//! // call to remote function `timestamp` with no params, in this case params can be () or ""
19//! println!(
20//! "2 + 3 = {:?}",
21//! jsonrpc_v2_awc::Request::new("timestamp", jsonrpc_v2_awc::Params(()), 1)
22//! .send("http://localhost:8082/api")
23//! .await?
24//! .body()
25//! .await?
26//! );
27//!
28//! // call to remote function `timestamp` with no params, using api_key
29//! println!(
30//! "2 + 3 = {:?}",
31//! jsonrpc_v2_awc::Request::new("timestamp", jsonrpc_v2_awc::Params(()), 1)
32//! .send_with_api_key("http://localhost:8082/api", "API_KEY", "ds09ds9d-0d9s0d.xxx.yyy")
33//! .await?
34//! .body()
35//! .await?
36//! );
37//! ```
38use awc::Client;
39use serde::Serialize;
40
41pub const JSONRPC_VERSION: &str = "2.0";
42
43#[derive(Debug, Serialize)]
44pub struct Params<T: Serialize>(pub T);
45
46#[derive(Debug, Serialize)]
47pub struct Request<T: Serialize> {
48 jsonrpc: String,
49 pub method: String,
50 pub params: Params<T>,
51 pub id: u64,
52}
53
54impl<T: Serialize> Request<T> {
55 pub fn new(method: &str, params: Params<T>, id: u64) -> Request<T> {
56 Request {
57 jsonrpc: JSONRPC_VERSION.to_string(),
58 method: method.to_string(),
59 params: params,
60 id: id,
61 }
62 }
63 pub fn send(self, url: &str) -> awc::SendClientRequest {
64 return Client::new()
65 .post(url)
66 .header("User-Agent", "actix-web/3.0")
67 .header("Content-Type", "application/json")
68 .send_json(&self);
69 }
70
71 pub fn send_with_api_key(self, url: &str, key_name: &str, key_value: &str) -> awc::SendClientRequest {
72 return Client::new()
73 .post(url)
74 .header("User-Agent", "actix-web/3.0")
75 .header("Content-Type", "application/json")
76 .header(key_name, key_value)
77 .send_json(&self);
78 }
79}