🔗 URL Encode in Go

introduction encoding url

URL encoding, also known as percent-encoding, is a method to encode URL using only a limited set of characters so that the URL can be safely transmitted over the internet. In Golang we have 2 basic functions in net/url package for encoding different parts of the URL:

Instead of building the URL manually, we can make this procedure a little easier by using url.URL structure. We just need to set Scheme, Host, Path of the URL and build RawQuery string by encoding query parameters inside url.Values struct.

See the example to compare these two methods of URL encoding:

package main

import (

func main() {
    // build url manually
    host := "https://example.com/"
    path := url.PathEscape("foo+bar!")
    query1Val := url.QueryEscape("ab+c")
    query2Val := url.QueryEscape("de$f")
    query := fmt.Sprintf("query=%s&query2=%s", query1Val, query2Val)
    fmt.Printf("%-35s %s%s?%s\n", "Manually built URL:", host, path, query)

    // build url using url.URL struct
    exampleURL := &url.URL{
        Scheme: "https",
        Host:   "example.com",
        Path:   "/foo+bar!",
    queryValues := url.Values{}
    queryValues.Add("query", "ab+c")
    queryValues.Add("query2", "de$f")
    exampleURL.RawQuery = queryValues.Encode()
    fmt.Printf("%-35s %s\n", "URL built using url.URL struct:", exampleURL)
Manually built URL:                 https://example.com/foo+bar%21?query=ab%2Bc&query2=de%24f
URL built using url.URL struct:     https://example.com/foo+bar%21?query=ab%2Bc&query2=de%24f

⛓️ URL Decode in Go

Learn how to URL decode a path and query parameters in Go
introduction encoding url

👈 Decode Base64 to a string in Go

Learn how to decode Base64 data to a string using encoding/base64 package
base64 encoding strings

👉 Encode a string to Base64 in Go

Learn how to encode strings to Base64 using encoding/base64 package
base64 encoding strings