URL encoding or percent-encoding, is a method of encoding URLs using only a limited set of characters so that the URL can be transmitted safely over the Internet. To decode such an encoded URL in Go, 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.
A typical URL consists of the following components:
The url.Parse()
takes an URL string as an argument and create the url.URL
struct containing all the components decoded. In case of problems, it returns an error.
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 specific components of an URL:
url.PathUnescape()
- to decode the URL path component. The path segment is encoded differently from the query (for example, the+
character is allowed in the path), so it needs a different method than the query part.url.QueryUnescape()
- to decode the URL query component.url.ParseQuery()
- to decode the URL query component and parse it to the form ofurl.Values
that maps a query key to the values.
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