How to Use Middleware in Gin

Web
Register middleware in Gin using the Use method on your router or pass it directly to specific route handlers to execute logic before and after request processing.

Use middleware in Gin by defining a function that accepts *gin.Context and calling Use() on your router instance to register it globally or on specific routes.

package main

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

func main() {
	r := gin.Default()

	// Define middleware
	r.Use(func(c *gin.Context) {
		// Logic before handler
		c.Next()
		// Logic after handler
	})

	// Define route
	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "Hello World"})
	})

	r.Run(":8080")
}

For route-specific middleware, pass the function to the route handler instead of Use():

r.GET("/admin", myMiddleware, func(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "Admin"})
})