2个稳定版本

1.1.0 2023年10月13日
1.0.0 2023年5月11日

#1754解析器实现


用于 casper-node

Apache-2.0

82KB
1.5K SLoC

casper-json-rpc

LOGO

Build Status Crates.io Documentation License

一个适合用作JSON-RPC服务器框架的库。

用法

通常使用涉及两个步骤

示例

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 route = casper_json_rpc::route(path, max_body_bytes, handlers);

    // 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();
}

如果收到以下请求

curl -X POST -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":"id","method":"get"}' http://127.0.0.1:3030/rpc

那么服务器将响应

{"jsonrpc":"2.0","id":"id","result":"got it"}

错误

要返回表示错误的JSON-RPC响应,请使用 Error::new。大多数需要返回保留错误的错误条件已经在提供的warp过滤器中处理。唯一的例外是 ReservedErrorCode::InvalidParams,它应由任何认为提供的 params: Option<Params> 因任何原因无效的RPC处理器返回。

通常应提供一组自定义错误代码。这些代码都应该实现 ErrorCodeT

示例自定义错误代码

use serde::{Deserialize, Serialize};
use casper_json_rpc::ErrorCodeT;

#[derive(Copy, Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
#[repr(i64)]
pub enum ErrorCode {
    /// The requested item was not found.
    NoSuchItem = -1,
    /// Failed to put the requested item to storage.
    FailedToPutItem = -2,
}

impl From<ErrorCode> for (i64, &'static str) {
    fn from(error_code: ErrorCode) -> Self {
        match error_code {
            ErrorCode::NoSuchItem => (error_code as i64, "No such item"),
            ErrorCode::FailedToPutItem => (error_code as i64, "Failed to put item"),
        }
    }
}

impl ErrorCodeT for ErrorCode {}

许可协议

根据 Apache License Version 2.0 许可。

依赖项

~9–19MB
~256K SLoC