DEV Community

Marcos Silva
Marcos Silva

Posted on

Building a Simple CRUD Application with Go: An Overview about the project PT/2

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
}

Enter fullscreen mode Exit fullscreen mode

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:

CRUD Project

Apache AGE

Top comments (0)