Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ServerAddr::hostname method #4485

Merged
merged 1 commit into from
Apr 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 26 additions & 11 deletions crates/turbopack-core/src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@ impl ServerAddr {
Self(Some(addr))
}

/// The hostname portion of the address, without the port. Prefers
/// "localhost" when using a loopback address.
pub fn hostname(&self) -> Option<String> {
self.0.map(|addr| {
if addr.ip().is_loopback() || addr.ip().is_unspecified() {
"localhost".to_string()
} else if addr.is_ipv6() {
// When using an IPv6 address, we need to surround the IP in brackets to
// distinguish it from the port's `:`.
format!("[{}]", addr.ip())
} else {
addr.ip().to_string()
}
})
}

pub fn ip(&self) -> Option<String> {
self.0.map(|addr| addr.ip().to_string())
}
Expand All @@ -33,18 +49,17 @@ impl ServerAddr {
self.0.map(|addr| addr.port())
}

/// Constructs a URL out of the address.
pub fn to_string(&self) -> Result<String> {
let addr = &self.0.context("expected some server address")?;
let uri = if addr.ip().is_loopback() || addr.ip().is_unspecified() {
match addr.port() {
80 => "http://localhost".to_string(),
443 => "https://localhost".to_string(),
_ => format!("http://localhost:{}", addr.port()),
}
} else {
format!("http://{}", addr)
};
Ok(uri)
let (hostname, port) = self
.hostname()
.zip(self.port())
.context("expected some server address")?;
Ok(match port {
80 => format!("http://{hostname}"),
443 => format!("https://{hostname}"),
_ => format!("http://{hostname}:{port}"),
})
}
}

Expand Down