JSON-RPC and LSP

From bibbleWiki
(Redirected from JSON-RPC)
Jump to navigation Jump to search

Introduction

This is probably the quickest thing to put my nose into. So here goes with rust

Rust Example JSON-RPC

To get going we need

[dependencies]
jsonrpc-core = "18.0.0"
jsonrpc-http-server = "18.0.0"
serde_json = "1.0.140"

And here is the code. Not must to discuss. The ServerBuilder I thought was pretty cool.

fn main() {
    let mut io = IoHandler::default();

    io.add_method("say_hello", |_params: Params| async {
        Ok( Value::String("Hello, world!".to_string()))
    });

    io.add_method("add", |params: Params| async {
        let tuple = params.parse::<(i32, i32)>();
        match tuple {
            Ok((a, b)) => Ok(Value::Number((a + b).into())),
            Err(_) => Err(jsonrpc_core::Error::invalid_params("Invalid parameters")),
            
        }
    });
   
    let server = ServerBuilder::new(io)
    .threads(3)
    .start_http(&"0.0.0.0:8003".parse().unwrap())
    .unwrap();

    println!("Server is up");

    server.wait();
}

And finally the JSON to send

{
  "jsonrpc": "2.0",
  "method": "add",
  "params": [10,12],
  "id": 1
}

And the no surprises response.

{
    "jsonrpc": "2.0",
    "result": 22,
    "id": 1
}

And in error (provided it is valid json)

{
    "jsonrpc": "2.0",
    "error": {
        "code": -32602,
        "message": "Invalid parameters"
    },
    "id": 1
}

With invalid json there is no id

{
    "jsonrpc": "2.0",
    "error": {
        "code": -32700,
        "message": "Parse error"
    },
    "id": null
}

Rust Example LSP

LSP is the same as JSON-RPC except we send a content length