networking.rs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // This file provides a Networking trait and a working hyper implementation
  2. use async_trait::async_trait;
  3. use hyper::{Body, Client, Method, Request};
  4. // provides a generic way to make network requests
  5. #[async_trait]
  6. pub trait Networking {
  7. async fn request(&self, endpoint: String, body: Vec<u8>) -> Vec<u8>;
  8. }
  9. pub struct HyperNet {
  10. pub hostname: String,
  11. }
  12. #[async_trait]
  13. impl Networking for HyperNet {
  14. async fn request(&self, endpoint: String, body: Vec<u8>) -> Vec<u8> {
  15. let client = Client::new();
  16. let url = self.hostname.to_string() + &endpoint;
  17. let uri: hyper::Uri = url.parse().expect("Failed to parse URL");
  18. // always POST even if body is empty
  19. let req = Request::builder()
  20. .method(Method::POST)
  21. .uri(uri)
  22. .body(Body::from(body))
  23. .expect("Failed to create POST request");
  24. let resp = client.request(req).await.expect("Failed to POST");
  25. println!("Response: {}", resp.status());
  26. let buf = hyper::body::to_bytes(resp)
  27. .await
  28. .expect("Failed to concat bytes");
  29. buf.to_vec()
  30. }
  31. }