1
0
mirror of https://git.sr.ht/~adnano/go-gemini synced 2024-11-24 01:12:02 +01:00

Use splitHostPort function from net/url

This commit is contained in:
adnano 2020-09-28 02:27:29 -04:00
parent 7fcfc5ee41
commit 094312d48b
2 changed files with 39 additions and 10 deletions

@ -50,7 +50,8 @@ type Request struct {
// Hostname returns the request host without the port.
func (r *Request) Hostname() string {
return hostname(r.Host)
host, _ := splitHostPort(r.Host)
return host
}
// NewRequest returns a new request. The host is inferred from the provided URL.
@ -300,12 +301,3 @@ func validCertificate(cert *x509.Certificate) bool {
// No need to check hash algorithms, hopefully tls has checked for us already
return true
}
// hostname extracts the host name from a valid host or host:port
func hostname(host string) string {
i := strings.LastIndexByte(host, ':')
if i != -1 {
return host[:i]
}
return host
}

@ -1,6 +1,8 @@
// Hostname verification code from the crypto/x509 package.
// Modified to allow Common Names in the short term, until new certificates
// can be issued with SANs.
//
// Also includes the splitHostPort function from net/url package.
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
@ -225,3 +227,38 @@ func verifyHostname(c *x509.Certificate, h string) error {
return x509.HostnameError{c, h}
}
// validOptionalPort reports whether port is either an empty string
// or matches /^:\d*$/
func validOptionalPort(port string) bool {
if port == "" {
return true
}
if port[0] != ':' {
return false
}
for _, b := range port[1:] {
if b < '0' || b > '9' {
return false
}
}
return true
}
// 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
colon := strings.LastIndexByte(host, ':')
if colon != -1 && validOptionalPort(host[colon:]) {
host, port = host[:colon], host[colon+1:]
}
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = host[1 : len(host)-1]
}
return
}