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
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() }
ping.go
package app
import "github.com/gin-gonic/gin"
func (r routes) addPing(rg *gin.RouterGroup) {
ping := rg.Group("/ping")
ping.GET("/", pongFunction)
}
users.go
package app
import "github.com/gin-gonic/gin"
func (r routes) addUsers(rg *gin.RouterGroup) {
users := rg.Group("/users")
users.GET("/", getUsersFunction)
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3