networking.rs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. let buf = hyper::body::to_bytes(resp)
  26. .await
  27. .expect("Failed to concat bytes");
  28. buf.to_vec()
  29. }
  30. }