Add a global middleware
If you add a middleware to the Gin top level router instance, The given middleware will be executed on every invocation of every route.
func RequestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("Request received!")
}
}
func main() {
// Create a Gin router instance
router := gin.Default()
// Now any router under this router will have the given middleware function executed.
router.Use(RequestLogger())
router.GET("/tasks", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"tasks": "Here are the tasks"})
})
router.Run(":8080")
}
Last updated on