How to understand and use url.QueryEscape
, in Go language?
Go has good support for url parsing. URL contains a scheme, authentication info, host, port, path, query params, and query fragment. we can parse URL and deduce what are the parameter is coming to the server and then process the request accordingly.
URL Encoding or Escaping a String in Go Go provides the following two functions to encode or escape a string so that it can be safely placed inside a URL: QueryEscape(): Encode a string to be safely placed inside a URL query string. PathEscape(): Encode a string to be safely placed inside a URL path segment.
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.
The query string is composed of a series of field-value pairs. Within each pair, the field name and value are separated by an equals sign, " = ". The series of pairs is separated by the ampersand, " & " (semicolons " ; " are not recommended by the W3C anymore, see below).
To understand the usage of url.QueryEscape
, you first need to understand what a url query string is.
A query string is a part of URL that contains data that can be passed to web applications. This data needs to be encoded, and this encoding is done using url.QueryEscape
. It performs what is also commonly called URL encoding.
Example
Let's say we have webpage:
http://mywebpage.com/thumbify
And we want to pass an image url, http://images.com/cat.png
, to this web application. Then this url needs look something like this:
http://mywebpage.com/thumbify?image=http%3A%2F%2Fimages.com%2Fcat.png
In Go code, it would look like this:
package main
import (
"fmt"
"net/url"
)
func main() {
webpage := "http://mywebpage.com/thumbify"
image := "http://images.com/cat.png"
fmt.Println( webpage + "?image=" + url.QueryEscape(image))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With