http.rs

 1use futures::future::BoxFuture;
 2use isahc::{
 3    config::{Configurable, RedirectPolicy},
 4    AsyncBody,
 5};
 6use std::sync::Arc;
 7
 8pub use anyhow::{anyhow, Result};
 9pub use isahc::{
10    http::{Method, Uri},
11    Error,
12};
13pub use url::Url;
14
15pub type Request = isahc::Request<AsyncBody>;
16pub type Response = isahc::Response<AsyncBody>;
17
18pub trait HttpClient: Send + Sync {
19    fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response, Error>>;
20
21    fn get<'a>(&'a self, uri: &str, body: AsyncBody) -> BoxFuture<'a, Result<Response, Error>> {
22        self.send(
23            isahc::Request::builder()
24                .method(Method::GET)
25                .uri(uri)
26                .body(body)
27                .unwrap(),
28        )
29    }
30}
31
32pub fn client() -> Arc<dyn HttpClient> {
33    Arc::new(
34        isahc::HttpClient::builder()
35            .redirect_policy(RedirectPolicy::Follow)
36            .build()
37            .unwrap(),
38    )
39}
40
41impl HttpClient for isahc::HttpClient {
42    fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response, Error>> {
43        Box::pin(async move { self.send_async(req).await })
44    }
45}