How to URL Encode a String in Golang
3 minsIn this article, you’ll learn how to URL Encode a query string or path segment in Golang. URL Encoding, also known as percent encoding, converts a string containing unprintable, reserved, or non-ASCII characters to a universally accepted format that can be transmitted over the internet.
URL Encoded data is also referred to as application/x-www-form-urlencoded
MIME format.
URL Encoding a Query string in Golang
Go’s net/url
package contains a built-in method called QueryEscape
to escape/encode a string so that it can be safely placed inside a URL query. The following example demonstrates how to encode a query string in Golang -
package main
import (
"fmt"
"net/url"
)
func main() {
query := "Hellö Wörld@Golang"
fmt.Println(url.QueryEscape(query))
}
# Output
Hell%C3%B6+W%C3%B6rld%40Golang
URL Encoding multiple Query parameters in Golang
If you want to encode multiple query parameters at once, then you can create a url.Values
struct consisting of Query param to value mapping and encode all the query params using the url.Values.Encode()
method.
Here is an example -
package main
import (
"fmt"
"net/url"
)
func main() {
params := url.Values{}
params.Add("name", "@Rajeev")
params.Add("phone", "+919999999999")
fmt.Println(params.Encode())
}
# Output
name=%40Rajeev&phone=%2B919999999999
URL Encoding a Path Segment in Golang
Just like QueryEscape
, the net/url
package in Go has another function named PathEscape()
to encode a string so that it can be safely placed in the path segment of a URL -
package main
import (
"fmt"
"net/url"
)
func main() {
path := "path with?reserved+characters"
fmt.Println(url.PathEscape(path))
}
# Output
path%20with%3Freserved+characters
Building a complete URL by encoding individual parts
Finally, Let’s see a complete example of URL parsing and URL encoding in Golang -
package main
import (
"fmt"
"net/url"
)
func main() {
// Let's start with a base url
baseUrl, err := url.Parse("http://www.mywebsite.com")
if err != nil {
fmt.Println("Malformed URL: ", err.Error())
return
}
// Add a Path Segment (Path segment is automatically escaped)
baseUrl.Path += "path with?reserved characters"
// Prepare Query Parameters
params := url.Values{}
params.Add("q", "Hello World")
params.Add("u", "@rajeev")
// Add Query Parameters to the URL
baseUrl.RawQuery = params.Encode() // Escape Query Parameters
fmt.Printf("Encoded URL is %q\n", baseUrl.String())
}
# Output
Encoded URL is "http://www.mywebsite.com/path%20with%3Freserved%20characters?q=Hello+World&u=%40rajeev"
Also Read: How to do URL decoding in Golang