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 { fn handle(&self, req: &mut Request) -> Result<Option<Response>> { let mut response = None; if req.matches("hello") { let params: String = req.deserialize()?; let message = format!("Hello, {}!", params); response = Some((req, Value::String(message)).into()); } Ok(response) } } fn main() -> Result<()> { let service: Box<dyn Service> = Box::new(ServiceHandler {}); let mut request = Request::new( "hello", Some(Value::String("world".to_string()))); let services = vec![&service]; let response = serve(&services, &mut request); 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.
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 |
Structs
Request | JSON-RPC request. |
Response | JSON-RPC response. |
RpcError | Error information for response messages. |
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. |
handle | Call services in order and return the first response message. |
serve | Infallible service handler, errors are automatically converted to responses. |
Type Definitions
Result | Result type for service handler functions and internal library errors. |