Go Lang and MongoDB Web App MVC pattern Part 2
Introduction
This is part two of a multi-part tutorial series explaining how to create a Go Lang and MongoDB web app with MVC pattern. Part one of this series explained how to configure Golang and create the sample dataset for the MongoDB database. Part two will cover how to configuring the database connection and create the files for the application.
Prerequisites
- Have a thorough understanding of part one of this series on creating a Go Lang and MongoDB web app with MVC pattern.
The Config Directory
- Referring back to part one of this series, the structure of the application and one of the directories was named
config
. This directory holds the Golang files responsible for database connection as well as other configurations.
Connecting to MongoDB database
This section we will cover configuring the database connection using a Go file.
- First, create a new Golang file inside the config directory and name it
Db.go
. Execute the following Go script to establish the database connection:
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 | package config import ( "fmt" _ "github.com/lib/pq" "gopkg.in/mgo.v2" ) // database var DB *mgo.Database // collections var Product *mgo.Collection func init() { // get a mongo sessions // connecting to mongodb with authentication. //s, err := mgo.Dial("mongodb://<username>:<password>localhost/bookstore") session, err := mgo.Dial("mongodb://localhost/EcommerceDb") if err != nil { panic(err) } if err = s.Ping(); err != nil { panic(err) } DB = session.DB("EcommerceDb") Product = DB.C("product") fmt.Println("You connected to your mongo database.") } |
NOTE: While this database connection is not using an authentication process, the code is provided in case authentication is required.
The above code initially performs a
mgo.Dial(URL)
that provides a pointer to a session and this will provide a pointer to aDB
.As the
DB
requires a database, specify the name of the databaseEcommerceDb
then assign it a pointer toDataBase
Now access the
C(-collection-)
from the pointerDB
. As this requires a collection name, provide the nameproduct
. This method will then provide a pointer to the collection assigned to the variableProduct
.Finally, a notification will be sent, via the console, once connection to the database is established.
The Template Configuration
This section will explain how to create another Go file to complete the file for the config directory. This file will be the map where the views, or the front end, of the application is located.
To do this, create another Go file and name it template.go and then execute the following command:
1 2 3 4 5 6 7 8 9 10 | package config import "html/template" // TPL *template.Template var TPL *template.Template func init() { TPL = template.Must(template.ParseGlob("templates/*.gohtml")) } |
The above code is designed to find all of the templates that match a particular pattern, in this case *.gohtml pattern, and store the templates.
The Controller
This section we will discuss how to create the controller for the web application. The controller within the MVC framework works like a bridge that connects the front and back ends of the application so the business logic codes will not be exposed.
- Create a new file within the config directory and name it controller.go with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package model import ( "ecommerce/config" "net/http" ) func Index(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed) return } pr, err := AllProducts() if err != nil { http.Error(w, http.StatusText(500)+err.Error(), http.StatusInternalServerError) return } config.TPL.ExecuteTemplate(w, "index.gohtml", pr) } |
The above code creates a function named index()
that calls for another function named AllProducts()
that resides in the models.go
file. This file processes and locates all of the documents within the MongoDB collection and passes the results to a page called index.gohtml
that will be handled by the tpl.go
file.
Configuring the Model
This section will demonstrate the first function in the model.
- Create a file within the
model
directory and name it models.go by executing the following code:
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 | package model import ( "ecommerce/config" "gopkg.in/mgo.v2/bson" ) // Product struct() type ProductCat struct { Sku string ` bson:"sku"` Title string `bson:"title"` Description string `bson:"description"` Qty int `bson:"qty"` Pricing int `bson:"pricing"` } func AllProducts() ([]ProductCat, error) { pr := []ProductCat{} err := config.Product.Find(bson.M{}).All(&pr) if err != nil { return nil, err } return pr, nil } |
Following is a breakdown of the above code:
- The code first creates a
struct
called ProductCat that serves as the collection of fields that mimics the fields in the database. - The
func AllProducts()
then retrieves all existing records within MongoDB using the methodFind()
.
Conclusion
This was part two of a multi-part tutorial series explaining how to create a Go Lang and MongoDB web app with MVC pattern. Part two reviewed how to set up the config directory, explained in part one, and then covered how to connect to the MongoDB database. This part of the tutorial series also explained how to set up the initial controller and configure the first model for the Go Lang and MongoDB web app with MVC pattern. Part three in this series will continue explaining how to set up additional parts of the application. Jump to top
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started