Grouping routes
Route groups let you organize related routes under a shared URL prefix. This is useful for:
- API versioning — group all v1 endpoints under
/v1and v2 endpoints under/v2. - Shared middleware — apply authentication, logging, or rate-limiting to an entire set of routes at once instead of attaching middleware to every route individually.
- Code organization — keep related handlers visually grouped in your source code.
Basic grouping
package main
import ( "net/http"
"github.com/gin-gonic/gin")
func loginEndpoint(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"action": "login"})}
func submitEndpoint(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"action": "submit"})}
func readEndpoint(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"action": "read"})}
func main() { router := gin.Default()
// Simple group: v1 { v1 := router.Group("/v1") v1.POST("/login", loginEndpoint) v1.POST("/submit", submitEndpoint) v1.POST("/read", readEndpoint) }
// Simple group: v2 { v2 := router.Group("/v2") v2.POST("/login", loginEndpoint) v2.POST("/submit", submitEndpoint) v2.POST("/read", readEndpoint) }
router.Run(":8080")}Applying middleware to a group
You can pass middleware to router.Group() or call Use() on a group. Every route in that group will run the middleware before its handler.
// AuthRequired is a placeholder for your auth middleware.func AuthRequired() gin.HandlerFunc { return func(c *gin.Context) { // ... check token, session, etc. c.Next() }}
func main() { router := gin.Default()
// Public routes -- no auth required public := router.Group("/api") { public.GET("/health", healthCheck) }
// Private routes -- auth middleware applied to the whole group private := router.Group("/api") private.Use(AuthRequired()) { private.GET("/profile", getProfile) private.POST("/settings", updateSettings) }
router.Run(":8080")}Nested groups
Groups can be nested to build deeper URL hierarchies while keeping middleware scoped appropriately.
func main() { router := gin.Default()
api := router.Group("/api") { // /api/v1 v1 := api.Group("/v1") { // /api/v1/users users := v1.Group("/users") users.GET("/", listUsers) users.GET("/:id", getUser)
// /api/v1/posts posts := v1.Group("/posts") posts.GET("/", listPosts) posts.GET("/:id", getPost) } }
router.Run(":8080")}Each level inherits the prefix of its parent, so the final routes become /api/v1/users/, /api/v1/users/:id, and so on.