@@ -5,46 +5,50 @@ use futures_util::stream::TryStreamExt;
5
5
use http_types:: headers:: { HeaderName , HeaderValue } ;
6
6
use http_types:: StatusCode ;
7
7
use hyper:: body:: HttpBody ;
8
+ use hyper:: client:: connect:: Connect ;
9
+ use hyper:: client:: HttpConnector ;
8
10
use hyper_tls:: HttpsConnector ;
9
11
use std:: convert:: TryFrom ;
12
+ use std:: fmt:: Debug ;
10
13
use std:: io;
11
14
use std:: str:: FromStr ;
15
+ use std:: sync:: Arc ;
12
16
13
17
/// Hyper-based HTTP Client.
14
- #[ derive( Debug ) ]
15
- pub struct HyperClient { }
18
+ #[ derive( Clone , Debug ) ]
19
+ pub struct HyperClient < C : Clone + Connect + Debug + Send + Sync + ' static > ( Arc < hyper :: Client < C > > ) ;
16
20
17
- impl HyperClient {
18
- /// Create a new client.
19
- ///
20
- /// There is no specific benefit to reusing instances of this client.
21
+ impl HyperClient < HttpsConnector < HttpConnector > > {
22
+ /// Create a new client instance.
21
23
pub fn new ( ) -> Self {
22
- HyperClient { }
24
+ let https = HttpsConnector :: new ( ) ;
25
+ let client = hyper:: Client :: builder ( ) . build ( https) ;
26
+ Self ( Arc :: new ( client) )
27
+ }
28
+ }
29
+
30
+ impl < C : Clone + Connect + Debug + Send + Sync + ' static > HyperClient < C > {
31
+ /// Create from externally initialized and configured client.
32
+ pub fn from_client ( client : hyper:: Client < C > ) -> Self {
33
+ Self ( Arc :: new ( client) )
34
+ }
35
+ }
36
+
37
+ impl Default for HyperClient < HttpsConnector < HttpConnector > > {
38
+ fn default ( ) -> Self {
39
+ Self :: new ( )
23
40
}
24
41
}
25
42
26
43
#[ async_trait]
27
- impl HttpClient for HyperClient {
44
+ impl < C : Clone + Connect + Debug + Send + Sync + ' static > HttpClient for HyperClient < C > {
28
45
async fn send ( & self , req : Request ) -> Result < Response , Error > {
29
46
let req = HyperHttpRequest :: try_from ( req) . await ?. into_inner ( ) ;
30
- // UNWRAP: Scheme guaranteed to be "http" or "https" as part of conversion
31
- let scheme = req. uri ( ) . scheme_str ( ) . unwrap ( ) ;
32
47
33
- let response = match scheme {
34
- "http" => {
35
- let client = hyper:: Client :: builder ( ) . build_http :: < hyper:: Body > ( ) ;
36
- client. request ( req) . await
37
- }
38
- "https" => {
39
- let https = HttpsConnector :: new ( ) ;
40
- let client = hyper:: Client :: builder ( ) . build :: < _ , hyper:: Body > ( https) ;
41
- client. request ( req) . await
42
- }
43
- _ => unreachable ! ( ) ,
44
- } ?;
48
+ let response = self . 0 . request ( req) . await ?;
45
49
46
- let resp = HttpTypesResponse :: try_from ( response) . await ?. into_inner ( ) ;
47
- Ok ( resp )
50
+ let res = HttpTypesResponse :: try_from ( response) . await ?. into_inner ( ) ;
51
+ Ok ( res )
48
52
}
49
53
}
50
54
0 commit comments