networking.rs 975 B

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