Every answer from a server starts with a status code: a number that says how the request went. 200 OK means the body holds what you asked for. 404 Not Found means there is nothing at that address. A 404 is not a crash: the request went out, the server answered, and http.Get returns no error. In Go, you read the code in response.StatusCode.
The status tells you what the body holds, so check it before you use the body. Here is the idea on another page of the supplier:
response, _ := http.Get(supplier + "/catalog?page=1")
defer response.Body.Close()
if response.StatusCode == 200 {
fmt.Println("Got the page")
}
Your script looks up three product ids: 3, 99 and 5. The supplier has no product 99, so it answers 404, and its body holds an error instead of a product. A Go map gives nil for a missing key, so reading product["name"] from that body would quietly print <nil> costs <nil>, as if it were a product.
GET /prices/3 → 200 {"name": "Lamp", "price": 14, …}
GET /prices/99 → 404 {"error": "No product with that id"}
GET /prices/5 → 200 {"name": "Plant", "price": 6, …}
Your script must print:
Product 3 - status 200 Lamp costs 14 Product 99 - status 404 No such product at the supplier Product 5 - status 200 Plant costs 6
Your task: loop over productIDs, get /prices/ followed by each id, and print the id and its status code. For a 200, decode the body into a map and print the product's name, "costs" and its price. For a 404, print "No such product at the supplier".
Assignment
Follow the Coding Tutorial to request each product, print its status code and handle the 200 and 404 answers.
Hint
The id is an int, so turn it into text with strconv.Itoa(productID) before you join it to the address. Print the status before the if, and start the else if line with the } that closes the if.
Free plan: 30 tutor messages. PRO is unlimited.
