Add a gin middleware to a route group

You can apply middlewares to a specific route groups

Create a route group with router.Group()

func CheckAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
        is_authorized := true

        // if not authorized deny access
        if !is_authorized {
            c.JSON(http.StatusUnauthorized, gin.H{"error": "Not Authorized"})
            c.Abort()
            return 
        }

        // if authorized, allow access
		c.Next()
    }
}

authorized := router.Group("/api/protected/")
// Add the Middleware
authorized.Use(CheckAuth())

// Route /api/protected/tasks
authorized.GET("/tasks", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"tasks": "Here are the tasks"})
})

// POST Route /api/protected/user
authorized.POST("/set-user", func(c *gin.Context) {
})

In this example if you visit any route under /api/protected/ the CheckAuth() middleware will be executed.

Last updated on