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.

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:

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:

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:

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:
