Skip to content

Commit

Permalink
[OPTIMIZATION] https redirectior
Browse files Browse the repository at this point in the history
  • Loading branch information
ismoilovdevml committed Oct 15, 2023
1 parent ad26fea commit 02d8c20
Showing 1 changed file with 32 additions and 29 deletions.
61 changes: 32 additions & 29 deletions src/middleware/https_redirector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,42 +22,45 @@ impl Middleware for HttpsRedirector {
request: Request<Body>,
context: &Context<'_>,
) -> Result<Request<Body>, Response<Body>> {
match context.client_scheme {
server::Scheme::HTTP => {
let host_authority = parse_host_header(&request)?;
if let server::Scheme::HTTP = context.client_scheme {
let host_authority = parse_host_header(&request)?;

let (parts, _body) = request.into_parts();
let uri_parts = parts.uri.into_parts();
let authority = uri_parts.authority.unwrap_or(host_authority);
let path_and_query = uri_parts.path_and_query.ok_or_else(internal_server_error)?;
let https_uri = Uri::builder()
.scheme(Scheme::HTTPS)
.authority(authority)
.path_and_query(path_and_query)
.build()
.map_err(handle_internal_server_error)?;
let (parts, _body) = request.into_parts();
let uri_parts = parts.uri.into_parts();
let authority = uri_parts.authority.unwrap_or(host_authority);
let path_and_query = uri_parts.path_and_query.ok_or_else(internal_server_error)?;
let https_uri = Uri::builder()
.scheme(Scheme::HTTPS)
.authority(authority)
.path_and_query(path_and_query)
.build()
.map_err(handle_internal_server_error)?;

let response = Response::builder()
debug!("Redirecting to {}", https_uri);

return Err(
Response::builder()
.status(StatusCode::MOVED_PERMANENTLY)
.header(LOCATION, https_uri.to_string())
.body(Body::empty())
.map_err(handle_internal_server_error)?;

debug!("Redirecting to {}", https_uri);

Err(response)
}
_ => Ok(request),
.map_err(handle_internal_server_error)?
);
}

Ok(request)
}
}

fn parse_host_header(request: &Request<Body>) -> Result<Authority, Response<Body>> {
let host = request
.headers()
.get(HOST)
.ok_or_else(|| bad_request("missing host header"))?
.to_str()
.map_err(|error| bad_request(error.to_string()))?;
Authority::try_from(host).map_err(|_error| bad_request("invalid host header"))
}
request
.headers()
.get(HOST)
.ok_or_else(|| bad_request("Missing Host header".to_string()))
.and_then(|host| {
host.to_str()
.map_err(|_| bad_request("Failed to parse Host header".to_string()))
})
.and_then(|host_str| {
Authority::try_from(host_str).map_err(|_| bad_request("Invalid Host header".to_string()))
})
}

0 comments on commit 02d8c20

Please sign in to comment.