Quick Tip: Remove Query Param from URL in Go - June 1, 2016

Spent a few too many minutes today figuring out how to easily remove query string parameters from a url.URL in Go.

Today’s short post shows how simple it is.

It’s so simple I could have kicked myself. 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).

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

That’s it. Simple, but a little subtle, so I this is a short post to remind myself, and anyone else searching for the answer.

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

func stripQueryParam(inURL string, stripKey string) string { u, err := url.Parse(inURL) if err != nil { // dunno, bail! return inURL } q := u.Query() q.Del(stripKey) u.RawQuery = q.Encode() return u.String() }