In order to avoid cluttering the main file with route definitions, you can group routes into separate files. This approach allows for better code organization and maintainability.
To create a nested route grouping, you can store the router variable in a struct or global variable. Individual files can then add handlers to this shared router instance.
routes.go
<code class="go">package app import ( "github.com/gin-gonic/gin" ) type routes struct { router *gin.Engine } func NewRoutes() routes { return routes{ router: gin.Default(), } } func (r routes) addPing(rg *gin.RouterGroup) { } func (r routes) addUsers(rg *gin.RouterGroup) { } func (r routes) Run(addr ...string) error { return r.router.Run() }</code>
ping.go
<code class="go">package app import "github.com/gin-gonic/gin" func (r routes) addPing(rg *gin.RouterGroup) { ping := rg.Group("/ping") ping.GET("/", pongFunction) }</code>
users.go
<code class="go">package app import "github.com/gin-gonic/gin" func (r routes) addUsers(rg *gin.RouterGroup) { users := rg.Group("/users") users.GET("/", getUsersFunction) }</code>
The above is the detailed content of How to Organize Routes in Gin: A Guide to Grouped Route Definition?. For more information, please follow other related articles on the PHP Chinese website!