Skip to main content

ntex/web/
httprequest.rs

1use std::{cell::Ref, cell::RefMut, convert::Infallible, fmt, future, net, rc::Rc};
2
3use urly::Url;
4
5use crate::http::{HeaderMap, HttpMessage, Message, Method, Payload, RequestHead, Version};
6use crate::{Cfg, io::IoRef, io::types, router::Path, util::Extensions};
7
8use super::config::WebAppConfig;
9use super::info::ConnectionInfo;
10use super::rmap::ResourceMap;
11use super::{FromRequest, State};
12
13#[derive(Clone)]
14/// An HTTP Request
15pub struct HttpRequest(pub(crate) Rc<HttpRequestInner>);
16
17pub(crate) struct HttpRequestInner {
18    pub(crate) head: Message<RequestHead>,
19    pub(crate) path: Path<Url>,
20    pub(crate) config: Cfg<WebAppConfig>,
21    pub(crate) rmap: Rc<ResourceMap>,
22}
23
24impl HttpRequest {
25    #[inline]
26    pub(crate) fn new(
27        path: Path<Url>,
28        head: Message<RequestHead>,
29        rmap: Rc<ResourceMap>,
30        config: Cfg<WebAppConfig>,
31    ) -> HttpRequest {
32        HttpRequest(Rc::new(HttpRequestInner {
33            head,
34            path,
35            config,
36            rmap,
37        }))
38    }
39}
40
41impl HttpRequest {
42    /// This method returns reference to the request head
43    #[inline]
44    pub fn head(&self) -> &RequestHead {
45        &self.0.head
46    }
47
48    /// This method returns mutable reference to the request head.
49    /// Panics if multiple references of http request exists.
50    #[inline]
51    pub(crate) fn head_mut(&mut self) -> &mut RequestHead {
52        &mut Rc::get_mut(&mut self.0).unwrap().head
53    }
54
55    /// Request's uri.
56    #[inline]
57    pub fn uri(&self) -> &Url {
58        &self.head().uri
59    }
60
61    /// Read the Request method.
62    #[inline]
63    pub fn method(&self) -> &Method {
64        &self.head().method
65    }
66
67    /// Read the Request Version.
68    #[inline]
69    pub fn version(&self) -> Version {
70        self.head().version
71    }
72
73    #[inline]
74    /// Returns request's headers.
75    pub fn headers(&self) -> &HeaderMap {
76        &self.head().headers
77    }
78
79    /// The target path of this Request.
80    #[inline]
81    pub fn path(&self) -> &str {
82        self.head().uri.path().as_str()
83    }
84
85    /// The query string in the URL.
86    ///
87    /// E.g., id=10
88    #[inline]
89    pub fn query_string(&self) -> &str {
90        self.uri().query().map_or("", urly::Query::as_str)
91    }
92
93    /// Io reference for current connection
94    #[inline]
95    pub fn io(&self) -> Option<&IoRef> {
96        self.head().io.as_ref()
97    }
98
99    /// Peer socket address
100    ///
101    /// Peer address is actual socket address, if proxy is used in front of
102    /// ntex http server, then peer address would be address of this proxy.
103    #[inline]
104    pub fn peer_addr(&self) -> Option<net::SocketAddr> {
105        self.io()
106            .and_then(|io| io.query::<types::PeerAddr>().get().map(|addr| addr.0))
107    }
108
109    /// Get a reference to the Path parameters.
110    ///
111    /// Params is a container for url parameters.
112    /// A variable segment is specified in the form `{identifier}`,
113    /// where the identifier can be used later in a request handler to
114    /// access the matched value for that segment.
115    #[inline]
116    pub fn match_info(&self) -> &Path<Url> {
117        &self.0.path
118    }
119
120    #[inline]
121    pub(crate) fn match_info_mut(&mut self) -> &mut Path<Url> {
122        &mut Rc::get_mut(&mut self.0).unwrap().path
123    }
124
125    /// Request extensions
126    #[inline]
127    pub fn extensions(&self) -> Ref<'_, Extensions> {
128        self.head().extensions()
129    }
130
131    /// Mutable reference to a the request's extensions
132    #[inline]
133    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
134        self.head().extensions_mut()
135    }
136
137    /// Generate url for named resource.
138    ///
139    /// Each element is percent-encoded as one literal URL component before it
140    /// replaces a dynamic segment.
141    ///
142    /// Elements fill the dynamic segments of the enclosing scopes first, then
143    /// of the resource. Each must match the pattern of its segment, for
144    /// example `{id:[0-9]+}`; a segment without a custom pattern accepts any
145    /// non-empty value without a newline, a remainder segment (`{tail}*`)
146    /// accepts any value.
147    ///
148    /// # Errors
149    ///
150    /// - [`ResourceNotFound`](crate::web::error::UrlGenerationError::ResourceNotFound) if no resource has this name.
151    /// - [`NotEnoughElements`](crate::web::error::UrlGenerationError::NotEnoughElements) or
152    ///   [`TooManyElements`](crate::web::error::UrlGenerationError::TooManyElements) if the number of elements
153    ///   differs from the number of dynamic segments.
154    /// - [`InvalidElement`](crate::web::error::UrlGenerationError::InvalidElement) if an element does not
155    ///   match the pattern of its segment.
156    /// - [`ParseError`](crate::web::error::UrlGenerationError::ParseError) if the generated URL is invalid.
157    ///
158    /// ```rust
159    /// # use ntex::web::{self, App, HttpRequest, HttpResponse};
160    /// #
161    /// async fn index(req: HttpRequest) -> HttpResponse {
162    ///     let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
163    ///     HttpResponse::Ok().into()
164    /// }
165    ///
166    /// fn main() {
167    ///     let app = App::default()
168    ///         .service(web::resource("/test/{one}/{two}/{three}")
169    ///              .name("foo")  // <- set resource name, then it could be used in `url_for`
170    ///              .route(web::get().to(index))
171    ///         );
172    /// }
173    /// ```
174    pub fn url_for<U, I>(
175        &self,
176        name: &str,
177        elements: U,
178    ) -> Result<urly::Url, super::error::UrlGenerationError>
179    where
180        U: IntoIterator<Item = I>,
181        I: AsRef<str>,
182    {
183        self.0.rmap.url_for(self, name, elements)
184    }
185
186    /// Generate url for named resource
187    ///
188    /// This method is similar to `HttpRequest::url_for()` but it can be used
189    /// for urls that do not contain variable parts.
190    pub fn url_for_static(
191        &self,
192        name: &str,
193    ) -> Result<urly::Url, super::error::UrlGenerationError> {
194        const NO_PARAMS: [&str; 0] = [];
195        self.url_for(name, NO_PARAMS)
196    }
197
198    #[inline]
199    /// Get a reference to a `ResourceMap` of current application.
200    pub fn resource_map(&self) -> &ResourceMap {
201        &self.0.rmap
202    }
203
204    /// Get *`ConnectionInfo`* for the current request.
205    ///
206    /// Forwarding headers are used as configured by
207    /// [`WebAppConfig::set_forwarded`](crate::web::WebAppConfig::set_forwarded).
208    ///
209    /// This method panics if request's extensions container is already
210    /// borrowed.
211    #[inline]
212    pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> {
213        ConnectionInfo::get(self.head(), &self.0.config)
214    }
215
216    /// App config
217    #[inline]
218    pub fn app_config(&self) -> &WebAppConfig {
219        &self.0.config
220    }
221
222    #[inline]
223    /// Get a configuration value stored with [`WebAppConfig::set_value()`].
224    ///
225    /// This does not read the application state `St`, see
226    /// [`WebAppConfig::set_value()`].
227    pub fn app_value<T: 'static>(&self) -> Option<&T> {
228        self.0.config.value::<T>()
229    }
230
231    #[inline]
232    #[doc(hidden)]
233    #[deprecated(since = "4.7.0", note = "use `HttpRequest::app_value()` instead")]
234    pub fn app_state<T: 'static>(&self) -> Option<&T> {
235        self.app_value()
236    }
237}
238
239impl HttpMessage for HttpRequest {
240    #[inline]
241    /// Returns Request's headers.
242    fn message_headers(&self) -> &HeaderMap {
243        &self.head().headers
244    }
245
246    /// Request extensions
247    #[inline]
248    fn message_extensions(&self) -> Ref<'_, Extensions> {
249        self.0.head.extensions()
250    }
251
252    /// Mutable reference to a the request's extensions
253    #[inline]
254    fn message_extensions_mut(&self) -> RefMut<'_, Extensions> {
255        self.0.head.extensions_mut()
256    }
257}
258
259impl Drop for HttpRequest {
260    fn drop(&mut self) {
261        let id = self.0.config.id();
262        let pool_size = self.0.config.pool_size;
263        super::config::put_request(id, pool_size, &mut self.0);
264    }
265}
266
267/// It is possible to get `HttpRequest` as an extractor handler parameter
268///
269/// ## Example
270///
271/// ```rust
272/// use ntex::web::{self, App, HttpRequest};
273///
274/// /// extract `HttpRequest` from request
275/// async fn index(req: HttpRequest) -> String {
276///    format!("Got thing: {req:?}")
277/// }
278///
279/// fn main() {
280///     let app = App::default().service(
281///         web::resource("/users/{first}").route(
282///             web::get().to(index))
283///     );
284/// }
285/// ```
286impl<St: State> FromRequest<St> for HttpRequest {
287    type Error = Infallible;
288
289    #[inline]
290    fn from_request(
291        _: &St,
292        req: &HttpRequest,
293        _: &mut Payload,
294    ) -> impl Future<Output = Result<Self, Self::Error>> {
295        future::ready(Ok(req.clone()))
296    }
297}
298
299impl fmt::Debug for HttpRequest {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        writeln!(
302            f,
303            "\nHttpRequest {:?} {}:{}",
304            self.0.head.version,
305            self.0.head.method,
306            self.path()
307        )?;
308        if !self.query_string().is_empty() {
309            writeln!(f, "  query: ?{:?}", self.query_string())?;
310        }
311        if !self.match_info().is_empty() {
312            writeln!(f, "  params: {:?}", self.match_info())?;
313        }
314        writeln!(f, "  headers:")?;
315        for (key, val) in self.headers() {
316            writeln!(f, "    {key:?}: {val:?}")?;
317        }
318        Ok(())
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use crate::http::header;
326    use crate::router::ResourceDef;
327    use crate::web::test::TestRequest;
328
329    /// STATEMENT: HTTP request debug formatting supports headers and queries without changing defaults.
330    ///
331    /// HOW:
332    /// - Format requests with a content-type header and a query-bearing URI.
333    /// - Assert both identify `HttpRequest`, and the latter has no peer and uses GET.
334    #[test]
335    fn test_debug() {
336        let req = TestRequest::with_header("content-type", "text/plain").to_http_request();
337        let dbg = format!("{req:?}");
338        assert!(dbg.contains("HttpRequest"));
339
340        let req = TestRequest::with_uri("/index.html?q=?").to_http_request();
341        let dbg = format!("{req:?}");
342        assert!(dbg.contains("HttpRequest"));
343        assert!(req.peer_addr().is_none());
344        assert_eq!(req.method(), &Method::GET);
345    }
346
347    /// STATEMENT: A request without cookie headers yields an empty cookie collection.
348    ///
349    /// HOW:
350    /// - Build the default request and parse its cookies.
351    /// - Assert parsing succeeds and the collection is empty.
352    #[cfg(feature = "cookie")]
353    #[test]
354    fn test_no_request_cookies() {
355        let req = TestRequest::default().to_http_request();
356        assert!(req.cookies().unwrap().is_empty());
357    }
358
359    /// STATEMENT: Multiple cookie headers support ordered parsing and lookup by name.
360    ///
361    /// HOW:
362    /// - Supply two cookie headers and assert both parsed names and values in order.
363    /// - Look up the first cookie and an unknown name, asserting a matching cookie and `None`.
364    #[cfg(feature = "cookie")]
365    #[test]
366    fn test_request_cookies() {
367        let req = TestRequest::default()
368            .header(header::COOKIE, "cookie1=value1")
369            .header(header::COOKIE, "cookie2=value2")
370            .to_http_request();
371        {
372            let cookies = req.cookies().unwrap();
373            assert_eq!(cookies.len(), 2);
374            assert_eq!(cookies[0].name(), "cookie1");
375            assert_eq!(cookies[0].value(), "value1");
376            assert_eq!(cookies[1].name(), "cookie2");
377            assert_eq!(cookies[1].value(), "value2");
378        }
379
380        let cookie = req.cookie("cookie1");
381        assert!(cookie.is_some());
382        let cookie = cookie.unwrap();
383        assert_eq!(cookie.name(), "cookie1");
384        assert_eq!(cookie.value(), "value1");
385
386        let cookie = req.cookie("cookie-unknown");
387        assert!(cookie.is_none());
388    }
389
390    /// STATEMENT: `query_string` exposes the URI query without the leading question mark.
391    ///
392    /// HOW:
393    /// - Build a request for `/?id=test`.
394    /// - Assert the query string is `id=test`.
395    #[test]
396    fn test_request_query() {
397        let req = TestRequest::with_uri("/?id=test").to_http_request();
398        assert_eq!(req.query_string(), "id=test");
399    }
400
401    /// STATEMENT: Named URL generation substitutes parameters and reports missing resources or values.
402    ///
403    /// HOW:
404    /// - Register `/user/{name}.{ext}` and build a request with an explicit host.
405    /// - Assert unknown names and insufficient elements return their specific errors.
406    /// - Supply both elements and assert the complete absolute URL.
407    #[test]
408    fn test_url_for() {
409        let mut res = ResourceDef::new("/user/{name}.{ext}");
410        res.set_name("index");
411
412        let mut rmap = ResourceMap::new(ResourceDef::new(""));
413        rmap.add(&mut res, None);
414        //assert!(rmap.has_resource("/user/test.html"));
415        //assert!(!rmap.has_resource("/test/unknown"));
416
417        let req = TestRequest::with_header(header::HOST, "www.rust-lang.org")
418            .rmap(rmap)
419            .to_http_request();
420
421        assert_eq!(
422            req.url_for("unknown", ["test"]),
423            Err(crate::web::error::UrlGenerationError::ResourceNotFound)
424        );
425        assert_eq!(
426            req.url_for("index", ["test"]),
427            Err(crate::web::error::UrlGenerationError::NotEnoughElements)
428        );
429        let url = req.url_for("index", ["test", "html"]);
430        assert_eq!(
431            url.ok().unwrap().as_str(),
432            "http://www.rust-lang.org/user/test.html"
433        );
434    }
435
436    /// STATEMENT: Static named resources generate absolute URLs using the request host.
437    ///
438    /// HOW:
439    /// - Register `/index.html` as `index` and set the request host.
440    /// - Call `url_for_static` and assert the generated URL points to that host and resource.
441    #[test]
442    fn test_url_for_static() {
443        let mut rdef = ResourceDef::new("/index.html");
444        rdef.set_name("index");
445
446        let mut rmap = ResourceMap::new(ResourceDef::new(""));
447        rmap.add(&mut rdef, None);
448
449        // assert!(rmap.has_resource("/index.html"));
450
451        let req = TestRequest::with_uri("/test")
452            .header(header::HOST, "www.rust-lang.org")
453            .rmap(rmap)
454            .to_http_request();
455        let url = req.url_for_static("index");
456        assert_eq!(
457            url.ok().unwrap().as_str(),
458            "http://www.rust-lang.org/index.html"
459        );
460    }
461
462    /// STATEMENT: External named resources retain their own origin during URL generation.
463    ///
464    /// HOW:
465    /// - Register an external URL template and create a request using its resource map.
466    /// - Substitute the video ID and assert the complete external HTTPS URL.
467    #[test]
468    fn test_url_for_external() {
469        let mut rdef = ResourceDef::new("https://youtube.com/watch/{video_id}");
470
471        rdef.set_name("youtube");
472
473        let mut rmap = ResourceMap::new(ResourceDef::new(""));
474        rmap.add(&mut rdef, None);
475
476        let req = TestRequest::default().rmap(rmap).to_http_request();
477        let url = req.url_for("youtube", ["oHg5SJYRHA0"]);
478        assert_eq!(
479            url.ok().unwrap().as_str(),
480            "https://youtube.com/watch/oHg5SJYRHA0"
481        );
482    }
483}