Go Lang and PostgreSQL Web App MVC pattern Part 7

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

This is Part 7, the final lesson in the multiple-series tutorial “Go Lang and PostgreSQL Web App with MVC pattern.” Today, you’ll learn how to perform the DELETE operation against a PostgreSQL record in your web app with the Model-View-Controller (MVC) pattern.

If you’re familiar with how to use the DELETE operation and want to skip the details, you can jump to The Code.

Prerequisites

  • Complete Parts 1 through 6 of the multiple-series tutorial, “Go Lang and PostgreSQL Web App with MVC pattern.”

Delete a Record in PostgreSQL using Go Lang

  • Modify your file main.go. To do this, add a new handler to give the DELETE functionality to your Go Lang and PostgreSQL Web App with MVC pattern like this:
1
2
3
4
5
6
7
8
9
10
11
12
http.HandleFunc("/", index)
http.HandleFunc("/list", model.PatientIndex)
http.HandleFunc("/patient/show", model.PatientShow)
http.HandleFunc("/patient/create", model.PatientCreate)
http.HandleFunc("/patient/create/process", model.PatientCreateProcess)
http.HandleFunc("/patient/update", model.PatientUpdate)
http.HandleFunc("/patient/update/process", model.UpdateProcess)
// below are the newly added code(s)
http.HandleFunc("/patient/delete/process", model.PatientDeleteProcess)
// end of of newly added code(s)

http.ListenAndServe(":8080", nil)
  • The code above is the beginning of the setup for the handler that will take care of the request to delete a record you select in your web app.

Controller for Deleting a Record in PostgreSQL using Go Lang

  • Now, the controller must be created to complete the code.

  • While inside the file handler.go, construct a function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func PatientDeleteProcess(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
        return
    }

    err := DeletePatient(r)
    if err != nil {
        http.Error(w, http.StatusText(400), http.StatusBadRequest)
        return
    }

    http.Redirect(w, r, "/list", http.StatusSeeOther)
}

Here is an explanation about the script you just entered above:

  • The file models.go contains the DeletePatient() function and the code you just inputted above will invoke it.

  • The record deletion process is complete. In other words, the business logic in MVC takes place when the controller lets the model know which record to delete. Next, the view is alerted that the model has been modified for your Go Lang and PostgreSQL Web App with MVC pattern.

NOTE: Handlers must be triggered. To complete this step, go ahead and update the index.gohtml file

Configuring Model for Deleting a Record in PostgreSQL using Go Lang

  • To enable the DELETE function to work properly, configure the model:
1
2
3
4
5
6
7
8
9
10
11
12
func DeletePatient(r *http.Request) error {
    pID := r.FormValue("id")
    if pID == "" {
        return errors.New("400. Bad Request.")
    }

    _, err := config.DB.Exec("DELETE FROM tbl_patientinfo WHERE patient_id=$1;", pID)
    if err != nil {
        return errors.New("500. Internal Server Error")
    }
    return nil
}

Regarding the code you just entered above:

  • After you sent the URL request, it obtained the FormValue of the record you want to delete.

Time to test your Go Lang and PostgreSQL Web App with MVC pattern DELETE function capability.

  • The result should look similar to this:

Conclusion

This concludes the final lesson on the multiple-series tutorial “Go Lang and PostgreSQL Web App with MVC pattern”. In Part 7, you learned how to perform the DELETE operation against a PostgreSQL record. Review Parts 1 through Part 7 to simplify your coding with PostgreSQL and Go Lang. Reference them anytime.

The Code

Here’s the entire code for this particular lesson, Part 7, which covers programming the DELETE operation for Go Lang and PostgreSQL Web App with MVC pattern.

The main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
    "html/template"
    "net/http"
    "patientinfo/model"

    _ "github.com/lib/pq"
)

// package level scope, which means it can be accessed anywhere in this packager.
var tpl *template.Template

func main() {
http.HandleFunc("/", index)
http.HandleFunc("/list", model.PatientIndex)
http.HandleFunc("/patient/show", model.PatientShow)
http.HandleFunc("/patient/create", model.PatientCreate)
http.HandleFunc("/patient/create/process", model.PatientCreateProcess)
http.HandleFunc("/patient/update", model.PatientUpdate)
http.HandleFunc("/patient/update/process", model.UpdateProcess)

// below are the newly added code(s)
http.HandleFunc("/patient/delete/process", model.PatientDeleteProcess)
// end of of newly added code(s)

http.ListenAndServe(":8080", nil)
}

func index(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "/list", http.StatusSeeOther)
}

The index.gohtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>

    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Create Patient</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    </head>
    <body>

        <!--[if lt IE 7]>
           <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
       <![endif]-->

    <div class="container mt-4">
        <h1>Patients Listing</h1>


        <table class="table table-sm table-bordered ">
            <thead class="thead-dark">

            <tr>
                <th>id</th>
                <th>Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Age</th>
                <th> </th>
                 <th scope="col" colspan="3">Action</th>
            </tr>

            </thead>

            {{range .}}
            <tbody id="myTable">

                <tr>
                    <td>{{.Patient_id}}</td>
                    <td>{{.Name}}</td>
                    <td>{{.Lastname}}</td>
                    <td>{{.Gender}}</td>
                    <td>{{.Age}}</td>
                     <td><a class="action" href="/patient/show?id={{.Patient_id}}">View</a></td>
                    <td><a class="action" href="/patient/update?id={{.Patient_id}}">Edit</a></td>
                    <td><a class="action" href="/patient/delete/process?id={{.Patient_id}}">Delete</a></td>
                </tr>
            </tbody>
            {{end}}

        </table>
        <a class="action btn btn-primary" href="/patient/create">Add Patient</a>

    </div>


        <script src="" async defer></script>
    </body>
</html>

The models.go

1
2
3
4
5
6
7
8
9
10
11
12
func DeletePatient(r *http.Request) error {
    pID := r.FormValue("id")
    if pID == "" {
        return errors.New("400. Bad Request.")
    }

    _, err := config.DB.Exec("DELETE FROM tbl_patientinfo WHERE patient_id=$1;", pID)
    if err != nil {
        return errors.New("500. Internal Server Error")
    }
    return nil
}

The handler.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func PatientDeleteProcess(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
        return
    }

    err := DeletePatient(r)
    if err != nil {
        http.Error(w, http.StatusText(400), http.StatusBadRequest)
        return
    }

    http.Redirect(w, r, "/list", http.StatusSeeOther)
}

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.