Welcome to another Golang tutorial designed for beginners. In this tutorial, we’ll be building a straightforward MVC (Model-View-Controller) application using the Echo framework and a MySQL database. The MVC pattern, standing for Model, View, and Controller, aids in organizing code and facilitating swift development for large projects.
What’s Inside
Understanding MVC:
In MVC, the Model manages database interactions, the View displays information through the Controller, and the Controller serves as the intermediary between the View and the Model.
Key Components in This Example:
Here are the essential files participating in this example:
- server.go: The main entry file for the Golang application.
- controllers/employee.go: Contains all handler methods.
- db/db_connection.go: Includes the method for establishing a database connection and returning the MySQL connection object.
- models/employee.go: Encompasses all methods related to database interactions.
Setting Up the Project Structure:
server.go:
package main import ( "github.com/labstack/echo" "github.com/labstack/echo/middleware" "net/http" ) func main() { e := echo.New() // Middleware setup 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}, })) // Welcome message route e.GET("/", func(c echo.Context) error { return c.JSON(http.StatusCreated, "Welcome to the MVC Echo with MySQL app using Golang") }) // Start server e.Logger.Fatal(e.Start(":8081")) }
In this section, we initialize the Echo framework instance, set up middleware for logging, recovery, and cross-origin resource sharing (CORS). Additionally, we create a simple route to display a welcome message.
db/db_connection.go:
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("Database connected successfully") } // Check connection availability err = db.Ping() fmt.Println(err) if err != nil { fmt.Println("Database not connected") fmt.Println(err.Error()) } return db }
Here, we establish a MySQL connection with the specified credentials.
controllers/employee.go:
package controllers import ( "echo_with_mysql_mvc/models" "net/http" "github.com/labstack/echo" ) // Handler to get employees func GetEmployees(c echo.Context) error { result := models.GetEmployee() return c.JSON(http.StatusOK, result) }
This file contains the handler method to retrieve employee data using the model method.
models/employee.go:
package models import ( "database/sql" _ "database/sql" "echo_with_mysql_mvc/db" "fmt" ) // Employee struct to store information type Employee struct { Id string `json:"id"` Name string `json:"employee_name"` Salary string `json:"employee_salary"` Age string `json:"employee_age"` } // Employees struct to store a collection of employees type Employees struct { Employees []Employee `json:"employee"` } var con *sql.DB // GetEmployee method to fetch records from MySQL func GetEmployee() Employees { con := 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) } defer rows.Close() result := Employees{} for rows.Next() { employee := Employee{} err2 := rows.Scan(&employee.Id, &employee.Name, &employee.Salary, &employee.Age) if err2 != nil { fmt.Print(err2) } result.Employees = append(result.Employees, employee) } return result }
In this section, we define the struct to store employee information and create the GetEmployee
method to fetch records from MySQL using the database connection.
Running the Application:
- Run the Golang application on port 8081:
$ go run server.go
2. Install external packages:
$ go get
Final Thought
In this tutorial, we’ve successfully created a Golang application following the MVC architecture. Feel free to customize the package names or adapt the code to your specific requirements. The separation of files into packages facilitates the retrieval of data from a MySQL database.
You May Also Like: