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:
url.PathUnescape()
- to decode string that is inside an URL path segment. Path segment is encoded differently from the query (for example, the+
character is allowed in the path), so it needs a different method from the query part.url.QueryUnescape()
- to decode string that is inside an URL query.url.ParseQuery()
- to decode string inside an URL query and parse it to the form ofurl.Values
map.
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