aboutsummaryrefslogtreecommitdiff
path: root/src/net/url/url.go
diff options
context:
space:
mode:
Diffstat (limited to 'src/net/url/url.go')
-rw-r--r--src/net/url/url.go54
1 files changed, 27 insertions, 27 deletions
diff --git a/src/net/url/url.go b/src/net/url/url.go
index 8d2a856699..b13677ca8a 100644
--- a/src/net/url/url.go
+++ b/src/net/url/url.go
@@ -636,6 +636,11 @@ func parseHost(host string) (string, error) {
}
return host1 + host2 + host3, nil
}
+ } else if i := strings.LastIndex(host, ":"); i != -1 {
+ colonPort := host[i:]
+ if !validOptionalPort(colonPort) {
+ return "", fmt.Errorf("invalid port %q after host", colonPort)
+ }
}
var err error
@@ -1033,44 +1038,39 @@ func (u *URL) RequestURI() string {
return result
}
-// Hostname returns u.Host, without any port number.
+// Hostname returns u.Host, stripping any valid port number if present.
//
-// If Host is an IPv6 literal with a port number, Hostname returns the
-// IPv6 literal without the square brackets. IPv6 literals may include
-// a zone identifier.
+// If the result is enclosed in square brackets, as literal IPv6 addresses are,
+// the square brackets are removed from the result.
func (u *URL) Hostname() string {
- return stripPort(u.Host)
+ host, _ := splitHostPort(u.Host)
+ return host
}
// Port returns the port part of u.Host, without the leading colon.
-// If u.Host doesn't contain a port, Port returns an empty string.
+//
+// If u.Host doesn't contain a valid numeric port, Port returns an empty string.
func (u *URL) Port() string {
- return portOnly(u.Host)
+ _, port := splitHostPort(u.Host)
+ return port
}
-func stripPort(hostport string) string {
- colon := strings.IndexByte(hostport, ':')
- if colon == -1 {
- return hostport
- }
- if i := strings.IndexByte(hostport, ']'); i != -1 {
- return strings.TrimPrefix(hostport[:i], "[")
- }
- return hostport[:colon]
-}
+// splitHostPort separates host and port. If the port is not valid, it returns
+// the entire input as host, and it doesn't check the validity of the host.
+// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
+func splitHostPort(hostport string) (host, port string) {
+ host = hostport
-func portOnly(hostport string) string {
- colon := strings.IndexByte(hostport, ':')
- if colon == -1 {
- return ""
- }
- if i := strings.Index(hostport, "]:"); i != -1 {
- return hostport[i+len("]:"):]
+ colon := strings.LastIndexByte(host, ':')
+ if colon != -1 && validOptionalPort(host[colon:]) {
+ host, port = host[:colon], host[colon+1:]
}
- if strings.Contains(hostport, "]") {
- return ""
+
+ if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
+ host = host[1 : len(host)-1]
}
- return hostport[colon+len(":"):]
+
+ return
}
// Marshaling interface implementations.