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
50
51
52
53
54
55
56
//! http-client implementation for isahc

use super::{Body, HttpClient, Request, Response};

use futures::future::BoxFuture;

use std::sync::Arc;

/// Curl-based HTTP Client.
#[derive(Debug)]
pub struct IsahcClient {
    client: Arc<isahc::HttpClient>,
}

impl Default for IsahcClient {
    fn default() -> Self {
        Self::new()
    }
}

impl IsahcClient {
    /// Create a new instance.
    pub fn new() -> Self {
        Self {
            client: Arc::new(isahc::HttpClient::new().unwrap()),
        }
    }
}

impl Clone for IsahcClient {
    fn clone(&self) -> Self {
        Self {
            client: self.client.clone(),
        }
    }
}

impl HttpClient for IsahcClient {
    type Error = isahc::Error;

    fn send(&self, req: Request) -> BoxFuture<'static, Result<Response, Self::Error>> {
        let client = self.client.clone();
        Box::pin(async move {
            let (parts, body) = req.into_parts();
            let body = isahc::Body::reader(body);
            let req: http::Request<isahc::Body> = http::Request::from_parts(parts, body);

            let res = client.send_async(req).await?;

            let (parts, body) = res.into_parts();
            let body = Body::from_reader(body);
            let res = http::Response::from_parts(parts, body);
            Ok(res)
        })
    }
}