rocket_community/local/blocking/
request.rs

1use std::fmt;
2
3use rocket_http::HttpVersion;
4
5use crate::http::uri::Origin;
6use crate::{http::Method, local::asynchronous, Request};
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/// # extern crate rocket_community as rocket;
21/// use rocket::local::blocking::{Client, LocalRequest};
22/// use rocket::http::{ContentType, Cookie};
23///
24/// let client = Client::tracked(rocket::build()).expect("valid rocket");
25/// let req = client.post("/")
26///     .header(ContentType::JSON)
27///     .remote("127.0.0.1:8000")
28///     .cookie(("name", "value"))
29///     .body(r#"{ "value": 42 }"#);
30///
31/// let response = req.dispatch();
32/// ```
33#[derive(Clone)]
34pub struct LocalRequest<'c> {
35    inner: asynchronous::LocalRequest<'c>,
36    client: &'c Client,
37}
38
39impl<'c> LocalRequest<'c> {
40    #[inline]
41    pub(crate) fn new<'u: 'c, U>(client: &'c Client, method: Method, uri: U) -> Self
42    where
43        U: TryInto<Origin<'u>> + fmt::Display,
44    {
45        let inner = asynchronous::LocalRequest::new(client.inner(), method, uri);
46        Self { inner, client }
47    }
48
49    #[inline]
50    pub fn override_version(&mut self, version: HttpVersion) {
51        self.inner.override_version(version);
52    }
53
54    #[inline]
55    fn _request(&self) -> &Request<'c> {
56        self.inner._request()
57    }
58
59    #[inline]
60    fn _request_mut(&mut self) -> &mut Request<'c> {
61        self.inner._request_mut()
62    }
63
64    fn _body_mut(&mut self) -> &mut Vec<u8> {
65        self.inner._body_mut()
66    }
67
68    fn _dispatch(self) -> LocalResponse<'c> {
69        let inner = self.client.block_on(self.inner.dispatch());
70        LocalResponse {
71            inner,
72            client: self.client,
73        }
74    }
75
76    pub_request_impl!(
77        "# use rocket::local::blocking::Client;\n\
78        use rocket::local::blocking::LocalRequest;"
79    );
80}
81
82impl std::fmt::Debug for LocalRequest<'_> {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        self._request().fmt(f)
85    }
86}
87
88impl<'c> std::ops::Deref for LocalRequest<'c> {
89    type Target = Request<'c>;
90
91    fn deref(&self) -> &Self::Target {
92        self.inner()
93    }
94}
95
96impl<'c> std::ops::DerefMut for LocalRequest<'c> {
97    fn deref_mut(&mut self) -> &mut Self::Target {
98        self.inner_mut()
99    }
100}