Start learning free

LESSON 22 OF 173 · BACKEND: YOUR FIRST API

Remove a Product

Practice

To remove something, a client uses the DELETE method and names what to remove in the path. DELETE /products/2 has the same path as GET /products/2, but a different method, so it needs its own handler, with DELETE in its pattern.

A Go slice has no remove method: you keep the items before index i, s[:i], and append the items after it, s[i+1:].... After a delete there is nothing to send back, so the answer is the status 204 No Content with no body: w.WriteHeader(204). Here is the idea on another route:

var tags = []string{"new", "sale", "gift"}

app.HandleFunc("DELETE /tags/{name}", func(w http.ResponseWriter, r *http.Request) {
	for i, tag := range tags {
		if tag == r.PathValue("name") {
			tags = append(tags[:i], tags[i+1:]...)
			w.WriteHeader(204)
			return
		}
	}
	writeJSON(w, 404, map[string]string{"error": "Tag not found"})
})

Your shop finds the product with a loop, like the GET handler for one product, and answers 404 with the same error when no product has that id. Your code must give, in this order:

DELETE /products/2   →  204  (empty body)
GET /products/2      →  404  {"error": "Product not found"}
GET /products        →  200  [{"id": 1, …}, {"id": 3, …}, {"id": 4, …}]
DELETE /products/2   →  404  {"error": "Product not found"}
DELETE /products/99  →  404  {"error": "Product not found"}
GET /products/count  →  200  {"count": 3}
POST /products  {"name": "Plant", "price": 15, "category": "home"}  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}

Your task: add a DELETE /products/{id} handler that removes the product with that id and answers 204 with an empty body, or 404 with {"error": "Product not found"} when there is no such product.


Assignment
Follow the Coding Tutorial to build the DELETE handler.


Hint
Find the product with the same loop as in the GET handler for one product, but keep the index i too. Stop with return right after the 204, inside the if; the 404 goes after the loop.


STEP 1 OF 8
    Ctrl + Enter to check