Crate json_rpc2

Source
Expand description

Simple, robust and pragmatic facade for JSON-RPC2 services that is transport agnostic.

use json_rpc2::*;
use serde_json::Value;

struct ServiceHandler;
impl Service for ServiceHandler {
   type Data = ();
   fn handle(&self, request: &Request, _ctx: &Self::Data) -> Result<Option<Response>> {
       let response = match request.method() {
         "hello" => {
           let params: String = request.deserialize()?;
           let message = format!("Hello, {}!", params);
           Some((request, Value::String(message)).into())
         }
         _ => None
       };
       Ok(response)
   }
}

fn main() -> Result<()> {
   let service: Box<dyn Service<Data = ()>> = Box::new(ServiceHandler {});
   let request = Request::new_reply(
       "hello", Some(Value::String("world".to_string())));
   let server = Server::new(vec![&service]);
   let response = server.serve(&request, &());
   assert_eq!(
       Some(Value::String("Hello, world!".to_string())),
       response.unwrap().into());
   Ok(())
}

§Parsing

When converting from incoming payloads use the from_* functions to convert JSON to a Request so that errors are mapped correctly.

§Context

For most applications user data can be assigned to the struct that implements the Service trait but sometimes you may need to serve requests from a callback function that passes useful information you want to expose to the service methods. Use Data = T with a custom type to expose user data to your handlers that is not available when the services are created.

§Async

For nonblocking support enable the async feature and use the Service trait from the futures module. You will also need to depend upon the async-trait crate and use the #[async_trait] attribute macro on your service implementation.

See the async example for usage.

Modules§

futures
Non-blocking implementation, requires the async feature.

Structs§

Request
JSON-RPC request.
Response
JSON-RPC response.
RpcError
Error information for response messages.
Server
Serve requests.

Enums§

Error
Enumeration of errors.

Traits§

Service
Trait for services that maybe handle a request.

Functions§

from_reader
Parse a JSON payload from an IO reader into a request.
from_slice
Parse a JSON payload from a byte slice into a request.
from_str
Parse a JSON payload from a string slice into a request.
from_value
Parse a JSON payload from a Value into a request.

Type Aliases§

Result
Result type for service handler functions and internal library errors.