Skip to content

Commit

Permalink
web: add HttpRequest::full_url() (#3096)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
TimoCak and robjtede authored Jun 10, 2024
1 parent 2ee92d7 commit 7a2313c
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
4 changes: 4 additions & 0 deletions actix-web/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
52 changes: 52 additions & 0 deletions actix-web/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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",
);
}
}

0 comments on commit 7a2313c

Please sign in to comment.