Gin & GORM in Golang

Golang is an open-source, procedural and statically typed programming language designed by Google. Go is popular because of its simplicity, readability, efficiency, and concurrent nature. Go is used for backend programming, also popular for making command-line tools.

Refer to the docs for installing Go in your system. In this blog, we will discuss about Gin framework and Gorm library in Go. This is a good place to start if you are interested in learning different concepts in Go or developing a RestAPI.

Now let us explore about Gin and Gorm library in Go.

Gin Framework

Gin is a Go web framework designed to be easy to use and fast. Gin is used to write web applications without much boilerplate code. This means that your code will be concise and easy to read.

The few features of GIN are:

  • Fast & Lightweight

  • Middleware support

  • Crash-free

  • Routes grouping

Installation

To install GIN, run: go get -u github.com/gin-gonic/gin

Example

This is a basic example of an API endpoint using gin.

package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()                          #1
    r.GET("/example", func(c *gin.Context) {    #2
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello World!",
        })  
    })
    r.Run(":8080")                                #3
}

To run the application, execute the following command: go run main.go You should now be able to access the server at http://localhost:8080/example.

  • Creates a gin router with default middleware. In gin, a router matches incoming requests to the appropriate handler. If a match is found, the corresponding handler is invoked. If no match is found, a 404 Not Found status is returned.

  • A handler for GET request on the “/example” endpoint. The handler is a function that is invoked when a match is found.

    1. we make a handler using the router.GET(path, handler), where the path is the relative path,​ and handler is the handler function that takes *gin.Context as an argument. The handler function serves a JSON response with a status of 200.

    2. similarly, we have

      • router.POST("/example", handler)

      • router.PUT("/example/:id", handler)

      • router.DELETE("/example/:id", handler)

  • Starts the router which serves on port 8080

GORM

The GORM(Go-ORM) is a fantastic ORM(Object-relational mappers) library for Golang. It is an ORM library for dealing with relational databases which act almost as brokers between developers and underlying databases. It reduces the complexity and provides ease to operate on databases without the hassle of writing pure SQL. This gorm library is developed on the top of the database/SQL package.

The few features of ORM are:

  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism)

  • Callbacks (Before/After Create/Save/Update/Delete/Find)

  • SQL Builder

  • Logger

  • Developer Friendly

Installation

To install the GORM package, run: go get gorm.io/gorm

Example

After installation of the Gorm package, you need to install the database driver for MySQL by running go get gorm.io/driver/mysql

doing this will allow the GORM library to communicate with the MySQL database and perform database operations.

Next, you need to import this package into your project along with the database drivers and connect to the database.

Connecting to database:

db, err := gorm.Open(“mysql”, “user:password@/dbname?charset=utf8&parseTime=True&loc=Local”)

To connect to the database, just use the above syntax.

Declaring models:

Models are normal structs with basic Go types

type User struct {
  gorm.Model
  Name string `json:"name"`
  Age int `json:"age"`
}

GORM defined a gorm.Model struct, which includes fields ID, CreatedAt, UpdatedAt, DeletedAt

// gorm.Model definition
type Model struct {
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}

You can embed it into your struct to include those fields, refer to Embedded Struct

Auto-migration:

This feature will automatically migrate your schema. db.AutoMigrate(&User{})

It will automatically create the table based on your model. We don’t need to create the table manually.

Now use the gorm to perform crud operations on the database

Perform CRUD operations:

Create :

user := User{Name: "John", Age: 18}
result := db.Create(&user)

Find :

result := db.Where("name = ?", "John").First(&user)

Update :

// User's ID is `111`:
result := db.Model(&user).Update("Name", "Hello")

Delete :

result := db.Where("name = ?", "John").Delete(&user)

To learn more in detail you can refer to the below docs: Gin, Gorm, REST API

Please leave your feedback if you have any.

Thank you for reading!!