aboutsummaryrefslogtreecommitdiff
path: root/jsonrpc/examples/server.rs
blob: b09232f8e6a87736084b044e06c48d140cccc5cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use smol::net::TcpListener;

use karyons_jsonrpc::{register_service, JsonRPCError, Server, ServerConfig};

struct Calc {
    version: String,
}

#[derive(Deserialize, Serialize)]
struct Req {
    x: u32,
    y: u32,
}

#[derive(Deserialize, Serialize)]
struct Pong {}

impl Calc {
    async fn ping(&self, _params: Value) -> Result<Value, JsonRPCError> {
        Ok(serde_json::json!(Pong {}))
    }

    async fn add(&self, params: Value) -> Result<Value, JsonRPCError> {
        let params: Req = serde_json::from_value(params)?;
        Ok(serde_json::json!(params.x + params.y))
    }

    async fn sub(&self, params: Value) -> Result<Value, JsonRPCError> {
        let params: Req = serde_json::from_value(params)?;
        Ok(serde_json::json!(params.x - params.y))
    }

    async fn version(&self, _params: Value) -> Result<Value, JsonRPCError> {
        Ok(serde_json::json!(self.version))
    }
}

fn main() {
    env_logger::init();
    let ex = Arc::new(smol::Executor::new());
    smol::block_on(ex.clone().run(async {
        // Creates a new server
        let listener = TcpListener::bind("127.0.0.1:60000").await.unwrap();
        let config = ServerConfig::default();
        let server = Server::new(listener, config, ex);

        // Register the Calc service
        register_service!(Calc, ping, add, sub, version);
        let calc = Calc {
            version: String::from("0.1"),
        };
        server.attach_service(calc).await;

        // Start the server
        server.start().await.unwrap();
    }));
}