How To Url Encode String In Golang Example

URL encoding is also known as “percent-encoding”. URL encoding is a mechanism to represent data used in a URI (Uniform Resource Identifier). This is also used when encoding data being sent using HTTP Forms for example when using the application/x-www-form-urlencoded media type.

Why do we need URL encoding?

URI by definition has two types of characters, reserved and unreserved. Think as reserved characters as special characters which have particular meaning. For example, forward slash characters are used to separate different parts of a URL. The URL encoding process allows us to translate any string to a URI valid string, encoding characters that would be otherwise reserved into percent-encoded ones.
When percent encoding strings the reserved characters gets represented in percent-encoded format, a percent sign % followed by the byte value representation of the ASCII value of that character. For instance double-quote " would become %22 when URL-encoded.

URL Encoding a Query String in Golang

As in all programming langauages, Go (Golang) is no exception when it comes to url encoding strings. We have already baked into the standard library the needed functionality to perfom a URL encoding operation. One simple example is when we need to URL encode a single string to be used in a URL. We can use net/url package to do so. The method we want to use is QueryEscape

func QueryEscape(s string) string

QueryEscape escapes the string so it can be safely placed inside a URL query.

Let’s see an example

package main

import (
    "fmt"
    "net/url"
)

func main() {
    s := "this will be esc@ped!"
    fmt.Println("http://example.com/say?message="+url.QueryEscape(s))
}
http://example.com/say?message=this+will+be+esc%40ped%21

URL Encoding multiple values in Golang

Same scenario as just explored above, but this time we can use a more powerful method to escape multiple fields at once. Using url.Values struct and url.Values.Encode() method. Here’s its definition

func (v Values) Encode() string

Encode encodes the values into “URL encoded” form (“bar=baz&foo=quux”) sorted by key.

Let’s see an example with multiple keys to be URL encoded

package main

import (
    "fmt"
    "net/url"
)

func main() {
    params := url.Values{}
    params.Add("message", "this will be esc@ped!")
    params.Add("author", "golang c@fe >.<")
    fmt.Println("http://example.com/say?"+params.Encode())
}
http://example.com/say?author=golang+c%40fe+%3E.%3C&message=this+will+be+esc%40ped%21

I hope you enjoyed the article and learned how to URL encode (or percent-encode) strings in Go (Golang)!

Join the Golang Developers Community on Golang Cafe