1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use hyper::body::Bytes;
use hyper::{Client as HyperClient, Method, Request, Body, body::HttpBody};
use hyperlocal::{UnixConnector, Uri};
use tokio::runtime::Runtime;

pub struct SimpleResponse {
    pub status: u16,
    pub body: Bytes,
}

impl Default for SimpleResponse {
    fn default() -> Self {
        SimpleResponse {
            status: 0,
            body: Bytes::new(),
        }
    }
}

pub fn request(client: &HyperClient<UnixConnector>, socket: String, url: String, method: Method, body: String, runtime: &Runtime) -> Result<SimpleResponse, Box<dyn std::error::Error + Send + Sync>> {
    runtime.block_on(async {
        let uri = Uri::new(&socket, &url);
        let body = Body::from(body);

        let req = Request::builder()
            .method(method)
            .uri(uri)
            .header("Content-Type", "application/json")
            .body(body)?
            .into();

        let mut response = client.request(req).await?; 
        while let Some(next) = response.data().await {
            let chunk = next?;

            let simple = SimpleResponse {
                status: response.status().as_u16(),
                body: chunk,
            };

            return Ok(simple);
        }

        Ok(SimpleResponse {
            status: response.status().as_u16().into(),
            body: Bytes::new(),
        })
    })
}