This article explains how to implement a PUT endpoint for updating products in a web application.
In this lesson, we detail how to add a new route for the PUT endpoint to update a specific product. This endpoint follows a structure similar to our GET and POST endpoints, with the PUT HTTP method enabling data updates.
Next, implement the updateProduct handler. The first step involves extracting the product ID from the URL, which is necessary to determine which product to update.
Copy
Ask AI
func (app *App) updateProduct(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) key, err := strconv.Atoi(vars["id"]) if err != nil { sendError(w, http.StatusBadRequest, "invalid product ID") return }}
Once you have successfully extracted the product ID, decode the user-provided JSON payload to update the product. The process is similar to the one used in the createProduct method. For reference, here is the original createProduct function:
Copy
Ask AI
func (app *App) createProduct(w http.ResponseWriter, r *http.Request) { var p product err := json.NewDecoder(r.Body).Decode(&p) if err != nil { sendError(w, http.StatusBadRequest, "Invalid request payload") return } err = p.createProduct(app.DB) if err != nil { sendError(w, http.StatusInternalServerError, err.Error()) return } sendResponse(w, http.StatusOK, p)}
For updating a product, the handler decodes the JSON payload and assigns the extracted product ID to the product before calling the updateProduct method:
Copy
Ask AI
func (app *App) updateProduct(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) key, err := strconv.Atoi(vars["id"]) if err != nil { sendError(w, http.StatusBadRequest, "invalid product ID") return } var p product err = json.NewDecoder(r.Body).Decode(&p) if err != nil { sendError(w, http.StatusBadRequest, "Invalid request payload") return } p.ID = key err = p.updateProduct(app.DB) if err != nil { sendError(w, http.StatusInternalServerError, err.Error()) return } sendResponse(w, http.StatusOK, p)}
Now, create the updateProduct method. This function updates the product’s attributes based on its ID. Notice the check to ensure that at least one row was affected by the update:
Copy
Ask AI
func (p *product) updateProduct(db *sql.DB) error { query := fmt.Sprintf("update products set name='%v', quantity=%v, price=%v where id=%v", p.Name, p.Quantity, p.Price, p.ID) result, err := db.Exec(query) if err != nil { return err } rowsAffected, err := result.RowsAffected() if err != nil { return err } if rowsAffected == 0 { return errors.New("No such row exists") } return nil}
Ensure that your database user has proper permissions for executing update queries and that the table schema matches the fields being updated.
When the update is successful, verify that the response returns the updated product data and that subsequent GET requests display the updated information.