11use itertools:: Itertools ;
22use reqwest:: { Client , ClientBuilder , Response } ;
3- use reqwest_middleware:: ClientWithMiddleware ;
3+ use reqwest_middleware:: { ClientWithMiddleware , Middleware } ;
44use reqwest_retry:: policies:: ExponentialBackoff ;
55use reqwest_retry:: {
66 DefaultRetryableStrategy , RetryTransientMiddleware , Retryable , RetryableStrategy ,
77} ;
88use std:: error:: Error ;
99use std:: fmt:: Debug ;
1010use std:: path:: Path ;
11+ use std:: sync:: Arc ;
1112use std:: time:: Duration ;
1213use std:: { env, iter} ;
1314use tracing:: debug;
@@ -54,6 +55,19 @@ pub struct BaseClientBuilder<'a> {
5455 platform : Option < & ' a Platform > ,
5556 auth_integration : AuthIntegration ,
5657 default_timeout : Duration ,
58+ extra_middleware : Option < ExtraMiddleware > ,
59+ }
60+
61+ /// A list of user-defined middlewares to be applied to the client.
62+ #[ derive( Clone ) ]
63+ pub struct ExtraMiddleware ( pub Vec < Arc < dyn Middleware > > ) ;
64+
65+ impl Debug for ExtraMiddleware {
66+ fn fmt ( & self , f : & mut std:: fmt:: Formatter < ' _ > ) -> std:: fmt:: Result {
67+ f. debug_struct ( "ExtraMiddleware" )
68+ . field ( "0" , & format ! ( "{} middlewares" , self . 0 . len( ) ) )
69+ . finish ( )
70+ }
5771}
5872
5973impl Default for BaseClientBuilder < ' _ > {
@@ -75,6 +89,7 @@ impl BaseClientBuilder<'_> {
7589 platform : None ,
7690 auth_integration : AuthIntegration :: default ( ) ,
7791 default_timeout : Duration :: from_secs ( 30 ) ,
92+ extra_middleware : None ,
7893 }
7994 }
8095}
@@ -140,6 +155,12 @@ impl<'a> BaseClientBuilder<'a> {
140155 self
141156 }
142157
158+ #[ must_use]
159+ pub fn extra_middleware ( mut self , middleware : ExtraMiddleware ) -> Self {
160+ self . extra_middleware = Some ( middleware) ;
161+ self
162+ }
163+
143164 pub fn is_offline ( & self ) -> bool {
144165 matches ! ( self . connectivity, Connectivity :: Offline )
145166 }
@@ -313,6 +334,13 @@ impl<'a> BaseClientBuilder<'a> {
313334 }
314335 }
315336
337+ // When supplied add the extra middleware
338+ if let Some ( extra_middleware) = & self . extra_middleware {
339+ for middleware in & extra_middleware. 0 {
340+ client = client. with_arc ( middleware. clone ( ) ) ;
341+ }
342+ }
343+
316344 client. build ( )
317345 }
318346 Connectivity :: Offline => reqwest_middleware:: ClientBuilder :: new ( client)
0 commit comments