URL encoding or percent-encoding, is a technique of encoding URLs utilizing solely a restricted set of characters in order that the URL may be transmitted safely over the Web. To decode such an encoded URL in Go, you’ll be able to simply use the parsing URL perform url.Parse()
from the url
package deal. It parses and decodes all components of the URL.
If you wish to URL encode a path, a question, or the entire URL, see URL Encode in Go put up.
A typical URL consists of the next elements:
scheme://host:port/path?question
The url.Parse()
takes an URL string as an argument and create the url.URL
struct containing all of the elements decoded. In case of issues, it returns an error.
package deal major
import (
"fmt"
"log"
"web/url"
)
func major() {
// decode URL by url.Parse
parsedURL, err := url.Parse("https://instance.com/foo+barpercent21?question=abpercent2Bc&query2=depercent24f")
if err != nil {
log.Deadly(err)
return
}
fmt.Printf("scheme: %sn", parsedURL.Scheme)
fmt.Printf("host: %sn", parsedURL.Host)
fmt.Printf("path: %sn", parsedURL.Path)
fmt.Println("question args:")
for key, values := vary parsedURL.Question() {
fmt.Printf(" %s = %sn", key, values[0])
}
}
Outcome:
scheme: https
host: instance.com
path: /foo+bar!
question args:
question = ab+c
query2 = de$f
Alternatively, you should use capabilities that decode particular elements of an URL:
url.PathUnescape()
– to decode the URL path element. The path phase is encoded in another way from the question (for instance, the+
character is allowed within the path), so it wants a distinct technique than the question half.url.QueryUnescape()
– to decode the URL question element.url.ParseQuery()
– to decode the URL question element and parse it to the type ofurl.Values
that maps a question key to the values.
See the instance to match these capabilities:
package deal major
import (
"fmt"
"log"
"web/url"
)
func major() {
// decode path by url.PathUnescape
path := "foo+barpercent21"
unescapedPath, err := url.PathUnescape(path)
if err != nil {
log.Deadly(err)
return
}
fmt.Printf("unescaped path: %sn", unescapedPath)
// decode question by url.QueryUnescape
question := "question=abpercent2Bc&query2=depercent24f"
unescapedQuery, err := url.QueryUnescape(question)
if err != nil {
log.Deadly(err)
return
}
fmt.Printf("unescaped question: %sn", unescapedQuery)
// decode question and parse by url.ParseQuery
parsedQuery, err := url.ParseQuery(question)
if err != nil {
log.Deadly(err)
return
}
fmt.Println("parsed question args:")
for key, values := vary parsedQuery {
fmt.Printf(" %s = %sn", key, values[0])
}
}
Outcome:
unescaped path: foo+bar!
unescaped question: question=ab+c&query2=de$f
parsed question args:
question = ab+c
query2 = de$f