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"
"net/url"
)
func main() {
encodedValue := "Hell%C3%B6+W%C3%B6rld%40Golang"
decodedValue, err := url.QueryUnescape(encodedValue)
if err != nil {
fmt.Println("Error decoding query string: ", err.Error())
return
}
fmt.Println(decodedValue)
} # Output
Hellö Wörld@Golang 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"
"net/url"
)
func main() {
path := "path%20with%3Freserved+characters"
unescapedPath, err := url.PathUnescape(path)
if err != nil {
fmt.Println("Error decoding path: ", err.Error())
return
}
fmt.Println(unescapedPath)
} # Output
path with?reserved+characters Parsing and decoding a complete URL in Golang
If you have a complete URL with encoded path and query parameters, you can use the url.Parse() function to parse the URL. The parsed URL will have the path segment and query parameters automatically decoded.
package main
import (
"fmt"
"net/url"
)
func main() {
rawUrl := "https://www.example.com/path%20segment?name=John+Doe&phone=%2B919999999999"
parsedUrl, err := url.Parse(rawUrl)
if err != nil {
fmt.Println("Error parsing URL: ", err.Error())
return
}
// Decoded path segment
fmt.Println("Decoded Path:", parsedUrl.Path)
// Parsed query parameters (automatically decoded)
queryParams := parsedUrl.Query()
fmt.Println("Name:", queryParams.Get("name"))
fmt.Println("Phone:", queryParams.Get("phone"))
} # Output
Decoded Path: /path segment
Name: John Doe
Phone: +919999999999 Also Read: How to URL Encode a String in Golang