The RouterGroup in gin-gonic/gin is used to group routes to apply middleware and/or routing rules to a specific set of routes. It allows for the creation of sub-routes with a common prefix.
Code Example 1: Creating a basic RouterGroup
router := gin.Default()
v1 := router.Group("/api/v1") { v1.GET("/users", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "This is the /users endpoint on v1", }) }) }
In this example, we create a RouterGroup for version 1 of our API ("/api/v1") using the Group method from gin's router. We then define a GET route for /users inside the RouterGroup and respond with a JSON message.
Code Example 2: Applying middleware to a RouterGroup
To apply middleware to a RouterGroup, we can use the Use method from gin's router. Middleware functions will be applied to all routes within that RouterGroup.
router := gin.Default()
// Global middleware router.Use(globalMiddleware())
v1 := router.Group("/api/v1") v1.Use(version1Middleware()) { v1.GET("/users", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "This is the /users endpoint on v1", }) }) }
In this example, we define two middleware functions: globalMiddleware and version1Middleware. We then apply the global middleware function using the Use method on our main router instance. Finally, we create a new RouterGroup for version 1 of our API ("/api/v1") and apply the version1Middleware function to it using the Use method. This middleware will only apply to routes within the v1 RouterGroup.
Overall, the gin-gonic/gin package is a versatile and powerful framework for building REST APIs and web applications in Go. The RouterGroup feature allows for greater flexibility in structuring routes and applying middleware.
Golang RouterGroup - 30 examples found. These are the top rated real world Golang examples of github.com/gin-gonic/gin.RouterGroup extracted from open source projects. You can rate examples to help us improve the quality of examples.