![]() |
VOOZH | about |
In this article, we’ll set up GORM, an ORM library, with MySQL using the Gin web framework in Go. GORM provides features that make database interactions easier by allowing the use of Go structs instead of raw SQL queries, which helps reduce boilerplate code and keeps the codebase cleaner.
We’ll take a step-by-step approach to establishing a database connection, implementing basic CRUD operations, and managing database migrations. Additionally, we’ll perform a simple query using the Gin API and GORM while maintaining a clear and simple folder structure for easier understanding.
Go is a simple and efficient programming language designed for fast performance and concurrency, making it ideal for robust applications. Developed by Google, it emphasizes clean syntax and ease of use, which speeds up development and improves maintainability.
Gin is a web framework built on Go's net/http package, offering high speed. Combined with Go's concurrency, it is widely used in efficient cloud-based applications. Understanding Gin's interaction with databases like MySQL is crucial for building web applications efficiently.
Initialize Gin using the following command:
go mod init MODULE_NAME
go get -u github.com/gin-gonic/gin
Install GORM and MySQL driver package using the following command:
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
mainDirectory
│ go.mod
│ go.sum
│ main.go
│
└───database
│ dbConfig.go
│
└───models
countries.go
main.go:package main
import (
"net/http"
"github.com/gin-gonic/gin"
"MODULE_NAME/database"
"MODULE_NAME/database/models"
)
func main(){
databaseInstance:= database.InIt()
router:=gin.Default()
router.POST("/add-country", func(c *gin.Context){ // Payload: {"Country":"India", "CountryCode":"+91"}
var newCountry models.Countries
if err := c.BindJSON(&newCountry); err != nil{
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err:= databaseInstance.Create(&newCountry).Error; err!=nil{
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{
"success": true,
"message":"Country Added Successfully",
"newCountry":newCountry,
})
})
router.GET("/get-all-countries", func(c *gin.Context){
allCountries:= [] models.Countries{};
if err:= databaseInstance.Find(&allCountries).Error; err!=nil{
c.JSON(http.StatusInternalServerError, gin.H{"success":false, "error":err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success":true, "allCountries": allCountries})
})
router.Run(":8080")
dbConfig.go:package database
import (
"fmt"
"os"
"log"
"time"
"strconv"
"gorm.io/gorm"
"gorm.io/driver/mysql"
"gorm.io/gorm/logger"
"MODULE_NAME/database/models"
)
var databaseInstance *gorm.DB
func InIt() *gorm.DB{
var err error
databaseInstance, err = connectionDatabase()
if err!=nil{
log.Fatalf("Could not connect to the database: %v", err)
}
err = performMigration()
if err!=nil{
log.Fatalf("Could not auto migrate: %v", err)
}
return databaseInstance
}
func connectionDatabase() (*gorm.DB, error){
dbUsername := getEnv("DB_USERNAME", "root")
dbPassword := getEnv("DB_PASSWORD", "")
dbName := getEnv("DB_NAME", "gorm")
dbHost := getEnv("DB_HOST", "localhost")
dbPort := getEnv("DB_PORT", "3306")
connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&loc=Local", dbUsername, dbPassword, dbHost, dbPort, dbName)
databaseConnection, err := gorm.Open(mysql.Open(connectionString), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info), // Enable logging for debugging
})
if err!=nil{
return nil, err
}
sqlDatabase, err :=databaseConnection.DB()
if err!=nil{
return nil,err
}
// Connection pool settings from environment variables
maxIdleConns, _ := strconv.Atoi(getEnv("DB_MAX_IDLE_CONNS", "10"))
maxOpenConns, _ := strconv.Atoi(getEnv("DB_MAX_OPEN_CONNS", "25"))
connMaxLifetime, _ := strconv.Atoi(getEnv("DB_CONN_MAX_LIFETIME", "3600")) // in seconds
sqlDatabase.SetMaxIdleConns(maxIdleConns)
sqlDatabase.SetMaxOpenConns(maxOpenConns)
sqlDatabase.SetConnMaxLifetime(time.Duration(connMaxLifetime) * time.Second)
return databaseConnection, nil
}
func performMigration() error{
err:= databaseInstance.AutoMigrate(&models.Countries{})
if err!=nil{
return err
}
return nil
}
func getEnv(key string, defaultVaule string) string {
value:= os.Getenv(key)
if value==""{
return defaultVaule
}
return value
}
countries.go:package models
type Countries struct {
Id uint `json:"id" gorm:"primarykey;autoIncrement"`
Country *string `json:"country" gorm:"not null"`
CountryCode *string `json:"countryCode" gorm:"not null"`
}
Start the application using the following command
go run main.go
In conclusion, while GORM may not achieve the raw speed of direct SQL queries due to the inherent overhead of its abstraction layer, it offers substantial advantages in terms of code readability and maintainability. By utilizing Go structs instead of raw SQL statements, GORM streamlines the coding process and makes it more intuitive.
This framework simplifies complex operations such as handling associations and transactions while significantly reducing boilerplate code, allowing for a greater focus on implementing business logic rather than managing repetitive database tasks.