main.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. mod demo;
  15. use crate::demo::demo;
  16. async fn _start() -> Result<()> {
  17. let rpc_addr = Url::parse("tcp://127.0.0.1:7777")?;
  18. let rpc_interface = Arc::new(JsonRpcInterface {});
  19. listen_and_serve(rpc_addr, rpc_interface).await?;
  20. Ok(())
  21. }
  22. struct JsonRpcInterface {}
  23. #[async_trait]
  24. impl RequestHandler for JsonRpcInterface {
  25. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  26. if req.params.as_array().is_none() {
  27. return JsonError::new(InvalidParams, None, req.id).into()
  28. }
  29. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  30. match req.method.as_str() {
  31. Some("say_hello") => return self.say_hello(req.id, req.params).await,
  32. Some(_) | None => return JsonError::new(MethodNotFound, None, req.id).into(),
  33. }
  34. }
  35. }
  36. impl JsonRpcInterface {
  37. // --> {"method": "say_hello", "params": []}
  38. // <-- {"result": "hello world"}
  39. async fn say_hello(&self, id: Value, _params: Value) -> JsonResult {
  40. JsonResponse::new(json!("hello world"), id).into()
  41. }
  42. }
  43. #[async_std::main]
  44. async fn main() -> Result<()> {
  45. TermLogger::init(
  46. LevelFilter::Debug,
  47. simplelog::Config::default(),
  48. TerminalMode::Mixed,
  49. ColorChoice::Auto,
  50. )?;
  51. //start().await?;
  52. demo().await.unwrap();
  53. Ok(())
  54. }