1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-10 19:01:05 +00:00

web: add HttpRequest::full_url() (#3096)

* implemented function which returns full uir

* changes added into the changelog

* added test funtion for full_uri method

* refactor: rename to full_url

---------

Co-authored-by: Rob Ede <robjtede@icloud.com>
This commit is contained in:
Timo Caktu 2024-06-10 04:49:50 +02:00 committed by GitHub
parent 2ee92d778e
commit 7a2313cc4b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 56 additions and 0 deletions

View file

@ -2,6 +2,10 @@
## Unreleased
### Added
- Add `HttpRequest::full_url()` method to get the complete URL of the request.
### Fixed
- `ConnectionInfo::realip_remote_addr()` now handles IPv6 addresses from `Forwarded` header correctly. Previously, it sometimes returned the forwarded port as well.

View file

@ -91,6 +91,35 @@ impl HttpRequest {
&self.head().uri
}
/// Returns request's original full URL.
///
/// Reconstructed URL is best-effort, using [`connection_info`](HttpRequest::connection_info())
/// to get forwarded scheme & host.
///
/// ```
/// use actix_web::test::TestRequest;
/// let req = TestRequest::with_uri("http://10.1.2.3:8443/api?id=4&name=foo")
/// .insert_header(("host", "example.com"))
/// .to_http_request();
///
/// assert_eq!(
/// req.full_url().as_str(),
/// "http://example.com/api?id=4&name=foo",
/// );
/// ```
pub fn full_url(&self) -> url::Url {
let info = self.connection_info();
let scheme = info.scheme();
let host = info.host();
let path_and_query = self
.uri()
.path_and_query()
.map(|paq| paq.as_str())
.unwrap_or("/");
url::Url::parse(&format!("{scheme}://{host}{path_and_query}")).unwrap()
}
/// Read the Request method.
#[inline]
pub fn method(&self) -> &Method {
@ -963,4 +992,27 @@ mod tests {
assert!(format!("{:?}", req).contains(location_header));
}
#[test]
fn check_full_url() {
let req = TestRequest::with_uri("/api?id=4&name=foo").to_http_request();
assert_eq!(
req.full_url().as_str(),
"http://localhost:8080/api?id=4&name=foo",
);
let req = TestRequest::with_uri("https://example.com/api?id=4&name=foo").to_http_request();
assert_eq!(
req.full_url().as_str(),
"https://example.com/api?id=4&name=foo",
);
let req = TestRequest::with_uri("http://10.1.2.3:8443/api?id=4&name=foo")
.insert_header(("host", "example.com"))
.to_http_request();
assert_eq!(
req.full_url().as_str(),
"http://example.com/api?id=4&name=foo",
);
}
}