Add a middleware to a specific Route

The function RequestLogger() will be be called before the request is processed and c.Next() processes the request. Any code afterwards is used to perform things after the request.

// RequestLogger is a middleware function that logs 
// the time taken to process a request
func RequestLogger() gin.HandlerFunc {
    return func(c *gin.Context) {
        // Before Request
        startTime := time.Now()
        fmt.Printf("Request Started %v\n", c.Request.URL.Path, duration)

        // Process request
        c.Next()

        // After request,
        // Calculate the duration
        duration := time.Since(startTime)
        fmt.Printf("Request to %s took %v\n", c.Request.URL.Path, duration)
    }
}

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

    // Define a route with the RequestLogger middleware
    router.GET("/timed", RequestLogger(), func(c *gin.Context) {
        time.Sleep(2 * time.Second) // Simulate a delay
        c.JSON(200, gin.H{
            "message": "This is a timed route!",
        })
    })

    router.Run(":8080")
}
Last updated on