Crate casper_json_rpc
source ·Expand description
casper-json-rpc
A library suitable for use as the framework for a JSON-RPC server.
Usage
Normally usage will involve two steps:
- construct a set of request handlers using a
RequestHandlersBuilder
- call
casper_json_rpc::route
to construct a boxed warp filter ready to be passed towarp::service
for example
Example
use casper_json_rpc::{Error, Params, RequestHandlersBuilder};
use std::{convert::Infallible, sync::Arc};
async fn get(params: Option<Params>) -> Result<String, Error> {
// * parse params or return `ReservedErrorCode::InvalidParams` error
// * handle request and return result
Ok("got it".to_string())
}
async fn put(params: Option<Params>, other_input: &str) -> Result<String, Error> {
Ok(other_input.to_string())
}
#[tokio::main]
async fn main() {
// Register handlers for methods "get" and "put".
let mut handlers = RequestHandlersBuilder::new();
handlers.register_handler("get", Arc::new(get));
let put_handler = move |params| async move { put(params, "other input").await };
handlers.register_handler("put", Arc::new(put_handler));
let handlers = handlers.build();
// Get the new route.
let path = "rpc";
let max_body_bytes = 1024;
let allow_unknown_fields = false;
let route = casper_json_rpc::route(path, max_body_bytes, handlers, allow_unknown_fields);
// Convert it into a `Service` and run it.
let make_svc = hyper::service::make_service_fn(move |_| {
let svc = warp::service(route.clone());
async move { Ok::<_, Infallible>(svc.clone()) }
});
hyper::Server::bind(&([127, 0, 0, 1], 3030).into())
.serve(make_svc)
.await
.unwrap();
}
Errors
To return a JSON-RPC response indicating an error, use Error::new
. Most error conditions
which require returning a reserved error are already handled in the provided warp filters. The
only exception is ReservedErrorCode::InvalidParams
which should be returned by any RPC
handler which deems the provided params: Option<Params>
to be invalid for any reason.
Generally a set of custom error codes should be provided. These should all implement
ErrorCodeT
.
Modules
- Warp filters which can be combined to provide JSON-RPC endpoints.
Structs
- An object suitable to be returned in a JSON-RPC response as the “error” field.
- A collection of request-handlers, indexed by the JSON-RPC “method” applicable to each.
- A builder for
RequestHandlers
.
Enums
- Specifies the CORS origin
- The “params” field of a JSON-RPC request.
- The various reserved codes which can be returned in the JSON-RPC response’s “error” object.
- A JSON-RPC response.
Traits
- A marker trait for a type suitable for use as an error code when constructing an
Error
.
Functions
- Constructs a set of warp filters suitable for use in a JSON-RPC server.
- Constructs a set of warp filters suitable for use in a JSON-RPC server.