Start learning free

LESSON 16 OF 173 · BACKEND: YOUR FIRST API

One Product by ID in Go

Practice

A shop can't write a handler for each of its products. Instead, one pattern has a placeholder in its path: a wildcard, written in braces. In "GET /products/{id}", the wildcard matches whatever is written in that part of the path, so /products/3 matches, and r.PathValue("id") gives your handler the text "3".

The wildcard matches any text, so /products/mug reaches your handler too. Turn the text into a number with strconv.Atoi: it gives back the number and an error, which is nil when it worked. When the error isn't nil, answer 404 with http.NotFound(w, r) and return. /products/count still goes to its own handler: when two patterns match, Go picks the more specific one. Here is the same idea on another path:

app.HandleFunc("GET /square/{number}", func(w http.ResponseWriter, r *http.Request) {
	n, err := strconv.Atoi(r.PathValue("number"))
	if err != nil {
		http.NotFound(w, r)
		return
	}
	writeJSON(w, 200, map[string]int{"square": n * n})
})

Once you have the id as a number, find the product with a loop: check each product's ID, and when it equals id, answer that product with writeJSON, then return. return ends the handler, so the loop stops there.

Your app must answer:

GET /products/1      →  200  {"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}
GET /products/3      →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home"}
GET /products/4      →  200  {"id": 4, "name": "Pen", "price": 2, "category": "office"}
GET /products/count  →  200  {"count": 4}
GET /products/mug    →  404  404 page not found

Your task: register a handler for "GET /products/{id}". It turns r.PathValue("id") into a number id with strconv.Atoi, answers 404 when that fails, then loops over products and answers, as JSON, the product whose ID equals id.


Assignment
Follow the Coding Tutorial to add the handler that answers one product by its id.


Hint
The name inside the braces and the name in r.PathValue(...) must be the same, "id". Inside the loop, compare product.ID with id: both are ints.


STEP 1 OF 7
    Ctrl + Enter to check

    Shop One Product in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free