A shop's front page often shows a menu of its categories. The shop keeps no list of them: each product only knows its own category. So your API builds the list from the products, every time someone asks.
The list must be distinct: two products are in "office", but the menu shows it once. Before adding a value to a slice, slices.Contains(list, x) tells you whether the slice already holds it, and ! turns the answer around. Then slices.Sort puts a slice of strings in alphabetical order, in place, with no compare function. The same idea on a list of colors:
colors := []string{}
for _, color := range []string{"red", "blue", "red"} {
if !slices.Contains(colors, color) {
colors = append(colors, color)
}
}
slices.Sort(colors)
fmt.Println(colors) // [blue red]
The list is built from the products on every request, so it always follows them. A product in a new category adds that category, and deleting the only product of a category removes it. Your code must answer these requests, in this order:
GET /categories → 200 ["home", "kitchen", "office"]
POST /products {"name": "Chair", "price": 45, "category": "furniture"} → 201 {"id": 5, "name": "Chair", …}
POST /products {"name": "Stapler", "price": 9, "category": "office"} → 201 {"id": 6, "name": "Stapler", …}
GET /categories → 200 ["furniture", "home", "kitchen", "office"]
DELETE /products/3 → 204
GET /categories → 200 ["furniture", "kitchen", "office"]
Your task: add a route for GET /categories that answers the distinct categories of the products, in alphabetical order, as a JSON list.
Assignment
Follow the Coding Tutorial to build the GET /categories route: an empty slice, a loop over products, a slices.Contains check, a sort and the JSON answer.
Hint
Append a category only when !slices.Contains(categories, product.Category). A slice of strings needs no compare function: slices.Sort(categories) puts it in alphabetical order, then answer it with writeJSON.
Free plan: 30 tutor messages. PRO is unlimited.
