⛓️ URL Decode in Go

introduction encoding url

To decode an escaped URL in Golang you can just use the parsing URL function url.Parse from the url package. It parses and decodes all parts of the URL.

If you want to URL encode a path, a query, or the whole URL, see URL Encode in Go post.

package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {
    // decode URL by url.Parse
    parsedURL, err := url.Parse("https://example.com/foo+bar%21?query=ab%2Bc&query2=de%24f")
    if err != nil {
        log.Fatal(err)
        return
    }

    fmt.Printf("scheme: %s\n", parsedURL.Scheme)
    fmt.Printf("host: %s\n", parsedURL.Host)
    fmt.Printf("path: %s\n", parsedURL.Path)
    fmt.Println("query args:")
    for key, values := range parsedURL.Query() {
        fmt.Printf("  %s = %s\n", key, values[0])
    }
}

Result:

scheme: https
host: example.com
path: /foo+bar!
query args:
  query = ab+c
  query2 = de$f

Alternatively, you can use functions that decode and parse different parts of the URL:

See the example to compare these functions:

package main

import (
    "fmt"
    "log"
    "net/url"
)

func main() {
    // decode path by url.PathUnescape
    path := "foo+bar%21"
    unescapedPath, err := url.PathUnescape(path)
    if err != nil {
        log.Fatal(err)
        return
    }
    fmt.Printf("unescaped path: %s\n", unescapedPath)

    // decode query by url.QueryUnescape
    query := "query=ab%2Bc&query2=de%24f"
    unescapedQuery, err := url.QueryUnescape(query)
    if err != nil {
        log.Fatal(err)
        return
    }
    fmt.Printf("unescaped query: %s\n", unescapedQuery)

    // decode query and parse by url.ParseQuery
    parsedQuery, err := url.ParseQuery(query)
    if err != nil {
        log.Fatal(err)
        return
    }
    fmt.Println("parsed query args:")
    for key, values := range parsedQuery {
        fmt.Printf("  %s = %s\n", key, values[0])
    }
}

Result:

unescaped path: foo+bar!
unescaped query: query=ab+c&query2=de$f
parsed query args:
  query = ab+c
  query2 = de$f

🔗 URL Encode in Go

Learn how to URL encode 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