Don't Just String Append to a Querystring

Something I've been guilty of doing in the past, but am trying to make up for, is using string concatenation with URLs to append parameters to a querystring.

For instance, let's take the following Go code:

package main

import (

func main() {
  u := ""
  fmt.Println(u + "?utm_medium=code_example");

In this case, the URL will be correctly output as:

It's something that is generally safe, but you're going to hit "edge cases" more often than not, such as a URL already having a querystring on it:
# when concatenated, it is *not* a valid URL:

Or we may have an empty querystring:
# when concatenated, it is *not* a valid URL:

Or we may have a fragment on the URL:
# when concatenated, it is *not* a valid querystring, as it's part of the fragment:

Or even if the URL already has a query parameter of that name, and we don't specify what we want the behaviour to be, which can cause confusion between URL parsing libraries:
# when concatenated

So what should we do instead?

We should treat the URL as a URL, not an arbitrary string, and then append/replace the parameter according to what we want to do.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.


This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.