Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Gin Middleware Examples 
2.1.
Example 2 
2.2.
Example 3 
3.
Frequently Asked Questions 
3.1.
Why do we use the gin framework?  
3.2.
What are the main challenges of building the web framework using Go? 
3.3.
What are some advantages of using the Go language? 
3.4.
What is the meaning of packages in the gin framework? 
3.5.
What is dynamic type declaration in go language?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Gin Middleware

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Middleware is software that applications use to communicate with each other. It helps provide the functionality to connect applications intelligently and efficiently to innovate faster. It acts as a bridge between diverse technologies, tools, and different databases so that you can integrate them seamlessly into a single system. The single system then provides a unified service to its users. 

Introduction image

For example, a Windows frontend application sends and receives data from a Linux backend server, but the application users are unaware of the difference. We will discuss gin middleware in this blog, so if you want to know more about gin middleware, keep reading this blog. 

Gin Middleware Examples 

Example 1

package main
import(
  "github.com/gin-gonic/gin"
)


func GetDummyEndpoint(c *gin.Context) {
  resp := map[string]string{"hello":"world"}
  c.JSON(200, resp)
}


func main() {
  api := gin.Default()
  api.GET("/dummy", GetDummyEndpoint)
  api.Run(":5000")
}


Output: 

output
After Adding The Middleware

func DummyGinMiddleware(c *gin.Context) {
  fmt.Println("Im a dummy!")


  // Pass on to the next-in-chain
  c.Next()
}


func main() {
  // Insert this middleware definition before any routes
  api.Use(DummyGinMiddleware)
  // ... more code
}


Output:

output

In the example above, there's a call, c.Next(). After our middleware is executed, we can pass on request handlers to the next func in the chain. As you can see, middleware functions are no different from regular endpoint functions as they only take one argument *gin.Context. 

Example 2 

This example will show how to create basic logging middleware in Gin in GoLang.

A middleware simply takes a gin.HandlerFunc, as one of its parameters, wraps it and returns a new gin.HandlerFunc for the server to call. 

Code 

package main
import (
"log"
"time"


"github.com/gin-gonic/gin"
)


func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()


// Set example variable
c.Set("example", "12345")


// before request


c.Next()


// after request
latency := time.Since(t)
log.Print(latency)


// access the status we are sending
status := c.Writer.Status()
log.Println(status)


}
}


func main() {
router := gin.New()
router.Use(Logger())


router.GET("/test", func(c *gin.Context) {
example := c.MustGet("example").(string)


// it would print: "12345"
log.Println(example)
})


// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}


Output:

output

Example 3 

Recovery middleware recovers from any panics and writes a 500 if there was one.
 

package main


 import (
  "log"
  "time"


  "github.com/gin-gonic/gin"
)



func main() {
  // Creates a router without any middleware by default
  router := gin.New()


  // Global middleware
  // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
  // By default gin.DefaultWriter = os.Stdout
  router.Use(gin.Logger())


  // Recovery middleware recovers from any panics and writes a 500 if there was one.
  router.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
    if err, ok := recovered.(string); ok {
      c.String(http.StatusInternalServerError, fmt.Sprintf("Error : %s", err))
    }
    c.AbortWithStatus(http.StatusInternalServerError)
  }))


  router.GET("/panic", func(c *gin.Context) {
    // panic with a string -- the custom middleware could save this to a database or report it to the user
    panic("500 Internal Server Error")
  })


  router.GET("/", func(c *gin.Context) {
    c.String(http.StatusOK, "200 OK")
  })


  // Listen and serve on 0.0.0.0:8080
  router.Run(":8080")
}


Output:
 

output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions 

Why do we use the gin framework?  

We use the gin framework because gin is fast, lightweight, easy to use, has a great community, and open source. 

What are the main challenges of building the web framework using Go? 

The main challenge of building web applications with Go is that the net/HTTP library requires plenty of outside work and boilerplate code to get functions working efficiently. Its lack of built-in web feature handling makes Go too inflexible to become the go-to language for web developers. Luckily, Go's many framework and language options solve these challenges in great ways.

What are some advantages of using the Go language? 

Go is an attempt to establish a fresh, concurrent, garbage-collected language with advantages like quick compilation and the ability to compile a large Go programme in a matter of seconds on a single machine. It offers a framework for building software that simplifies dependency analysis and does away with most of the C-style overhead, such as files and libraries. Go offers essential support for concurrent execution and communication and is fully garbage-collected.

What is the meaning of packages in the gin framework? 

Gin programs are made up of packages. The program starts running in the main box. This program uses the packages with import paths "fmt" and "math/rand."

What is dynamic type declaration in go language?

A dynamic type variable declaration requires the compiler to interpret the type of variable based on the value passed to it. Compilers don't need a variable to have type statically as a necessary requirement.

Conclusion

In this blog, we discussed the introduction of middleware, looked at the custom gin middleware, and then discussed the different gin middleware.  

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations. Read our blogs on aptitudecompetitive programminginterview questionsIT certifications, and data structures and algorithms for the best practices

Live masterclass