Crate json_rpc2[][src]

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: &mut Request, _ctx: &Context<Self::Data>) -> Result<Option<Response>> {
       let mut response = None;
       if request.matches("hello") {
           let params: String = request.deserialize()?;
           let message = format!("Hello, {}!", params);
           response = Some((request, Value::String(message)).into());
       }
       Ok(response)
   }
}

fn main() -> Result<()> {
   let service: Box<dyn Service<Data = ()>> = Box::new(ServiceHandler {});
   let mut request = Request::new(
       "hello", Some(Value::String("world".to_string())));
   let server = Server::new(vec![&service]);
   let response = server.serve(&mut request, &Context::new(()));
   assert_eq!(
       Some(Value::String("Hello, world!".to_string())),
       response.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 Context<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

Context

Context information passed to service handlers that wraps user data.

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 Definitions

Result

Result type for service handler functions and internal library errors.