Introduction
This is the part 2 of my overview about my golang project, in this project I did a CRUD application with golang, I will explain the UPDATE and the DELETE functions.
Functions
- Update(U) The UpdateUser function serves as a handler for updating a user's information.
func UpdateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "PUT")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
params := mux.Vars(r)
id, err := strconv.Atoi(params["id"])
if err != nil {
log.Fatalf("Cannot find the User by ID. %v", err)
}
var user models.User
// decoding json request to user
err = json.NewDecoder(r.Body).Decode(&user)
if err != nil {
log.Fatalf("Unable to decode the body. %v", err)
}
updatedRows := updateUser(int64(id), user)
msg := fmt.Sprintf("User updated! Total rows/record affected %v", updatedRows)
res := response{
ID: int64(id),
Message: msg,
}
// send the response
json.NewEncoder(w).Encode(res)
}
It extracts the necessary information from the request, updates the user's data, constructs a response message, and sends it back to the client.
- Delete(D) The Delete function handles the deletion of a user. It extracts the necessary information from the request, deletes the user's data, constructs a response message, and sends it back to the client.
func DeleteUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Context-Type", "application/x-www-form-urlencoded")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
params := mux.Vars(r)
id, err := strconv.Atoi(params["id"])
if err != nil {
log.Fatalf("Cannot convert the user ID. %v", err)
}
deletedRows := deleteUser(int64(id))
msg := fmt.Sprintf("User deleted! Total rows/record affected %v", deletedRows)
res := response{
ID: int64(id),
Message: msg,
}
json.NewEncoder(w).Encode(res)
}
The objective is to delete the user's data, constructs a response message, and sends it back to the client.
Conclusion
The objective of this project is to provide a comprehensive explanation of the workings of the CRUD project. For the next article I will work in explain the ROUTES of this project.
- References:
Top comments (0)