Skip to content

Instantly share code, notes, and snippets.

@0xpr03
Last active October 4, 2019 00:11
Show Gist options
  • Save 0xpr03/b099c420170735a8c3ee03db5657fe1e to your computer and use it in GitHub Desktop.
Save 0xpr03/b099c420170735a8c3ee03db5657fe1e to your computer and use it in GitHub Desktop.
Jsonrpc-Core to Actix-Web bridge actix-web 1.0
/// Handle jsonrpc-core IOHandler stuff in actix
/// Based on https://github.com/paritytech/jsonrpc/blob/9360dc86e9c02e65e858ee7816c5ce6e04f18aef/http/src/handler.rs#L415
fn jsonrpc_websocket_bridge(
(data, req): (web::Json<Request>, web::Data<JsonrpcState>),
) -> impl Future<Item = HttpResponse, Error = WebError> {
req.handle_rpc_request(data.into_inner())
.map(|res| match res {
Some(v) => HttpResponse::Ok().json(v),
e => {
error!("Invalid response for request: {:?}", e);
HttpResponse::InternalServerError().finish()
}
})
.map_err(|_| {
ErrorInternalServerError("()-Error route in jsonrpc-actix bridge! Should never happen.")
})
}
type JsonrpcState = Arc<IoHandler>;
/// Handle jsonrpc-core IOHandler stuff in actix
/// Based on https://github.com/paritytech/jsonrpc/blob/9360dc86e9c02e65e858ee7816c5ce6e04f18aef/http/src/handler.rs#L415
fn jsonrpc_websocket_bridge(
(data, req): (web::Json<Request>, web::Data<JsonrpcState>),
) -> impl Future<Item = HttpResponse, Error = WebError> {
req.handle_rpc_request(data.into_inner())
.map(|res| match res {
Some(v) => HttpResponse::Ok().json(v),
e => {
error!("Invalid response for request: {:?}", e);
HttpResponse::InternalServerError().finish()
}
})
.map_err(|_| {
ErrorInternalServerError("()-Error route in jsonrpc-actix bridge! Should never happen.")
})
}let mut io = IoHandler::new();
let inst_c = instances.clone();
io.add_method("foo", move |data: Params| {
/* ...*/
}
let state: JsonrpcState = Arc::new(io);
actix_web::HttpServer::new(move || {
let json_only = actix_web::guard::Header("Content-Type", "application/json");
actix_web::App::new()
.data(state.clone())
.service(
web::resource("/").route(
web::post()
.guard(json_only)
.to_async(jsonrpc_websocket_bridge),
),
)
})
/*---*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment