test-server.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use anyhow::Result;
  2. use std::collections::HashMap;
  3. fn print_usage(program: &str, opts: getopts::Options) {
  4. let brief = format!(
  5. "test-server: run a test CBORPC server on standard input-output that provides a counter (testproto/add1)\nUsage: {}",
  6. program
  7. );
  8. eprint!("{}", opts.usage(&brief));
  9. }
  10. fn main() {
  11. let args: Vec<String> = std::env::args().collect();
  12. let program = args[0].clone();
  13. let mut opts = getopts::Options::new();
  14. opts.optflag("h", "help", "print this help menu");
  15. let matches = match opts.parse(&args[1..]) {
  16. Ok(m) => m,
  17. Err(f) => panic!(f.to_string()),
  18. };
  19. if matches.opt_present("h") {
  20. print_usage(&program, opts);
  21. return;
  22. }
  23. let state = 0;
  24. fn adder(v: &mut i64, _: &cborpc::Data) -> Result<cborpc::CallResponse> {
  25. *v += 1;
  26. Ok(cborpc::CallResponse {
  27. success: true,
  28. message: vec![*v as u8],
  29. })
  30. };
  31. let mut responder = cborpc::Responder::new(state);
  32. {
  33. let mut protocol = HashMap::new();
  34. protocol.insert("add1".to_string(), adder as cborpc::CallHandler<i64>);
  35. let protocols = responder.protocols();
  36. protocols.insert("testproto".to_string(), protocol);
  37. }
  38. loop {
  39. let r: Result<()> = match responder.answer_call(&mut std::io::stdin(), &mut std::io::stdout()) {
  40. Ok(success) => {
  41. eprint!("Call answered, success={}", success);
  42. Ok(())
  43. }
  44. Err(error) => Err(error),
  45. };
  46. r.unwrap();
  47. }
  48. }