9

How to understand and use url.QueryEscape, in Go language?

exebook
  • 32,014
  • 33
  • 141
  • 226
ggaaooppeenngg
  • 1,323
  • 3
  • 17
  • 27

1 Answers1

23

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))
}
ANisus
  • 74,460
  • 29
  • 162
  • 158
  • why should we do like this, rather than directly use the image url? – ggaaooppeenngg Jan 04 '14 at 14:15
  • 4
    It is part of the standard and it is required. Some characters are not allowed in urls (like space), and some characters have special meanings in the url (like =, # or &). Without encoding we cannot say if & is part of the data or if it is a delimiter. – ANisus Jan 04 '14 at 14:21