This project puts most of what you have built so far into one new route. A product page shows the product's rating: the average of the stars in its reviews. The rating belongs to one product, so it gets a nested path under that product, just like the reviews: /products/1/rating.
An average in Go: collect the numbers in a slice, then divide sum by len, both turned into float64. To keep 2 decimal places, round 100 times the average with math.Round and divide by 100, the way the GET /stats route does for the prices.
temperatures := []int{20, 23, 22}
average := math.Round(float64(sum(temperatures))*100/float64(len(temperatures))) / 100
fmt.Println(average) // 21.67
No numbers, no average: when the slice is empty, len is 0, and 0.0 / 0.0 is NaN, "not a number", which JSON can't send. So check for an empty slice first, answer nil, which is null in JSON, and return. A product with no reviews still exists, so it gets 200 with a null rating. A product that isn't in products gets 404, as always.
The test requests, in this order, and what your code must answer:
GET /products/1/rating → 200 {"product_id": 1, "rating": 4.5}
GET /products/3/rating → 200 {"product_id": 3, "rating": 2}
GET /products/2/rating → 200 {"product_id": 2, "rating": null}
GET /products/99/rating → 404 {"error": "Product not found"}
POST /products/1/reviews {"stars": 5, "text": "My favourite mug"} → 201 (the review)
GET /products/1/rating → 200 {"product_id": 1, "rating": 4.67}
POST /products/2/reviews {"stars": 3, "text": "Thin pages"} → 201 (the review)
GET /products/2/rating → 200 {"product_id": 2, "rating": 3}
DELETE /products/3 → 204 (empty)
GET /products/3/rating → 404 {"error": "Product not found"}
Your task: at the end of the file, the route for GET /products/{id}/rating is started for you: it reads id, loops over the products and has an if for the matching one. Fill it in: answer "product_id" and "rating", the average of the product's stars rounded to 2 places, or null when the product has no reviews. When no product has that ID, answer 404 with "Product not found".
Assignment
Follow the Coding Tutorial to finish the /rating route at the end of the file: answer the 404, collect the stars of the product's reviews, and answer their rounded average, or a null rating when there are none.
Hint
Copy the shape of the reviews routes for the 404 with errorResponse, and the shape of the GET /stats route for the slice, the empty check and the rounded average. In Go, answering doesn't stop the handler: end each answer inside the loop with return.
Free plan: 30 tutor messages. PRO is unlimited.
