rocket/local/blocking/
request.rs

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