Skip to content

net/url: mention net.JoinHostPort for constructing url.URL.Host #61093

@dsnet

Description

@dsnet

In #16142, we add read support for extracting out the hostname and port.

However, that API is lacking the ability to write a host:port pair. Unfortunately, this is not as trivial as concatenating the host and port with a ":" in-between in the case of IPv6, which requires wrapping the entire host with "[" and "]" characters.

I propose the addition of:

// JoinHostnamePort joins a hostname and a port, separating them with a colon.
// If the hostname is an IPv6 address, then it is wrapped with brackets.
// If the port is empty, then the hostname alone is returned.
func JoinHostnamePort(hostname, port string) string

Example outputs:

JoinHostnamePort("carbonite.digitalstatic.ts.net", "")              // carbonite.digitalstatic.ts.net
JoinHostnamePort("carbonite.digitalstatic.ts.net", "9200")          // carbonite.digitalstatic.ts.net:9200
JoinHostnamePort("100.109.51.95", "")                               // 100.109.51.95
JoinHostnamePort("100.109.51.95", "9200")                           // 100.109.51.95:9200
JoinHostnamePort("fd7a:115c:a1e0:ab12:4843:cd96:626d:335f", "")     // fd7a:115c:a1e0:ab12:4843:cd96:626d:335f
JoinHostnamePort("fd7a:115c:a1e0:ab12:4843:cd96:626d:335f", "9200") // [fd7a:115c:a1e0:ab12:4843:cd96:626d:335f]:9200

Considerations:

  • It's called JoinHostnamePort instead of JoinHostPort to be consistent with the url.URL.Hostname method.
  • The port is a string to be consistent with url.URL.Port
  • A standalone function that returns a string is consistent with top-level string-only transformers like JoinPath, PathEscape, PathUnescape, QueryEscape, QueryUnescape.
  • What happens if the hostname contains colons but is not an IPv6 or the port is not a valid integer? We'll just concatenate the host and port with a colon in-between even if the result is ambiguous to parse. Alternatively, we could modify the API of JoinHostnamePort to return an error, but I personally like the simplicity of an error-less result.

\cc @bradfitz

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions