So i have built a simple REST API with Gin, that can make POST, and GET requests to add user objects and retrieve them. The users are of type struct, and and are stored in a slice. This just runs in memory, and is therefore not connected to a database.
I wanted to create a new function, that can update an existing user with a PATCH request, but what i made doesn't seem to work correctly:
func updateUser(c *gin.Context) {
id := c.Param("id")
var updatedUser user
if err := c.BindJSON(&updatedUser); err != nil {
return
}
updatedId := updatedUser.ID
updatedFirstName := updatedUser.FirstName
updatedLastName := updatedUser.LastName
updatedEmail := updatedUser.Email
for _, user := range users {
if updatedUser.ID == id {
user.ID = updatedId
user.FirstName = updatedFirstName
user.LastName = updatedLastName
user.Email = updatedEmail
users = append(users, updatedUser)
c.JSON(http.StatusCreated, gin.H{"success": "user updated"})
return
}
}
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
}
This just creates a new user and appends it to the end of my slice, instead of updating the user with id specified in the URL with the request. How can i make this function work, to update the values of my user object, while still keeping the same order in the slice?