URL Encode Query String Parameters in Go

0
25820
URL Encode Query String Parameters in Go
URL Encode Query String Parameters in Go

In this post, I will show you how to perform URL encode query string parameters in Go (golang).

To URL encode query string parameters in Go, we will make use of type url.Values, which is a builtin type from net/url library.

Take a look at following code:

package main

import (
	"fmt"
	"net/url"
)

func main() {
	params := url.Values{}
	params.Add("author", "Pete Houston")
	params.Add("title", "URL Encode Query String Parameters in Go")

	queryStr := params.Encode()
	fmt.Println("URL Encoded: ", queryStr)
}

First step, we declare an instance of type url.Values , then use Add() to provide map of all key/value pairs of query string parameters.

Finally, to get the URL encoded result, make call to Encode() method.

This is the result:

$ go run main.go
URL Encoded:  author=Pete+Houston&title=URL+Encode+Query+String+Parameters+in+Go

This is very helpful when we need to build a long list  or already have the key/value pairs.

However, if we have a query string, it’s not so convenient to parse into a map of key-value pair then add one by one to the url.Values object. In such case, we can use this quick and handy function, url.QueryEscape().

originalQueryString := "author=Pete Houston&title=URL Encode Query String Parameters in Go"
fmt.Println("Original: ", originalQueryString)
encodedQueryString := url.QueryEscape(originalQueryString)
fmt.Println("URL Encoded: ", encodedQueryString)

This is the output of the snippet:

$ go run main.go
Original:  author=Pete Houston&title=URL Encode Query String Parameters in Go
URL Encoded:  author%3DPete+Houston%26title%3DURL+Encode+Query+String+Parameters+in+Go

Have fun!