To make GET /products fast, the shop keeps the product list in a map called cache. The first request reads the database and remembers the list; every later one answers from memory. An AI assistant wrote the handler that changes a price:
app.HandleFunc("PATCH /products/{id}", func(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(r.PathValue("id"))
var data map[string]int
json.NewDecoder(r.Body).Decode(&data)
res, _ := db.Exec("UPDATE products SET price = ? WHERE id = ?", data["price"], id)
changed, _ := res.RowsAffected()
if changed == 0 {
writeJSON(w, 404, map[string]string{"error": "Product not found"})
return
}
writeJSON(w, 200, map[string]int{"id": id, "price": data["price"]})
})
The new price is saved, but nobody tells the cache. After PATCH /products/1 sets the Mug to 14, GET /products keeps answering the list it remembered, with the Mug at 12, until the app restarts. The remembered list is stale: true once, wrong now.
The rule for any cache: every route that changes the data clears what was remembered about it. If the shop also cached its categories, the handler that adds one would forget that list:
app.HandleFunc("POST /categories", func(w http.ResponseWriter, r *http.Request) {
var data map[string]string
json.NewDecoder(r.Body).Decode(&data)
db.Exec("INSERT INTO categories (name) VALUES (?)", data["name"])
delete(cache, "categories") // forget the remembered list
writeJSON(w, 201, map[string]string{"name": data["name"]})
})
delete(cache, key) forgets one key, and the built-in clear(cache) empties the whole map. The requests and the answers your app must give:
GET /products → 200 [{"id": 1, "name": "Mug", "price": 12}, {"id": 2, "name": "Notebook", "price": 7}, …] (8 products)
PATCH /products/1 {"price": 14} → 200 {"id": 1, "price": 14}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14}, {"id": 2, "name": "Notebook", "price": 7}, …]
PATCH /products/99 {"price": 5} → 404 {"error": "Product not found"}
PATCH /products/4 {"price": 3} → 200 {"id": 4, "price": 3}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14}, …, {"id": 4, "name": "Pen", "price": 3}, …]
Your task: rewrite the PATCH /products/{id} handler. Save the new price, answer 404 when no product has that id, empty the cache after a real change, and answer the id and the new price.
Assignment
Follow the Coding Tutorial to rewrite the PATCH handler so the shop shows every new price at once.
Hint
The line the AI forgot is clear(cache). Put it after the 404 check and its return: when no product changed, the remembered list is still true, so there is nothing to forget.
Free plan: 30 tutor messages. PRO is unlimited.
