How to Build a Simple Golang and CockroachDB Web App via the MVC Pattern Part 2

Introduction

If you’re interested in building a web app that can interact with CockroachDB using the Golang language, there are many possibilities. You might want to create a CockroachDB record using Golang, you may want to update a CockroachDB record using Golang, or you even might need to delete from CockroachDB using Golang. Our first article in this multi-part series covered some of the initial tasks needed to get this project started. In this article, we’ll discuss the different parts of our project directories and the files associated with them.

Prerequisites

There’s only one key prerequisite that’s necessary to complete the steps outlined in this article– you need to make sure that you were able to finish the tasks described in Part 1 of this multi-part series.

The Config Directory

Our config directory can be described as a container of database settings and configuration files. Let’s take a closer look at those files and discuss each one.

How to connect Go to the CockroachDB database

The directory “config” will hold files associated with the database connection. We’ll need to create a file named db.go that will contain the following Go script.

// (1)
package config

// (2)
import (
"database/sql"
"fmt"

_ "github.com/lib/pq"
)


// (3)
var DB *sql.DB


// (4)
func init() {
var err error
connStr := "postgres://yeshua:password@localhost:26257/restaurants?sslmode=disable"
DB, err = sql.Open("postgres", connStr)
if err != nil {
panic(err)
}

// (5)
if err = DB.Ping(); err != nil {
panic(err)
}
fmt.Println("Connected to the database")
}

The code shown above might look a bit complicated, but it’s actually fairly simple Let’s see what’s going on in this script:

  1. First, package config simply tells about the package name.
  2. Then, the import statements will import the necessary dependencies.
  3. DB creates a variable that we can reference outside this package. We can also export this variable so we can use it anywhere in our files as needed.
  4. We use the func init() function to load the configuration of our database just once.
  5. Finally, DB.ping() just tells us if the connection was successful.

Controlling the Template access

At this point, we’re done with the configuration of the database. Now we’ll proceed to create a configuration file for our templates and discuss how to make them available as needed.

Let’s create another file in the “config” directory and save it as “tpl.go”. Then, add the following code to it:

package config

import "html/template"

var TPL *template.Template

func init() {
TPL = template.Must(template.ParseGlob("templates/*.gohtml"))
}

The code shown above will simply parse all the templates in the “templates” directory, then it will assign them to TPL and make it available as needed. We’ll see more clearly how both of these config files work in the next part of this article.

The Controller in Model-View-Controller

In this section, we’ll be discussing how to create a controller for our web app. The controller part of the MVC pattern serves as the bridge that helps the view and the model to communicate with each other.

Let’s create a controller file named “handlers.go” and add the following code to it:

NOTE: The code will be broken down into sections labeled with numbers so we can discuss each part.

// (1)
package controllers

// (2)
import (
"database/sql"
"net/http"
"webGo/config"
"webGo/models"
)

// (3)
func Index(w http.ResponseWriter, r *http.Request) {


if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}


// (4)
restos, err := models.AllResto()

if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}

// (5)
config.TPL.ExecuteTemplate(w, "index.gohtml", restos)
}

Let’s discuss the above code one section at a time:

  1. The package controllers statement simply tells the name of the package.
  2. The import statements import the necessary dependencies for this package.
  3. The func Index() function serves as the controller that will handle the request from the user when they first navigate to our web app.
  4. We use models.AllResto() which calls the function AllResto() from the package models. This function will be covered in the next article.
  5. We use TPL from package config so we can serve the template against the request of the user.

NOTE: Notice that package controllers handles the communication between the model models.AllResto() and the view index.gohtml, in keeping with the MVC pattern.

Conclusion

In this second part of out multi-part series, we discussed how we can create controllers to handle the communication between the model and the view of our web app. We’ve made a lot of progress in this project so far, but we’re not done yet: The model part of the MVC will be discussed in the next article.

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.