Start learning free

LESSON 23 OF 173 · BACKEND: YOUR FIRST API

Update a Product (PUT) in Go

Practice

Prices change. To change a product that already exists, a client sends PUT to the product's own path, with the new version of the product in the JSON body. The server replaces the stored name, price and category with the ones it got. The id comes from the path, so it never changes.

A PUT handler is registered like the handlers you know, with "PUT /path" as its pattern. Here is a small one that replaces a value in a map settings (not part of the shop):

var settings = map[string]string{"theme": "light"}

app.HandleFunc("PUT /settings", func(w http.ResponseWriter, r *http.Request) {
	var data map[string]string
	json.NewDecoder(r.Body).Decode(&data)
	settings["theme"] = data["theme"]
	writeJSON(w, 200, settings)
})

The shop holds many products in a slice, so your PUT first finds the one whose id is in the path, with the same loop as the DELETE handler. One Go detail: in for i, product := range products, product is a copy of the item, so you change the stored one, products[i]. The handler answers the changed product with 200 OK, or 404 when no product has that id. The requests and answers your code must give, in this order:

PUT /products/2  {"name": "Notebook", "price": 9, "category": "office"}
  →  200  {"id": 2, "name": "Notebook", "price": 9, "category": "office"}
GET /products/2  →  200  {"id": 2, "name": "Notebook", "price": 9, "category": "office"}
PUT /products/4  {"name": "Blue pen", "price": 3, "category": "office"}
  →  200  {"id": 4, "name": "Blue pen", "price": 3, "category": "office"}
PUT /products/99  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  404  {"error": "Product not found"}
GET /products  →  200  [{"id": 1, "name": "Mug", …}, {"id": 2, "name": "Notebook", "price": 9, …}, {"id": 3, "name": "Lamp", …}, {"id": 4, "name": "Blue pen", "price": 3, …}]

Your task: add a handler for PUT /products/{id}. It decodes the JSON body into a Product, finds the product with that id, sets its name, price and category to the values in the body, and answers the changed product. When no product has that id, it answers 404 with {"error": "Product not found"}.


Assignment
Follow the Coding Tutorial to add the PUT handler that replaces a product's name, price and category.


Hint
The first line is the one of the DELETE handler, and so is the loop with i and product. Change and answer products[i], not the copy product. Answer and return inside the if, and put the 404 after the loop, so it only runs when no product matched.


STEP 1 OF 12
    Ctrl + Enter to check

    Shop Update Product 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