Start learning free

LESSON 17 OF 173 · BACKEND: YOUR FIRST API

When It Isn't There in Go

Practice

When no product has the id that was asked for, the loop in the "GET /products/{id}" handler ends without writing anything. A Go handler that writes nothing still gets an answer: net/http sends 200 OK with an empty body. The client reads 200 as "it worked", then finds no product to read. But the product just isn't there, and the answer should say so.

The status code tells the client how its request went: 200 means OK, 404 means Not Found, 500 means the server failed. The writeJSON helper takes the status as its second argument, so the same helper can send any status. For example, a members-only page could answer 403, which means Forbidden:

app.HandleFunc("GET /vip", func(w http.ResponseWriter, r *http.Request) {
	forbidden := map[string]string{"error": "Members only"}
	writeJSON(w, 403, forbidden)
})

An API answers its errors in JSON too, like {"error": "Product not found"}, so the client's program can read what went wrong. The error belongs after the loop: a match writes the product and returns, so those lines run only when no product matched.

Your app must answer:

GET /products/99    →  404  {"error": "Product not found"}
GET /products/2     →  200  {"id": 2, "name": "Notebook", "price": 7, "category": "office"}
GET /products/0     →  404  {"error": "Product not found"}
GET /products/5     →  404  {"error": "Product not found"}
GET /products/lamp  →  404  404 page not found (plain text)

Your task: after the loop in the "GET /products/{id}" handler, make a map named notFound with the key "error" and the value "Product not found", and answer it as JSON with the status 404.


Assignment
Follow the Coding Tutorial to answer 404 with a JSON error when no product has the requested id.


Hint
The two new lines go after the loop's closing }, not inside it. The status is writeJSON's second argument, where the other handlers have 200.


STEP 1 OF 2
    Ctrl + Enter to check

    Shop Not Found in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free