Start learning free

LESSON 5 OF 173 · BACKEND: HOW THE WEB WORKS

Send a Query String

Practice

A query string is the part of a URL after the ?. It carries options for the path as name=value pairs, joined with &. The server reads them and shapes its answer: /prices?max_price=5 asks the supplier for the products that cost 5 or less.

You don't have to write the query string by hand. Put the options in a url.Values with Set, and its Encode() writes them as name=value text. Encode() adds no ?, so you write that one yourself. response.Request.URL shows the address the request really went to:

params := url.Values{}
params.Set("page", "2")
response, _ := http.Get(supplier + "/catalog?" + params.Encode())
fmt.Println(response.Request.URL)   // http://127.0.0.1:8001/catalog?page=2

The supplier filters its list before it answers, so the products that cost more never leave the server. For /prices with max_price set to 5, your script must print:

URL: http://127.0.0.1:8001/prices?max_price=5
Mug costs 5
Notebook costs 3
Pen costs 1

Your task: the starting code already sets max_price to "5" in params. Ask for /prices? followed by params.Encode(), print "URL:" and response.Request.URL, then decode the list of products and print each one that came back: its name, "costs" and its price.


Assignment
Follow the Coding Tutorial to send the query string built from params, print the URL that went out and print the products the supplier sent back.


Hint
params.Encode() gives only max_price=5, so end the path text with the ?: "/prices?". The answer is a list of products: decode it into a []map[string]any and loop over it with range.


STEP 1 OF 6
    Ctrl + Enter to check