Organizing routes into separate files is a common practice to reduce the clutter and complexity of a main router file. In Gin, this can be achieved by leveraging the Group method.
One approach is to store the router variable as a struct member or global variable, allowing individual files to add handlers to it. Here's an example:
<code class="go">package app import ( "github.com/gin-gonic/gin" ) type routes struct { router *gin.Engine } func NewRoutes() routes { r := routes{ router: gin.Default(), } v1 := r.router.Group("/v1") r.addPing(v1) r.addUsers(v1) return r } func (r routes) Run(addr ...string) error { return r.router.Run() }</code>
<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) } func pongFunction(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }</code>
<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) } func getUsersFunction(c *gin.Context) { c.JSON(200, gin.H{ "users": "...", }) }</code>
By utilizing this approach, each function file can define handlers within its specific group, keeping the main codebase organized and modular.
The above is the detailed content of How to Structure Your Gin Routes for Clean Code?. For more information, please follow other related articles on the PHP Chinese website!