I have implemented json rpc server with rust by looking up this.
use jsonrpc_core::*;
use jsonrpc_http_server::*;
fn main() {
let mut io = IoHandler::new();
io.add_method("say_hello", |_: Params| {
println!("Params : {:?}", params);
Ok(Value::String("hello".to_string()))
});
let _server = ServerBuilder::new(io)
.start_http(&"127.0.0.1:3030".parse().unwrap())
.expect("Unable to start RPC server");
_server.wait();
}
The above server is working as expected. Here the param takes vector or map.
For request {"jsonrpc": "2.0", "method": "say_hello", "params": {"a": 2, "b": 3}, "id": 1}
it prints
Params : Map({"a": Number(2), "b": Number(3)})
And for request {"jsonrpc": "2.0", "method": "say_hello", "params": [2,3], "id": 1}
it prints
Params : Array([Number(42), Number(23)])
How do I access these parameters from this Params enum as Map or Array?
UPDATE 1
I modified my code to get params as map -
io.add_method("say_hello", |params: Params| {
let map: HashMap<String, Value> = params.parse().unwrap();
println!("Params : {:?}", map);
Ok(Value::String("hello".to_string()))
});
It prints
Params : {"a": Number(2), "b": Number(3)}
UPDATE 2 Modification for accessing map by key -
io.add_method("say_hello", |params: Params| {
let map: HashMap<String, Value> = params.parse().unwrap();
println!("Params : {:?}", map);
let var_a = map.get(&"a");
let var_b = map.get(&"b");
println!("A : {:?}, B: {:?}", var_a, var_b);
Ok(Value::String("hello".to_string()))
});
Now I am getting following error :
error[E0277]: the trait bound `std::string::String:
std::borrow::Borrow<&str>` is not satisfied --> src/main.rs:41:29
|
41 | let var_a = map.get(&"a");
| ^^^ the trait `std::borrow::Borrow<&str>` is not implemented for `std::string::String`
|
= help: the following implementations were found:
<std::string::String as std::borrow::Borrow<str>>