rocket/local/blocking/
request.rs

1use std::fmt;
2
3use crate::{Request, http::Method, local::asynchronous};
4use crate::http::uri::Origin;
5
6use super::{Client, LocalResponse};
7
8/// A `blocking` local request as returned by [`Client`](super::Client).
9///
10/// For details, see [the top-level documentation](../index.html#localrequest).
11///
12/// ## Example
13///
14/// The following snippet uses the available builder methods to construct and
15/// dispatch a `POST` request to `/` with a JSON body:
16///
17/// ```rust,no_run
18/// use rocket::local::blocking::{Client, LocalRequest};
19/// use rocket::http::{ContentType, Cookie};
20///
21/// let client = Client::tracked(rocket::build()).expect("valid rocket");
22/// let req = client.post("/")
23///     .header(ContentType::JSON)
24///     .remote("127.0.0.1:8000".parse().unwrap())
25///     .cookie(("name", "value"))
26///     .body(r#"{ "value": 42 }"#);
27///
28/// let response = req.dispatch();
29/// ```
30#[derive(Clone)]
31pub struct LocalRequest<'c> {
32    inner: asynchronous::LocalRequest<'c>,
33    client: &'c Client,
34}
35
36impl<'c> LocalRequest<'c> {
37    #[inline]
38    pub(crate) fn new<'u: 'c, U>(client: &'c Client, method: Method, uri: U) -> Self
39        where U: TryInto<Origin<'u>> + fmt::Display
40    {
41        let inner = asynchronous::LocalRequest::new(client.inner(), method, uri);
42        Self { inner, client }
43    }
44
45    #[inline]
46    fn _request(&self) -> &Request<'c> {
47        self.inner._request()
48    }
49
50    #[inline]
51    fn _request_mut(&mut self) -> &mut Request<'c> {
52        self.inner._request_mut()
53    }
54
55    fn _body_mut(&mut self) -> &mut Vec<u8> {
56        self.inner._body_mut()
57    }
58
59    fn _dispatch(self) -> LocalResponse<'c> {
60        let inner = self.client.block_on(self.inner.dispatch());
61        LocalResponse { inner, client: self.client }
62    }
63
64    pub_request_impl!("# use rocket::local::blocking::Client;\n\
65        use rocket::local::blocking::LocalRequest;");
66}
67
68impl std::fmt::Debug for LocalRequest<'_> {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        self._request().fmt(f)
71    }
72}
73
74impl<'c> std::ops::Deref for LocalRequest<'c> {
75    type Target = Request<'c>;
76
77    fn deref(&self) -> &Self::Target {
78        self.inner()
79    }
80}
81
82impl<'c> std::ops::DerefMut for LocalRequest<'c> {
83    fn deref_mut(&mut self) -> &mut Self::Target {
84        self.inner_mut()
85    }
86}