How to Decode URLs in Golang

In this article, you’ll learn how to URL decode query strings or form parameters in Golang. URL Decoding is the inverse operation of URL encoding. It converts the encoded characters back to their normal form.

URL Decoding a Query string in Golang

Go’s net/url package contains a built-in method called QueryUnescape to unescape/decode a string. The following example shows how to decode a query string in Golang -

package main

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

func main() {
	encodedValue := "Hell%C3%B6+W%C3%B6rld%40Golang"
	parsedValue, err := url.QueryUnescape(encodedValue)
	if err != nil {
		log.Fatal(err)
		return
	} 
	fmt.Println(parsedValue)
}
# Output
Hellö Wörld@Golang

Parsing a URL encoded query string of the form ("param1=value1&param2=value2")

You can use url.ParseQuery() method to parse a series of key=value pairs separated by & into a map[string][]string -

package main

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

func main() {
	queryStr := "name=Rajeev%20Singh&phone=%2B9199999999&phone=%2B628888888888"
	params, err := url.ParseQuery(queryStr)
	if err != nil {
		log.Fatal(err)
		return
	}

	fmt.Println("Query Params: ")
	for key, value := range params {
		fmt.Printf("  %v = %v\n", key, value)
	}
}
# Output
Query Params: 
  name = [Rajeev Singh]
  phone = [+9199999999 +628888888888]

URL Decoding a Path Segment in Golang

PathUnescape() function is identical to QueryUnescape() except that it does not unescape plus sign (+) to space(" ") because plus sign is allowed in the path segment of a URL. It is a special character only in the query component.

package main

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

func main() {
	path := "path%20with%3Freserved+characters"
	unescapedPath, err := url.PathUnescape(path)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(unescapedPath)
}
# Output
path with?reserved+characters

Parsing a complete URL in Golang

Finally, Let’s see a complete example of URL parsing in Golang -

package main

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

func main() {
	u, err := url.Parse("https://www.website.com/person?name=Rajeev%20Singh&phone=%2B919999999999&phone=%2B628888888888")

	if err != nil {
		log.Fatal(err)
		return
	}

	fmt.Println("Scheme: ", u.Scheme)
	fmt.Println("Host: ", u.Host)

	queries := u.Query()
	fmt.Println("Query Strings: ")
	for key, value := range queries {
		fmt.Printf("  %v = %v\n", key, value)
	}
	fmt.Println("Path: ", u.Path)
}
# Output
Scheme:  https
Host:  www.website.com
Query Strings: 
  phone = [+919999999999 +628888888888]
  name = [Rajeev Singh]
Path:  /person

Also Read: How to URL Encode a String in Golang

References