Go Lang and MongoDB Web App MVC pattern Part 7
Introduction
This is part seven of a multi-part tutorial series explaining how to create a Go Lang and MongoDB web app with MVC pattern. Parts one through six of this seven-part tutorial series covered how to set up the project development environment and create a sample database in MongoDB, configure the database connection and create the files for the application, how to add new files and test the configurations, how to insert a MongoDB document and create parts of the CRUD
operation. Part seven will now explain how to perform the ‘DELETE’ operation against a selected MongoDB document. If there are any doubt as to the comprehension of the functions explained in the first six parts of this series, parts one through six of this tutorial should be reviewed before proceeding with part seven.
Prerequisites
- Have a thorough command of the first six parts of this series on how to create a Go Lang and MongoDB web app with MVC pattern.
Delete a MongoDB Document using Go Lang
This part of the tutorial series will explain the final function of the Go Lang and MongoDB Web App with MVC pattern, namely how to delete a selected MongoDB document.
- Begin by modifying the mongo.go file. Execute the following code to add a new handler for processing a delete request from a user.
1 2 3 4 5 6 7 8 9 10 | http.HandleFunc("/", index) http.HandleFunc("/products", model.Index) http.HandleFunc("/products/show", model.ShowProduct) http.HandleFunc("/products/form", model.CreateForm) http.HandleFunc("/products/create/process", model.ProductCreateProcess) http.HandleFunc("/products/update/form", model.UpdateForm) http.HandleFunc("/products/update/process", model.ProductUpdateProcess) // handles the URL 'localhost:8080/products/delete/process http.HandleFunc("/products/delete/process", model.ProductDeleteProcess) http.ListenAndServe(":8080", nil) |
- The above commands create a new request handler that will directly call a delete controller function to process a delete request instantly.
Controller for Deleting a Record in MongoDB Document using Go Lang
This section will explain how to create the controller for the delete request.
First, create a new function inside handler.go and name it
PatientDeleteProcess
.To create the controller for the delete request of the user, an ‘sku’ field is required as the parameter. Call up the
ProductDeleteProcess()
function as shown here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | func ProductDeleteProcess(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed) return } err := DeleteProduct(r) if err != nil { http.Error(w, http.StatusText(400), http.StatusBadRequest) return } http.Redirect(w, r, "/products", http.StatusSeeOther) } |
Following is a breakdown of the above code:
- First, a function named
DeleteProduct()
is called within the models.go file. - The system then redirects the user to the product listing page if the delete operation is successful.
NOTE: In order to trigger the handler that was created in the previous sections, the index.gohtml
code must be updated as follows:
-td--a class="action" href="/product/delete/proecess?id={{.sku}}-Delete-/a--/td-
.
Configuring Model for Deleting a Record in PostgreSQL using Go Lang
This section will explain the main process that performs the DELETE
operation against a selected MongoDB document.
The following code will perform the delete operation using the Remove()
method with a value from a form value:
1 2 3 4 5 6 7 8 9 10 11 12 | func DeleteProduct(r *http.Request) error { sku := r.FormValue("sku") if sku == "" { return errors.New("400. Bad Request.") } err := config.Product.Remove(bson.M{"sku": sku}) if err != nil { return errors.New("500. Internal Server Error") } return nil } |
With the required configuration and functions completed, the application can now be tested as shown in the following image:
Conclusion
This was the final part in a seven-part tutorial series covering how to create a Go Lang and MongoDB Web App with MVC pattern. Part seven focused specifically on how to perform the delete operation against a selected MongoDB document. The article explained how to create new a request handler for directly calling a delete controller function, how to create a controller for deleting a record in MongoDB using Golang and configuring the model for deleting a record in PostgreSQL using Golang. Remember that a new function inside the handler.go file must first be set up in order to create the controller for the delete request.
The Code
Following is the code for the files used in this tutorial:
The main.go
1 2 3 4 5 6 7 8 9 10 | http.HandleFunc("/", index) http.HandleFunc("/products", model.Index) http.HandleFunc("/products/show", model.ShowProduct) http.HandleFunc("/products/form", model.CreateForm) http.HandleFunc("/products/create/process", model.ProductCreateProcess) http.HandleFunc("/products/update/form", model.UpdateForm) http.HandleFunc("/products/update/process", model.ProductUpdateProcess) // handles the URL 'localhost:8080/products/delete/process http.HandleFunc("/products/delete/process", model.ProductDeleteProcess) http.ListenAndServe(":8080", nil) |
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 63 | <!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Products</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 class="text-center" >Products Listing</h1> <table class="table table-sm table-bordered "> <thead> <tr> <th>Sku</th> <th>Title</th> <th>Description</th> <th>Quantity</th> <th>Pricing</th> <th> </th> <th scope="col" colspan="3">Action</th> </tr> </thead> <tbody > {{ range . }} <tr> <td>{{ .Sku }}</td> <td>{{ .Title }}</td> <td>{{ .Description }}</td> <td>{{ .Qty }}</td> <td>{{ .Pricing }}</td> <td><a class="action" href="/products/show?sku={{.Sku}}">View</a></td> <td><a class="action" href="/products/update/form?sku={{.Sku}}">Edit</a></td> <td><a class="action" href="/products/delete/process?sku={{.Sku}}">Delete</a></td> </tr> {{end}} </tbody> </table> <a class="action btn btn-primary" href="/products/form">Add Product</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 DeleteProduct(r *http.Request) error { sku := r.FormValue("sku") if sku == "" { return errors.New("400. Bad Request.") } err := config.Product.Remove(bson.M{"sku": sku}) if err != nil { return errors.New("500. Internal Server Error") } return nil } |
The controller.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | func ProductDeleteProcess(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed) return } err := DeleteProduct(r) if err != nil { http.Error(w, http.StatusText(400), http.StatusBadRequest) return } http.Redirect(w, r, "/products", http.StatusSeeOther) } |
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started