Go Lang and MongoDB Web App MVC pattern Part 3

Introduction

This is part three in a step-by-step tutorial series explaining how to create a Go Lang and MongoDB web app with MVC pattern. Part one explained how to set up the project development environment and create a sample database in MongoDB and part two covered how to configuring the database connection and create the files for the application. Part three will now explain how to add a few new configurations and additional files to the application as well as set up a quick test to confirm the initial configurations are working properly.

Prerequisites

  • A solid understanding of the first two parts of this tutorial series on how to create a Go Lang and MongoDB Web App with MVC pattern.

Configure the Main application

Part two of this series covered how to configured the controller and the model of the Go Lang and MongoDB web app with MVC pattern. This section will explain how to handle the user request using the Golang handler HandleFUnc() method.

  • First, create another Go file in the root directory of the project and name it main.go. Now execute the following code:
package main

import (
    "ecommerce/model"
    "net/http"
)

func main() {
    http.HandleFunc("/", index)
    // handles the URL 'localhost:8080/products
    http.HandleFunc("/products", model.Index)
    // this is where the web application will listen
    http.ListenAndServe(":8080", nil)
}

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

Following is a breakdown of the above code:

  • The package mainat the very beginning of the code tells the application to compile this file as an executable program so it can be used as an entry point of the application.

  • The import() command imports the dependencies into the file as needed.

  • The http.HandleFunc() method, mentioned in the previous section, monitors the request coming from the user and will match it accordingly to the specified functions.

Configure the View (Front End)

This section will cover creating the front end, or the view, of the application.

First, a new file must be created within the templates directory. Name the file ‘index.gohtml’ and then append the file with the following code:

<!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>Products Listing</h1>


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

            <tr>
                <th>Id</th>
                <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>{{ .ID }}</td>
                    <td>{{ .Sku }}</td>
                    <td>{{ .Title }}</td>
                    <td>{{ .Description }}</td>
                    <td>{{ .Qty }}</td>
                    <td>{{ .Pricing }}</td>
                     <td><a class="action" href="">View</a></td>
                    <td><a class="action" href="">Edit</a></td>
                    <td><a class="action" href="">Delete</a></td>
                </tr>
            {{end}}
            </tbody>



        </table>
        <a class="action btn btn-primary" href="">Add Product</a>

    </div>


        <script src="" async defer></script>
    </body>
</html>
  • The above is just a normal HTML structure.

  • Since the application has access to the package text\html that allows for the generation of dynamic data, it uses the curly brackets in this format: {{}}.

  • The . (dot) allows access of the elements within a data structure, such as the field of a struct or a key within a map. Here the values from the struct, configured in part two of this series, were accessed as shown in the following code:

<td>{{ .ID }}</td>
<td>{{ .Sku }}</td>
<td>{{ .Title }}</td>
<td>{{ .Description }}</td>
<td>{{ .Qty }}</td>
<td>{{ .Pricing }}</td>

Testing the Web Application

This section will explain how to run the application to confirm the initial configuration is working properly.

  • First, open the command line or terminal. Only from the root of the project directory, execute the following command:
go run main.go

A conformation should appear in the command line saying: You are connected to your mongo database.

Now navigate to the application using the chrome browser with the following URL: http://localhost:8080/products

The output should resemble the following:

Conclusion

This was part three in a step-by-step tutorial series on how to create a Go Lang and MongoDB web app with MVC pattern. Part three explained how to handle the user request using the Golang handler HandleFUnc() method, configure the front end, create the first template to display the MongoDB documents and then test the web application. Remember that it is critical to only execute the command from the root of the project directory when testing the web app. Part four in this series will continue expanding on how to create a Go Lang and MongoDB Web App with MVC pattern.

The Code

Following is the code of the files used in this application:

The main.go

package main

import (
    "ecommerce/model"
    "net/http"
)

func main() {
    http.HandleFunc("/", index)
    // handles the URL 'localhost:8080/products
    http.HandleFunc("/products", model.Index)
    // this is where the web application will listen
    http.ListenAndServe(":8080", nil)
}

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

The index.gohtml

<!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>Products Listing</h1>


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

            <tr>
                <th>Id</th>
                <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>{{ .ID }}</td>
                    <td>{{ .Sku }}</td>
                    <td>{{ .Title }}</td>
                    <td>{{ .Description }}</td>
                    <td>{{ .Qty }}</td>
                    <td>{{ .Pricing }}</td>
                     <td><a class="action" href="">View</a></td>
                    <td><a class="action" href="">Edit</a></td>
                    <td><a class="action" href="">Delete</a></td>
                </tr>
            {{end}}
            </tbody>
        </table>
        <a class="action btn btn-primary" href="">Add Product</a>
    </div>
        <script src="" async defer></script>
    </body>
</html>

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.