The product list is the shop's busiest page, and it rarely changes, so running the same query for every visitor is wasted work. A cache keeps an answer you already worked out, so you can give it again without the work.
The simplest cache is a map: its keys name what is remembered, its values are the remembered answers. Look up the key first with two names on the left, the value and ok; if ok is true, give the remembered answer; if not, do the work and store the result. Here is the idea on another value, squares of numbers:
var squares = map[int]int{}
func square(n int) int {
value, ok := squares[n]
if ok {
return value
}
result := n * n
squares[n] = result
return result
}
The first call fills the cache, every later call reads it. Count the queries to prove it: two lists, one query. Only GET /products uses the cache, so GET /products/1 still asks the database. Your code must give these answers, in this order:
GET /products → 200 [{"category": "kitchen", "id": 1, "name": "Mug", "price": 12, "stock": 10}, … 8 products]
GET /debug/queries → 200 {"queries": 1}
GET /products → 200 [the same 8 products]
GET /debug/queries → 200 {"queries": 1}
GET /products/1 → 200 {"category": "kitchen", "id": 1, "name": "Mug", "price": 12, "stock": 10}
GET /debug/queries → 200 {"queries": 2}
The cache lives in the app's memory, not in the database, so it starts empty each time the app starts.
Your task: below stats, add an empty map[string][]Product called cache. In the /products handler, store the finished list in cache under the key "products" just before the last writeJSON, and, as the first lines, look it up with cached, ok := cache["products"]: when ok is true, answer cached with writeJSON and return.
Assignment
Follow the Coding Tutorial to cache the product list, so only the first GET /products runs the query.
Hint
The lookup must come before the query, or the query has already run. Go won't build while cached or ok is unused, so those errors go away once the if uses them. Don't forget the return: writeJSON doesn't stop the handler.
Free plan: 30 tutor messages. PRO is unlimited.
