Skip to content

Instantly share code, notes, and snippets.

@peterkellydev
Last active October 28, 2016 14:25
Show Gist options
  • Save peterkellydev/1d884081e2dc3b917f6c2a93c27df3b4 to your computer and use it in GitHub Desktop.
Save peterkellydev/1d884081e2dc3b917f6c2a93c27df3b4 to your computer and use it in GitHub Desktop.
package url
import (
"errors"
"net"
"net/url"
"strings"
)
func AddPortToURL(hostUrl, port string) (*url.URL, error) {
if !strings.HasPrefix(hostUrl, "http") {
return nil, errors.New("No scheme provided for host URL")
}
url, err := url.Parse(hostUrl)
if err != nil {
return nil, err
}
// strip : from port if it exists
port = strings.Replace(port, ":", "", strings.Count(port, ":"))
host := url.Host
// split apart host and port, if any port exists already
// then build back up with the port passed in to this function
host, p, err := net.SplitHostPort(url.Host)
if err != nil {
addErr := err.(*net.AddrError)
if addErr.Err == "missing port in address" {
host = url.Host
} else {
return err
}
}
if port == "" {
url.Host = host
} else if strings.HasPrefix(url.Host, "[") {
// JoinHostPort does not already handle existing [ and ]
// it will just add more [ and ] to host e.g. [[host]]
url.Host = host + ":" + port
} else {
url.Host = net.JoinHostPort(host, port)
}
return url, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment