Simple MVC Example Using Golang Echo and MySQL

Simple MVC Example Using Golang Echo and MySQL

This is another golang tutorial for beginners, I am creating a simple MVC application using the Echo framework and Mysql Database. MVC stands for the model view and controller pattern. We will create models and handlers in a separate file, that help to easy and fast development for a big project.

I have already shared Creating a Go(lang) API with Echo Framework and PostgreSQL and Creating a Go(lang) API with Echo Framework and MySQL.These golang tutorial are not following the MVC pattern but use an echo framework.

The Model will be used to handle DB interaction, the View used to display information using the controller, and the Controller provides a medium to communicate between view and model.

We will create a listing operation to fetch data from the MySQL database using echo in the MVC pattern. It’s very easy to create add, edit and delete options using them.

There are following files will participate in this example:

  • server.go: This is the main go application entry file.
  • controllers/employee.go: This file will have all handlers methods.
  • db/db_connection.go: This file will have a database connection method and return the MySQL connection object.
  • models/employee.go: This file will have all database interaction-related methods.
go_echo_with_mvc

You can also check other recommended tutorials of golang,

  • Getting Started with GoLang
  • Creating a Go(lang) API with Echo Framework and PostgreSQL
  • Building GoLang Restful API Using Echo and MySQL
  • How To Use BasicAuth Middleware With Go Echo Framework
  • How to Write Log into Files in Go/Golang

Creating Golang MVC Application Using Echo framework and MySQL

We will create simple server.go file that has to route information with controller methods. I will create a restful API to fetch data from MySQL.The DB file will have database connection information. I am creating a separate file for handlers, database and model class.

I have created 'test' database and employee table(which has name, salary, and age column) into MySQL database server.

Step 1: We will create server.go file and add the below code to import the required package for this application.

package main

import (
        "github.com/labstack/echo"
        "github.com/labstack/echo/middleware"
        "net/http"
)

func main() {
        e := echo.New()
        e.Use(middleware.Logger())
        e.Use(middleware.Recover())

        e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
                AllowOrigins: []string{"*"},
                AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
        }))

        e.GET("/", func(c echo.Context) error {
                return c.JSON(http.StatusCreated, "Welcome mvc echo with mysql app using Golang")
        })

        e.Logger.Fatal(e.Start(":8081"))

}

Created echo framework instance using echo.New() method assigned into 'e' variable. I also added CORS for cross-origin access, for testing purposes added a simple HTTP rest call to show messages, golang app working fine using http://localhost:8081 url.
We are running golang app on ‘8081’ port, you can change the port as per system availability.

We will run the below command to get all external packages,

$ go get

Create Dattabase Connection with Golang

Step 2: Let’s Creates "db_connection.go()" file for database connection with go and MySQL into the DB folder.

package db

import (
        "database/sql"
        "fmt"
        _"github.com/go-sql-driver/mysql"
)

/*Create mysql connection*/
func CreateCon() *sql.DB {
        db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/test")
        if err != nil {
                fmt.Println(err.Error())
        } else {
                fmt.Println("db is connected")
        }
        //defer db.Close()
        // make sure connection is available
        err = db.Ping()
        fmt.Println(err)
        if err != nil {
                fmt.Println("db is not connected")
                fmt.Println(err.Error())
        }
        return db
}

/*end mysql connection*/

You need to change the database hostname, user and pass as per your database server credentials.

Step 3: Created "employee.go()" file for handle router function.

package controllers

import (
        "echo_with_mysql_mvc/models"
        "net/http"
        "github.com/labstack/echo"
)

func GetEmployees(c echo.Context) error {
        result := models.GetEmployee()
        println("foo")
        return c.JSON(http.StatusOK,result)
}

I have to create GetEmployees() method into controller packages, we will use this method as a handler in server.go file. I have also used ‘GetEmployee()’ method, which is defined in the model package to get all employee records from the MySQL database.

Now I will create a model method.

Step 4: Created "employee.go()" file and added method to get all employee data from the database.

package models

import (
        _"database/sql"
        "echo_with_mysql_mvc/db"
        "fmt"
        "database/sql"
)

type Employee struct {
        Id     string `json:"id"`
        Name   string `json:"employee_name"`
        Salary string `json: "employee_salary"`
        Age    string `json : "employee_age"`
}
type Employees struct {
        Employees []Employee `json:"employee"`
}
var con *sql.DB

func GetEmployee() Employees {
        con := db.CreateCon()
        //db.CreateCon()
        sqlStatement := "SELECT id,employee_name, employee_age, employee_salary FROM employee order by id"

        rows, err := con.Query(sqlStatement)
        fmt.Println(rows)
        fmt.Println(err)
        if err != nil {
                fmt.Println(err)
                //return c.JSON(http.StatusCreated, u);
        }
        defer rows.Close()
        result := Employees{}

        for rows.Next() {
                employee := Employee{}

                err2 := rows.Scan(&employee.Id, &employee.Name, &employee.Salary, &employee.Age)
                // Exit if we get an error
                if err2 != nil {
                        fmt.Print(err2)
                }
                result.Employees = append(result.Employees, employee)
        }
        return result

}

Here, I have defined a struct to store employee information, Created 'GetEmployee()' method to fetch records from MySQL. I have included DB to get the connection object.

Now we have created the controller/handler method and use the model method to fetch data from database. I will use the handler method in server.go file, I will add the controller package into server.go file

"echo_with_mysql_mvc/controllers"

Now defined routes to get all employee data using echo instance.

e.GET("/employees", controllers.GetEmployees)

I have created a GET type HTTP request which will handle by the controller package GetEmployees() method.

Conclusion:

I have created a Go application in MVC architecture, You might change the package name from controllers to handle. I have created a separate file and added it as a package to get all data from the MySQL database.