reqwest_middleware/client.rs
1use http::Extensions;
2use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
3use reqwest::{Body, Client, IntoUrl, Method, Request, Response};
4use serde::Serialize;
5use std::convert::TryFrom;
6use std::fmt::{self, Display};
7use std::sync::Arc;
8
9#[cfg(feature = "multipart")]
10use reqwest::multipart;
11
12use crate::error::Result;
13use crate::middleware::{Middleware, Next};
14use crate::RequestInitialiser;
15
16/// A `ClientBuilder` is used to build a [`ClientWithMiddleware`].
17///
18/// [`ClientWithMiddleware`]: crate::ClientWithMiddleware
19pub struct ClientBuilder {
20 client: Client,
21 middleware_stack: Vec<Arc<dyn Middleware>>,
22 initialiser_stack: Vec<Arc<dyn RequestInitialiser>>,
23}
24
25impl ClientBuilder {
26 pub fn new(client: Client) -> Self {
27 ClientBuilder {
28 client,
29 middleware_stack: Vec::new(),
30 initialiser_stack: Vec::new(),
31 }
32 }
33
34 /// This method allows creating a ClientBuilder
35 /// from an existing ClientWithMiddleware instance
36 pub fn from_client(client_with_middleware: ClientWithMiddleware) -> Self {
37 Self {
38 client: client_with_middleware.inner,
39 middleware_stack: client_with_middleware.middleware_stack.into_vec(),
40 initialiser_stack: client_with_middleware.initialiser_stack.into_vec(),
41 }
42 }
43
44 /// Convenience method to attach middleware.
45 ///
46 /// If you need to keep a reference to the middleware after attaching, use [`with_arc`].
47 ///
48 /// [`with_arc`]: Self::with_arc
49 pub fn with<M>(self, middleware: M) -> Self
50 where
51 M: Middleware,
52 {
53 self.with_arc(Arc::new(middleware))
54 }
55
56 /// Add middleware to the chain. [`with`] is more ergonomic if you don't need the `Arc`.
57 ///
58 /// [`with`]: Self::with
59 pub fn with_arc(mut self, middleware: Arc<dyn Middleware>) -> Self {
60 self.middleware_stack.push(middleware);
61 self
62 }
63
64 /// Convenience method to attach a request initialiser.
65 ///
66 /// If you need to keep a reference to the initialiser after attaching, use [`with_arc_init`].
67 ///
68 /// [`with_arc_init`]: Self::with_arc_init
69 pub fn with_init<I>(self, initialiser: I) -> Self
70 where
71 I: RequestInitialiser,
72 {
73 self.with_arc_init(Arc::new(initialiser))
74 }
75
76 /// Add a request initialiser to the chain. [`with_init`] is more ergonomic if you don't need the `Arc`.
77 ///
78 /// [`with_init`]: Self::with_init
79 pub fn with_arc_init(mut self, initialiser: Arc<dyn RequestInitialiser>) -> Self {
80 self.initialiser_stack.push(initialiser);
81 self
82 }
83
84 /// Returns a `ClientWithMiddleware` using this builder configuration.
85 pub fn build(self) -> ClientWithMiddleware {
86 ClientWithMiddleware {
87 inner: self.client,
88 middleware_stack: self.middleware_stack.into_boxed_slice(),
89 initialiser_stack: self.initialiser_stack.into_boxed_slice(),
90 }
91 }
92}
93
94/// `ClientWithMiddleware` is a wrapper around [`reqwest::Client`] which runs middleware on every
95/// request.
96#[derive(Clone, Default)]
97pub struct ClientWithMiddleware {
98 inner: reqwest::Client,
99 middleware_stack: Box<[Arc<dyn Middleware>]>,
100 initialiser_stack: Box<[Arc<dyn RequestInitialiser>]>,
101}
102
103impl ClientWithMiddleware {
104 /// See [`ClientBuilder`] for a more ergonomic way to build `ClientWithMiddleware` instances.
105 pub fn new<T>(client: Client, middleware_stack: T) -> Self
106 where
107 T: Into<Box<[Arc<dyn Middleware>]>>,
108 {
109 ClientWithMiddleware {
110 inner: client,
111 middleware_stack: middleware_stack.into(),
112 // TODO(conradludgate) - allow downstream code to control this manually if desired
113 initialiser_stack: Box::new([]),
114 }
115 }
116
117 /// Convenience method to make a `GET` request to a URL.
118 ///
119 /// # Errors
120 ///
121 /// This method fails whenever the supplied `Url` cannot be parsed.
122 pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
123 self.request(Method::GET, url)
124 }
125
126 /// Convenience method to make a `POST` request to a URL.
127 ///
128 /// # Errors
129 ///
130 /// This method fails whenever the supplied `Url` cannot be parsed.
131 pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
132 self.request(Method::POST, url)
133 }
134
135 /// Convenience method to make a `PUT` request to a URL.
136 ///
137 /// # Errors
138 ///
139 /// This method fails whenever the supplied `Url` cannot be parsed.
140 pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder {
141 self.request(Method::PUT, url)
142 }
143
144 /// Convenience method to make a `PATCH` request to a URL.
145 ///
146 /// # Errors
147 ///
148 /// This method fails whenever the supplied `Url` cannot be parsed.
149 pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder {
150 self.request(Method::PATCH, url)
151 }
152
153 /// Convenience method to make a `DELETE` request to a URL.
154 ///
155 /// # Errors
156 ///
157 /// This method fails whenever the supplied `Url` cannot be parsed.
158 pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
159 self.request(Method::DELETE, url)
160 }
161
162 /// Convenience method to make a `HEAD` request to a URL.
163 ///
164 /// # Errors
165 ///
166 /// This method fails whenever the supplied `Url` cannot be parsed.
167 pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
168 self.request(Method::HEAD, url)
169 }
170
171 /// Start building a `Request` with the `Method` and `Url`.
172 ///
173 /// Returns a `RequestBuilder`, which will allow setting headers and
174 /// the request body before sending.
175 ///
176 /// # Errors
177 ///
178 /// This method fails whenever the supplied `Url` cannot be parsed.
179 pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
180 let req = RequestBuilder {
181 inner: self.inner.request(method, url),
182 extensions: Extensions::new(),
183 middleware_stack: self.middleware_stack.clone(),
184 initialiser_stack: self.initialiser_stack.clone(),
185 };
186 self.initialiser_stack
187 .iter()
188 .fold(req, |req, i| i.init(req))
189 }
190
191 /// Executes a `Request`.
192 ///
193 /// A `Request` can be built manually with `Request::new()` or obtained
194 /// from a RequestBuilder with `RequestBuilder::build()`.
195 ///
196 /// You should prefer to use the `RequestBuilder` and
197 /// `RequestBuilder::send()`.
198 ///
199 /// # Errors
200 ///
201 /// This method fails if there was an error while sending request,
202 /// redirect loop was detected or redirect limit was exhausted.
203 pub async fn execute(&self, req: Request) -> Result<Response> {
204 let mut ext = Extensions::new();
205 self.execute_with_extensions(req, &mut ext).await
206 }
207
208 /// Executes a `Request` with initial [`Extensions`].
209 ///
210 /// A `Request` can be built manually with `Request::new()` or obtained
211 /// from a RequestBuilder with `RequestBuilder::build()`.
212 ///
213 /// You should prefer to use the `RequestBuilder` and
214 /// `RequestBuilder::send()`.
215 ///
216 /// # Errors
217 ///
218 /// This method fails if there was an error while sending request,
219 /// redirect loop was detected or redirect limit was exhausted.
220 pub async fn execute_with_extensions(
221 &self,
222 req: Request,
223 ext: &mut Extensions,
224 ) -> Result<Response> {
225 let next = Next::new(&self.inner, &self.middleware_stack);
226 next.run(req, ext).await
227 }
228}
229
230/// Create a `ClientWithMiddleware` without any middleware.
231impl From<Client> for ClientWithMiddleware {
232 fn from(client: Client) -> Self {
233 ClientWithMiddleware {
234 inner: client,
235 middleware_stack: Box::new([]),
236 initialiser_stack: Box::new([]),
237 }
238 }
239}
240
241impl fmt::Debug for ClientWithMiddleware {
242 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
243 // skipping middleware_stack field for now
244 f.debug_struct("ClientWithMiddleware")
245 .field("inner", &self.inner)
246 .finish_non_exhaustive()
247 }
248}
249
250mod service {
251 use std::{
252 future::Future,
253 pin::Pin,
254 task::{Context, Poll},
255 };
256
257 use crate::Result;
258 use http::Extensions;
259 use reqwest::{Request, Response};
260
261 use crate::{middleware::BoxFuture, ClientWithMiddleware, Next};
262
263 // this is meant to be semi-private, same as reqwest's pending
264 pub struct Pending {
265 inner: BoxFuture<'static, Result<Response>>,
266 }
267
268 impl Unpin for Pending {}
269
270 impl Future for Pending {
271 type Output = Result<Response>;
272
273 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
274 self.inner.as_mut().poll(cx)
275 }
276 }
277
278 impl tower_service::Service<Request> for ClientWithMiddleware {
279 type Response = Response;
280 type Error = crate::Error;
281 type Future = Pending;
282
283 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<()>> {
284 self.inner.poll_ready(cx).map_err(crate::Error::Reqwest)
285 }
286
287 fn call(&mut self, req: Request) -> Self::Future {
288 let inner = self.inner.clone();
289 let middlewares = self.middleware_stack.clone();
290 let mut extensions = Extensions::new();
291 Pending {
292 inner: Box::pin(async move {
293 let next = Next::new(&inner, &middlewares);
294 next.run(req, &mut extensions).await
295 }),
296 }
297 }
298 }
299
300 impl tower_service::Service<Request> for &'_ ClientWithMiddleware {
301 type Response = Response;
302 type Error = crate::Error;
303 type Future = Pending;
304
305 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<()>> {
306 (&self.inner).poll_ready(cx).map_err(crate::Error::Reqwest)
307 }
308
309 fn call(&mut self, req: Request) -> Self::Future {
310 let inner = self.inner.clone();
311 let middlewares = self.middleware_stack.clone();
312 let mut extensions = Extensions::new();
313 Pending {
314 inner: Box::pin(async move {
315 let next = Next::new(&inner, &middlewares);
316 next.run(req, &mut extensions).await
317 }),
318 }
319 }
320 }
321}
322
323/// This is a wrapper around [`reqwest::RequestBuilder`] exposing the same API.
324#[must_use = "RequestBuilder does nothing until you 'send' it"]
325pub struct RequestBuilder {
326 inner: reqwest::RequestBuilder,
327 middleware_stack: Box<[Arc<dyn Middleware>]>,
328 initialiser_stack: Box<[Arc<dyn RequestInitialiser>]>,
329 extensions: Extensions,
330}
331
332impl RequestBuilder {
333 /// Assemble a builder starting from an existing `Client` and a `Request`.
334 pub fn from_parts(client: ClientWithMiddleware, request: Request) -> RequestBuilder {
335 let inner = reqwest::RequestBuilder::from_parts(client.inner, request);
336 RequestBuilder {
337 inner,
338 middleware_stack: client.middleware_stack,
339 initialiser_stack: client.initialiser_stack,
340 extensions: Extensions::new(),
341 }
342 }
343
344 /// Add a `Header` to this Request.
345 pub fn header<K, V>(self, key: K, value: V) -> Self
346 where
347 HeaderName: TryFrom<K>,
348 <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
349 HeaderValue: TryFrom<V>,
350 <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
351 {
352 RequestBuilder {
353 inner: self.inner.header(key, value),
354 ..self
355 }
356 }
357
358 /// Add a set of Headers to the existing ones on this Request.
359 ///
360 /// The headers will be merged in to any already set.
361 pub fn headers(self, headers: HeaderMap) -> Self {
362 RequestBuilder {
363 inner: self.inner.headers(headers),
364 ..self
365 }
366 }
367
368 #[cfg(not(target_arch = "wasm32"))]
369 pub fn version(self, version: reqwest::Version) -> Self {
370 RequestBuilder {
371 inner: self.inner.version(version),
372 ..self
373 }
374 }
375
376 /// Enable HTTP basic authentication.
377 ///
378 /// ```rust
379 /// # use anyhow::Error;
380 ///
381 /// # async fn run() -> Result<(), Error> {
382 /// let client = reqwest_middleware::ClientWithMiddleware::from(reqwest::Client::new());
383 /// let resp = client.delete("http://httpbin.org/delete")
384 /// .basic_auth("admin", Some("good password"))
385 /// .send()
386 /// .await?;
387 /// # Ok(())
388 /// # }
389 /// ```
390 pub fn basic_auth<U, P>(self, username: U, password: Option<P>) -> Self
391 where
392 U: Display,
393 P: Display,
394 {
395 RequestBuilder {
396 inner: self.inner.basic_auth(username, password),
397 ..self
398 }
399 }
400
401 /// Enable HTTP bearer authentication.
402 pub fn bearer_auth<T>(self, token: T) -> Self
403 where
404 T: Display,
405 {
406 RequestBuilder {
407 inner: self.inner.bearer_auth(token),
408 ..self
409 }
410 }
411
412 /// Set the request body.
413 pub fn body<T: Into<Body>>(self, body: T) -> Self {
414 RequestBuilder {
415 inner: self.inner.body(body),
416 ..self
417 }
418 }
419
420 /// Enables a request timeout.
421 ///
422 /// The timeout is applied from when the request starts connecting until the
423 /// response body has finished. It affects only this request and overrides
424 /// the timeout configured using `ClientBuilder::timeout()`.
425 pub fn timeout(self, timeout: std::time::Duration) -> Self {
426 RequestBuilder {
427 inner: self.inner.timeout(timeout),
428 ..self
429 }
430 }
431
432 #[cfg(feature = "multipart")]
433 #[cfg_attr(docsrs, doc(cfg(feature = "multipart")))]
434 pub fn multipart(self, multipart: multipart::Form) -> Self {
435 RequestBuilder {
436 inner: self.inner.multipart(multipart),
437 ..self
438 }
439 }
440
441 /// Modify the query string of the URL.
442 ///
443 /// Modifies the URL of this request, adding the parameters provided.
444 /// This method appends and does not overwrite. This means that it can
445 /// be called multiple times and that existing query parameters are not
446 /// overwritten if the same key is used. The key will simply show up
447 /// twice in the query string.
448 /// Calling `.query(&[("foo", "a"), ("foo", "b")])` gives `"foo=a&foo=b"`.
449 ///
450 /// # Note
451 /// This method does not support serializing a single key-value
452 /// pair. Instead of using `.query(("key", "val"))`, use a sequence, such
453 /// as `.query(&[("key", "val")])`. It's also possible to serialize structs
454 /// and maps into a key-value pair.
455 ///
456 /// # Errors
457 /// This method will fail if the object you provide cannot be serialized
458 /// into a query string.
459 pub fn query<T: Serialize + ?Sized>(self, query: &T) -> Self {
460 RequestBuilder {
461 inner: self.inner.query(query),
462 ..self
463 }
464 }
465
466 /// Send a form body.
467 ///
468 /// Sets the body to the url encoded serialization of the passed value,
469 /// and also sets the `Content-Type: application/x-www-form-urlencoded`
470 /// header.
471 ///
472 /// ```rust
473 /// # use anyhow::Error;
474 /// # use std::collections::HashMap;
475 /// #
476 /// # async fn run() -> Result<(), Error> {
477 /// let mut params = HashMap::new();
478 /// params.insert("lang", "rust");
479 ///
480 /// let client = reqwest_middleware::ClientWithMiddleware::from(reqwest::Client::new());
481 /// let res = client.post("http://httpbin.org")
482 /// .form(¶ms)
483 /// .send()
484 /// .await?;
485 /// # Ok(())
486 /// # }
487 /// ```
488 ///
489 /// # Errors
490 ///
491 /// This method fails if the passed value cannot be serialized into
492 /// url encoded format
493 pub fn form<T: Serialize + ?Sized>(self, form: &T) -> Self {
494 RequestBuilder {
495 inner: self.inner.form(form),
496 ..self
497 }
498 }
499
500 /// Send a JSON body.
501 ///
502 /// # Optional
503 ///
504 /// This requires the optional `json` feature enabled.
505 ///
506 /// # Errors
507 ///
508 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
509 /// fail, or if `T` contains a map with non-string keys.
510 #[cfg(feature = "json")]
511 #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
512 pub fn json<T: Serialize + ?Sized>(self, json: &T) -> Self {
513 RequestBuilder {
514 inner: self.inner.json(json),
515 ..self
516 }
517 }
518
519 /// Disable CORS on fetching the request.
520 ///
521 /// # WASM
522 ///
523 /// This option is only effective with WebAssembly target.
524 ///
525 /// The [request mode][mdn] will be set to 'no-cors'.
526 ///
527 /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
528 pub fn fetch_mode_no_cors(self) -> Self {
529 RequestBuilder {
530 inner: self.inner.fetch_mode_no_cors(),
531 ..self
532 }
533 }
534
535 /// Build a `Request`, which can be inspected, modified and executed with
536 /// `ClientWithMiddleware::execute()`.
537 pub fn build(self) -> reqwest::Result<Request> {
538 self.inner.build()
539 }
540
541 /// Build a `Request`, which can be inspected, modified and executed with
542 /// `ClientWithMiddleware::execute()`.
543 ///
544 /// This is similar to [`RequestBuilder::build()`], but also returns the
545 /// embedded `Client`.
546 pub fn build_split(self) -> (ClientWithMiddleware, reqwest::Result<Request>) {
547 let Self {
548 inner,
549 middleware_stack,
550 initialiser_stack,
551 ..
552 } = self;
553 let (inner, req) = inner.build_split();
554 let client = ClientWithMiddleware {
555 inner,
556 middleware_stack,
557 initialiser_stack,
558 };
559 (client, req)
560 }
561
562 /// Inserts the extension into this request builder
563 pub fn with_extension<T: Send + Sync + Clone + 'static>(mut self, extension: T) -> Self {
564 self.extensions.insert(extension);
565 self
566 }
567
568 /// Returns a mutable reference to the internal set of extensions for this request
569 pub fn extensions(&mut self) -> &mut Extensions {
570 &mut self.extensions
571 }
572
573 /// Constructs the Request and sends it to the target URL, returning a
574 /// future Response.
575 ///
576 /// # Errors
577 ///
578 /// This method fails if there was an error while sending request,
579 /// redirect loop was detected or redirect limit was exhausted.
580 ///
581 /// # Example
582 ///
583 /// ```no_run
584 /// # use anyhow::Error;
585 /// #
586 /// # async fn run() -> Result<(), Error> {
587 /// let response = reqwest_middleware::ClientWithMiddleware::from(reqwest::Client::new())
588 /// .get("https://hyper.rs")
589 /// .send()
590 /// .await?;
591 /// # Ok(())
592 /// # }
593 /// ```
594 pub async fn send(mut self) -> Result<Response> {
595 let mut extensions = std::mem::take(self.extensions());
596 let (client, req) = self.build_split();
597 client.execute_with_extensions(req?, &mut extensions).await
598 }
599
600 /// Attempt to clone the RequestBuilder.
601 ///
602 /// `None` is returned if the RequestBuilder can not be cloned,
603 /// i.e. if the request body is a stream.
604 ///
605 /// # Examples
606 ///
607 /// ```
608 /// # use reqwest::Error;
609 /// #
610 /// # fn run() -> Result<(), Error> {
611 /// let client = reqwest_middleware::ClientWithMiddleware::from(reqwest::Client::new());
612 /// let builder = client.post("http://httpbin.org/post")
613 /// .body("from a &str!");
614 /// let clone = builder.try_clone();
615 /// assert!(clone.is_some());
616 /// # Ok(())
617 /// # }
618 /// ```
619 pub fn try_clone(&self) -> Option<Self> {
620 self.inner.try_clone().map(|inner| RequestBuilder {
621 inner,
622 middleware_stack: self.middleware_stack.clone(),
623 initialiser_stack: self.initialiser_stack.clone(),
624 extensions: self.extensions.clone(),
625 })
626 }
627}
628
629impl fmt::Debug for RequestBuilder {
630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631 // skipping middleware_stack field for now
632 f.debug_struct("RequestBuilder")
633 .field("inner", &self.inner)
634 .finish_non_exhaustive()
635 }
636}