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
Non-blocking implementation, requires the async
feature.
Structs
JSON-RPC request.
JSON-RPC response.
Error information for response messages.
Serve requests.
Enums
Enumeration of errors.
Traits
Trait for services that maybe handle a request.
Functions
Parse a JSON payload from an IO reader into a request.
Parse a JSON payload from a byte slice into a request.
Parse a JSON payload from a string slice into a request.
Parse a JSON payload from a Value into a request.
Type Definitions
Result type for service handler functions and internal library errors.