Quick Tip: Remove Query Param from URL in Go

- Wednesday, June 1, 2016

How to easily remove query string parameters from a url.URL in Go.

Today’s short post shows how simple it is.

To remove a query string param component from a Go url.URL, you have to rebuild the RawQuery portion of the url.URL.

  • First you extract the url.Values from the url.Url with q := myURL.Query(), and use the q.Del(key) method to drop the component you wish to strip (where key is the name portion of the key/value pair).

  • Then, simply assign the output of q.Encode() to the myURL.RawQuery field.

That’s it. Simple, but a little subtle, so I wrote this short post to remind myself.

You can see the code below in action on the Go Playground

The relevant lines are highlighted.

func stripQueryParam(inURL string, stripKey string) string {
  u, err := url.Parse(inURL)
  if err != nil {
    // TODO: log or handle error, in the meanwhile just return the original
    return inURL
  q := u.Query()
  u.RawQuery = q.Encode()
  return u.String()