Search code examples
stringgourlurl-rewritingsubstring

Replacing protocol and hostname in URL in Go


Is there a straightforward way in Go to modify a URL/URI without having to use regex to extract the components (i.e. I'm looking for a deterministic "tried and true" way/approach).

For example, I have two types of URLs that get sent to my application:

  • http://wiley.coyote.acme.co/this/is/a/long/path?param1=123&param2=456
  • https://road.runner.acme.co/another/long/path?meep=meep

What I need to do is re-write the URLs so the parameter list and endpoint/path is intact, but the protocol is changed from http to https (unless it's already https), and the entire hostname/FQDN needs to be changed to egghead.local. So, for example, the two URLs above would become:

  • https://egghead.local/this/is/a/long/path?param1=123&param2=456
  • https://egghead.local/another/long/path?meep=meep

Is there a reliably/mature approach to handling this (e.g. preferably without regex)?


Solution

  • Use the url package:

    func toHTTPS(addr string) (string, error) {
        u, err := url.Parse(addr)
        if err != nil {
            return "", err
        }
        u.Scheme = "https"
        return u.String(), nil
    }
    

    or

    func setHostname(addr, hostname string) (string, error) {
        u, err := url.Parse(addr)
        if err != nil {
            return "", err
        }
        u.Host = hostname
        return u.String(), nil
    }