Start learning free

LESSON 71 OF 173 · BACKEND: APIS WITH A DATABASE

Update a Product (UPDATE) in Go

Practice

Prices change: the Notebook costs 9 now, not 7. To change a product, a client sends a PUT to the product's own path, like /products/2, with its new name, price and category in the JSON body. Your handler turns it into an UPDATE statement.

Here is an UPDATE on another table, a list of newsletter subscribers:

res, _ := db.Exec("UPDATE subscribers SET email = ? WHERE id = ?", "sam@example.com", 3)
changed, _ := res.RowsAffected()
fmt.Println(changed)   // 1 if subscriber 3 exists, 0 if not

db.Exec runs a statement that gives back no rows, and the change is saved at once. The WHERE limits the change to one row: without it, every row of the table changes. An UPDATE that matches no row is not an error, it just changes nothing, so res.RowsAffected() is 0: that's when you answer 404. Columns the UPDATE doesn't name, like stock, keep their values.

Starting from the shop's 8 products, your code must answer:

PUT /products/2  {"name": "Notebook", "price": 9, "category": "office"}  →  200  {"id": 2, "name": "Notebook", "price": 9, "category": "office", "stock": 0}
PUT /products/8  {"name": "Gift card", "price": 40, "category": "gifts"}  →  200  {"id": 8, "name": "Gift card", "price": 40, "category": "gifts", "stock": 999}
PUT /products/99  {"name": "Cup", "price": 5, "category": "kitchen"}  →  404  {"error": "Product not found"}
GET /products?category=gifts  →  200  [{"id": 8, "name": "Gift card", "price": 40, "category": "gifts", "stock": 999}]

Your task: add the handler PUT /products/{id}. Update that product's name, price and category with ? placeholders. Answer 404 if no row changed, and otherwise the product as it is stored now.


Assignment
Follow the Coding Tutorial to add the PUT /products/{id} handler, which changes a product in the database.


Hint
The values go in the same order as the ?s: data.Name, data.Price, data.Category, then id for the WHERE. After the UPDATE, read the row again with the SELECT from the GET /products/{id} handler, scanning it into data.


STEP 1 OF 12
    Ctrl + Enter to check

    Db Update 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