Other services break: a bug, a full disk, a deploy gone wrong. The supplier then answers 500 Internal Server Error, with JSON like {"error": "The supplier is down"}. That JSON has no "stock", and in Go a missing map key reads as 0. So your handler answers 200 with "supplier_stock": 0: a false stock, and the customer believes it.
Check the status before you trust the answer. Your handler is a gateway: a server that passes requests on to another server. When the server behind it fails, a gateway answers 502 Bad Gateway. Here is the idea in a weather app:
response, _ := http.Get(weather + "/today/" + city)
defer response.Body.Close()
if response.StatusCode != 200 {
writeJSON(w, 502, map[string]string{"error": "The weather service is not answering"})
return
}
var data map[string]int
502 tells the client that the problem is behind your shop: not in its request (a 4xx), and not a crash of your shop (a 500). Keep the 404 check first, so the Teapot still gets its 404; then "not 200" catches every other failure. End the new block with return, so the handler stops there.
The check switches the supplier off for one request with POST /check/supplier-down, a page that only exists in the tests. Your shop must answer:
GET /products/1/supplier-stock → 200 {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1} → 200 {"down_next": 1}
GET /products/1/supplier-stock → 502 {"error": "The supplier is not answering"}
GET /products/1/supplier-stock → 200 {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1} → 200 {"down_next": 1}
GET /products/3/supplier-stock → 502 {"error": "The supplier is not answering"}
GET /products/6/supplier-stock → 404 {"error": "The supplier doesn't sell this product"}
Your task: in the supplier-stock handler, below the 404 block, answer "The supplier is not answering" with 502 and return whenever response.StatusCode is not 200.
Assignment
Follow the Coding Tutorial to answer a clear 502 when the supplier fails, instead of passing on a false stock.
Hint
The new if goes between the 404 block and var data. Answer with writeJSON(w, 502, …), then return, like the 404 block does.
Free plan: 30 tutor messages. PRO is unlimited.
