From b76b054118f29aa8ab31722831518398b3b7f40d Mon Sep 17 00:00:00 2001 From: Ferris Tseng Date: Sun, 4 Apr 2021 18:50:07 -0400 Subject: make HyperBackend generic --- ipfs-api-backend-hyper/src/backend.rs | 56 ++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 21 deletions(-) (limited to 'ipfs-api-backend-hyper') diff --git a/ipfs-api-backend-hyper/src/backend.rs b/ipfs-api-backend-hyper/src/backend.rs index 01e30de..c496de6 100644 --- a/ipfs-api-backend-hyper/src/backend.rs +++ b/ipfs-api-backend-hyper/src/backend.rs @@ -17,40 +17,54 @@ use http::{ }; use hyper::{ body, - client::{self, Builder, HttpConnector}, + client::{self, Builder, connect::Connect, HttpConnector}, }; -use hyper_tls::HttpsConnector; use ipfs_api_prelude::{ApiRequest, Backend, TryFromUri}; use multipart::client::multipart; use serde::Serialize; -pub struct HyperBackend { +pub struct HyperBackend where C: Connect + Clone + Send + Sync + 'static { base: Uri, - client: client::Client, hyper::Body>, + client: client::Client, } -impl Default for HyperBackend { - /// Creates an `IpfsClient` connected to the endpoint specified in ~/.ipfs/api. - /// If not found, tries to connect to `localhost:5001`. - /// - fn default() -> Self { - Self::from_ipfs_config() - .unwrap_or_else(|| Self::from_host_and_port(Scheme::HTTP, "localhost", 5001).unwrap()) - } +macro_rules! impl_default { + ($http_connector:path) => { + impl_default!($http_connector, <$http_connector>::new()); + }; + ($http_connector:path, $constructor:expr) => { + impl Default for HyperBackend<$http_connector> { + /// Creates an `IpfsClient` connected to the endpoint specified in ~/.ipfs/api. + /// If not found, tries to connect to `localhost:5001`. + /// + fn default() -> Self { + Self::from_ipfs_config() + .unwrap_or_else(|| Self::from_host_and_port(Scheme::HTTP, "localhost", 5001).unwrap()) + } + } + + impl TryFromUri for HyperBackend<$http_connector> { + fn build_with_base_uri(base: Uri) -> Self { + let client = Builder::default() + .pool_max_idle_per_host(0) + .build($constructor); + + HyperBackend { base, client } + } + } + }; } -impl TryFromUri for HyperBackend { - fn build_with_base_uri(base: Uri) -> Self { - let client = Builder::default() - .pool_max_idle_per_host(0) - .build(HttpsConnector::new()); +impl_default!(HttpConnector); - HyperBackend { base, client } - } -} +#[cfg(feature = "with-hyper-tls")] +impl_default!(hyper_tls::HttpsConnector); + +#[cfg(feature = "with-hyper-rustls")] +impl_default!(hyper_rustls::HttpsConnector, hyper_rustls::HttpsConnector::with_native_roots()); #[async_trait(?Send)] -impl Backend for HyperBackend { +impl Backend for HyperBackend where C: Connect + Clone + Send + Sync + 'static { type HttpRequest = http::Request; type HttpResponse = http::Response; -- cgit v1.2.3