A service can also be slow instead of broken: overloaded, it answers after many seconds, or never. http.Get waits as long as it takes, and so does your customer, while your shop keeps a handler busy for nothing.
Give the call a timeout: make an http.Client with Timeout: time.Second and call client.Get(url). When the time runs out, the client gives up: client.Get returns an error in err, and response is nil. Check err right after the call, before the defer line: after a timeout there is no response to close. Here it is in a weather app:
client := http.Client{Timeout: 2 * time.Second}
response, err := client.Get(weather + "/today/" + city)
if err != nil {
writeJSON(w, 504, map[string]string{"error": "The weather service took too long"})
return
}
defer response.Body.Close()
The status is 504 Gateway Timeout: like 502, the problem is behind your shop, and 504 says exactly what it was. The customer waits one second at most, and gets an answer either way.
The check makes the supplier take 2 seconds for one request with POST /check/supplier-slow, 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-slow {"times": 1} → 200 {"slow_next": 1}
GET /products/1/supplier-stock → 504 {"error": "The supplier took too long"}
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 url line, make client with a Timeout of time.Second, call client.Get(url) into response and err, and when err is not nil, answer "The supplier took too long" with 504 and return. The defer line and the 404 and 502 checks stay below, unchanged; the time import is already there.
Assignment
Follow the Coding Tutorial to give the supplier call a time limit and answer 504 when it runs out.
Hint
All the new lines go between the url line and the defer line. Timeout is a field of http.Client, and time.Second is one second.
Free plan: 30 tutor messages. PRO is unlimited.
