123456789101112131415161718192021222324252627282930313233343536 |
- // This file provides a Networking trait and a working hyper implementation
- use anyhow::Result;
- 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>) -> Result<Vec<u8>>;
- }
- pub struct HyperNet {
- pub hostname: String,
- }
- #[async_trait]
- impl Networking for HyperNet {
- async fn request(&self, endpoint: String, body: Vec<u8>) -> Result<Vec<u8>> {
- let client = Client::new();
- let url = self.hostname.to_string() + &endpoint;
- let uri: hyper::Uri = url.parse()?;
- // always POST even if body is empty
- let req = Request::builder()
- .method(Method::POST)
- .uri(uri)
- .body(Body::from(body))?;
- let resp = client.request(req).await?;
- let buf = hyper::body::to_bytes(resp).await?;
- Ok(buf.to_vec())
- }
- }
|