Start learning free

LESSON 19 OF 173 · BACKEND: YOUR FIRST API

Two Filters at Once

Practice

A query string can carry several parameters, joined with &. In /products?category=office&max_price=5 the client asks for office products that cost 5 or less. The order of the parameters doesn't matter, because you read each one by its name.

Not every parameter is a number. A category is text, so you read it with r.URL.Query().Get alone, without strconv.Atoi; like any parameter, it is the empty text "" when the URL leaves it out. Here is the idea on another route, with two optional parameters:

app.HandleFunc("GET /greet", func(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	times, err := strconv.Atoi(r.URL.Query().Get("times"))
	if name == "" {
		name = "friend"
	}
	if err != nil {
		times = 1
	}
	for i := 0; i < times; i++ {
		fmt.Fprint(w, "Hello, "+name+"! ")
	}
})

To combine two filters, put one check inside the other: a product is added only when it passes the price check and the category check. Each check lets every product through when its parameter is missing (err != nil for the price, category == "" for the category), so each filter also works alone. Your code must give:

GET /products?category=office                →  200  [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products?category=office&max_price=5    →  200  [{"id": 4, "name": "Pen", …}]
GET /products?max_price=20&category=kitchen  →  200  [{"id": 1, "name": "Mug", …}]
GET /products?category=garden                →  200  []
GET /products?category=home&max_price=10     →  200  []
GET /products?max_price=10                   →  200  [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products                                →  200  all 4 products

Your task: read a second query parameter, category, and change the loop in the "GET /products" handler so a product is added only when it passes both filters. In the starting code the price check is empty: the append comes back one level deeper. Either filter can be left out.


Assignment
Follow the Coding Tutorial to read category and add the category check inside the price check.


Hint
The category check has the same shape as the price check: the "not given" test first (category == ""), then ||, then a comparison with ==. The append line goes inside the new if.


STEP 1 OF 3
    Ctrl + Enter to check