Go Lang and PostgreSQL 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 PostgreSQL Web App with MVC pattern. Part two will cover the various parts and required fields of the web application and how to configure Golang to use the MVC framework. The MVC design is one of the most-used web application models and allows programmers to create easily maintainable web applications.

Prerequisite

  • Have a thorough understanding of part one of this tutorial series on how to use Go Lang and PostgreSQL Web App with MVC pattern.

Config Directory

Part one of this tutorial series explained the structure of the web application, with one of the directories being named config. The config directory holds the database connection and configuration files of the application.

Connecting to PostgreSQL database

Remember from part one of this series, the config directory contains the code for the database connection. Here a new file must be created. For this example the file will be named db.go. Execute the following script to create the database connection:

package config

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

var DB *sql.DB

func init() {
    var err error
    DB, err = sql.Open("postgres", "postgres://postgres:1234@localhost/patientinfo?sslmode=disable")
    if err != nil {
        panic(err)
    }

    if err = DB.Ping(); err != nil {
        panic(err)
    }
    fmt.Println("Database connection is succesful")

}

Here is a breakdown of the above script:

  • The uppermost part of the script specifies where this file will be located within the application, the package config in this case.
  • Next, the needed dependencies are imported via the import method.
  • The variable DB for the pointer for the database is created. Making the letters uppercase allows for access of this variable outside this config package, meaning its scope is global.
  • Now the func init() is used to load the entire database configuration.
  • Finally, the DB.Ping() confirms that the connection to the database was successful.

The Templates Directory

In this section the templates of the web app will be configured. This enables the changing of the view of the front-end presentation as the different functions on the web app are performed.

  • First, a new file must be created within the config directory. Here the file will be named template.go.

  • Create the template.go file with the following code:

package config

import "text/template"

var TPL *template.Template

func init() {
    TPL = template.Must(template.ParseGlob("templates/*.gohtml"))
}
  • The above script will parse all of the incoming requests as the template function is called. This template will serve the requested template within any given operation.

Configure the web app controller

  • This section will explain how to create the controller for the web application. The controller in the MVC framework bridges the View, or the front-end, and the Model, or the business logic, of the web app.

  • Create a new file within the model folder and name it handler.go

The first route for the application will be created within this file by executing the following code:

package model

import (
    "net/http"
    "patientinfo/config"
)
func PatientIndex(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
        return
    }
    patients, err := ShowAllPatients()
    if err != nil {
        http.Error(w, http.StatusText(500), http.StatusInternalServerError)
        return
    }
    config.TPL.ExecuteTemplate(w, "index.gohtml", patients)
}

Following is a breakdown of the above script:

  • The uppermost part of the code states what the package does with the file, in this case it belongs to package model.

  • Referring to the import() method, this part of the script downloads the needed dependencies.

  • A function named PatientIndex() is created and the ShowAllPatient() method function is then created inside that function. This will be discussed in greater detail later on in the tutorial series.

  • Finally, the script creates the TPL needed to serve the template for the front-end and data for showing all of the record. In this case this is the patient’s record via the patients object.

Configuring the Model

This section will cover configuring the first business logic of the application.

  • First, a file within the model directory must be created. Name the file models.go.

  • Now execute the following script:

package model

import "patientinfo/config"

// Fields first letter must be uppercase so we can export them to templates.
type Patient struct {
    Patient_id string
    Name       string
    Lastname   string
    Gender     string
    Age        int
}

// Show all patients
func ShowAllPatients() ([]Patient, error) {

    rows, err := config.DB.Query("SELECT * FROM tbl_patientinfo")

    if err != nil {
        return nil, err
    }
    defer rows.Close()

    patients := make([]Patient, 0)
    for rows.Next() {
        patient := Patient{}
        err := rows.Scan(&patient.Patient_id, &patient.Name, &patient.Lastname, &patient.Gender, &patient.Age)
        if err != nil {

            return nil, err
        }
        patients = append(patients, patient)
    }
    if err = rows.Err(); err != nil {
        return nil, err
    }

    return patients, nil
}

A breakdown of the above code follows:

  • First, the code creates a struct of the Patient model that serves as the collection of fields that mimics the database fields.
  • The func ShowAllPatients() retrieves all of the existing records within the database using the SELECT operation.
  • Finally, the rows.next() method is used to iterate the records and return the results as patients.

Conclusion

This was part two of a tutorial series explaining how to create a Go Lang and PostgreSQL Web App with MVC pattern. Part two covered the various parts and required fields of the web app and how to configure Golang to use the MVC framework. The article specifically covered how to connect to the PostgreSQL database and set the templates directory, configure the web app controller and how to configure the model. The tutorial also provided a breakdown of the scripts used to execute the functions. Remember that a new file must be created within the config directory when configuring the templates.

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.