main.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. use std::sync::Arc;
  2. use async_trait::async_trait;
  3. use log::debug;
  4. use serde_json::{json, Value};
  5. use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
  6. use url::Url;
  7. use darkfi::{
  8. rpc::{
  9. jsonrpc::{ErrorCode::*, JsonError, JsonRequest, JsonResponse, JsonResult},
  10. server::{listen_and_serve, RequestHandler},
  11. },
  12. Result,
  13. };
  14. async fn start() -> Result<()> {
  15. let rpc_addr = Url::parse("tcp://127.0.0.1:7777")?;
  16. let rpc_interface = Arc::new(JsonRpcInterface {});
  17. listen_and_serve(rpc_addr, rpc_interface).await?;
  18. Ok(())
  19. }
  20. struct JsonRpcInterface {}
  21. #[async_trait]
  22. impl RequestHandler for JsonRpcInterface {
  23. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  24. if req.params.as_array().is_none() {
  25. return JsonError::new(InvalidParams, None, req.id).into()
  26. }
  27. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  28. match req.method.as_str() {
  29. Some("say_hello") => return self.say_hello(req.id, req.params).await,
  30. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  31. }
  32. }
  33. }
  34. impl JsonRpcInterface {
  35. // --> {"method": "say_hello", "params": []}
  36. // <-- {"result": "hello world"}
  37. async fn say_hello(&self, id: Value, _params: Value) -> JsonResult {
  38. JsonResponse::new(json!("hello world"), id).into()
  39. }
  40. }
  41. #[async_std::main]
  42. async fn main() -> Result<()> {
  43. TermLogger::init(
  44. LevelFilter::Debug,
  45. simplelog::Config::default(),
  46. TerminalMode::Mixed,
  47. ColorChoice::Auto,
  48. )?;
  49. start().await?;
  50. Ok(())
  51. }