How do I add middleware with Gin in Go?

In Go, the Gin framework allows you to easily add middleware to your application. Middleware functions are executed before the main handler and can be used for tasks such as logging, authentication, and modifying requests/responses. This guide provides a simple example of how to implement and use middleware in a Gin application.

To create a middleware in Gin, you define a function that takes a gin.HandlerFunc as a parameter and returns a gin.HandlerFunc. Inside this function, you can perform pre-processing and post-processing of requests.

package main

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

func Logger() gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        // Process request
        c.Next()
        // Calculate duration
        duration := time.Since(start)
        // Log the request
        println("Request processed in", duration)
    }
}

func main() {
    r := gin.Default()
    
    // Use the Logger middleware
    r.Use(Logger())

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

    r.Run(":8080")
}

In this example, we define a Logger middleware that logs the duration of each request. We then register this middleware with our Gin router using the Use method, which allows us to apply it globally. When a request hits the /ping endpoint, the middleware logs the time taken to process that request.


Gin Go middleware Gin framework Go web development middleware example