1

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)?

0

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.