URL Encode a String

· 179 words · 1 minute read

If you are coming from a PHP background you’re probably very used to functions like urlencode() and rawurlencode(). The good news is you can do the same in Go and rather simply too. In the net/url package there’s a QueryEscape function which accepts a string and will return the string with all the special characters encoded so they can be added to a url safely. An example of is converting the ‘+’ character into %2B.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"net/url"
)

func main() {

	text := "1 + 2, example for golangcode.com"
	fmt.Println("Before:", text)

	output := url.QueryEscape(text)
	fmt.Println("After:", output)
}

url encode query string basic

Alternatively, use url.Values for building a longer query

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"net/url"
)

func main() {

	// Use net/url's value list to build query, then encode it
	params := url.Values{}
	params.Add("q", "1 + 2")
	params.Add("s", "example for golangcode.com")
	output := params.Encode()

	fmt.Println("After:", output)
}

url encode query string with values

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!