12345678910111213141516171819202122232425262728293031323334353637383940 |
- // This file provides a Networking trait and a working hyper implementation
- use async_trait::async_trait;
- use hyper::{Body, Client, Method, Request};
- // provides a generic way to make network requests
- #[async_trait]
- pub trait Networking {
- async fn request(&self, endpoint: String, body: Vec<u8>) -> Vec<u8>;
- }
- pub struct HyperNet {
- pub hostname: String,
- }
- #[async_trait]
- impl Networking for HyperNet {
- async fn request(&self, endpoint: String, body: Vec<u8>) -> Vec<u8> {
- let client = Client::new();
- let url = self.hostname.to_string() + &endpoint;
- let uri: hyper::Uri = url.parse().expect("Failed to parse URL");
- // always POST even if body is empty
- let req = Request::builder()
- .method(Method::POST)
- .uri(uri)
- .body(Body::from(body))
- .expect("Failed to create POST request");
- let resp = client.request(req).await.expect("Failed to POST");
- println!("Response: {}", resp.status());
- let buf = hyper::body::to_bytes(resp)
- .await
- .expect("Failed to concat bytes");
- buf.to_vec()
- }
- }
|