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