🔗 URL Encode in Go

April 13, 2021
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 (
    "fmt"
    "net/url"
)

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

✒️ Write to a CSV file in Go

Learn how to write data to a CSV or TSV file
introduction file

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings