在一个项目中,我们会有很多路由,那么我们该如何更好的管理自己的路由,在多人协同的情况下可以更好的规范路由呢,我来说一下自己的做法
1.承接gin框架初识(先跑一个简单demo) ①,先创建一个controller文件夹,再创建子文件夹及go文件,如下:
2.每个go文件的代码如下:
project->index.go:
package main import ( c "project/controller" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() rr := c.GinRouter(r) // 监听并在 0.0.0.0:8080 上启动服务 rr.Run(":8080") }
project->controller->index.go:
package controller import ( "fmt" "project/controller/forth" "project/controller/second" "project/controller/third" "github.com/gin-gonic/gin" ) func GinRouter(r *gin.Engine) *gin.Engine { rr := r.Group("/") rr.GET("/first", func(c *gin.Context) { fmt.Println("first .........") }) rr = r.Group("/a") second.Routers(rr) third.Routers(rr) forth.Routers(rr) return r }
project->controller->second->index.go:
package second import ( "fmt" "github.com/gin-gonic/gin" ) func Routers(r *gin.RouterGroup) { rr := r.Group("") rr.POST("/second", Function) return } func Function(c *gin.Context) { fmt.Println("second .........") return }
project->controller->third->index.go:
package third import ( "fmt" "github.com/gin-gonic/gin" ) func Routers(r *gin.RouterGroup) { rr := r.Group("") rr.POST("/third", Function) return } func Function(c *gin.Context) { fmt.Println("third .........") return }
project->controller->forth->index.go:
package forth import ( "fmt" "github.com/gin-gonic/gin" ) func Routers(r *gin.RouterGroup) { rr := r.Group("") rr.POST("/forth", Function1) rr.POST("/five", Function2) return } func Function1(c *gin.Context) { fmt.Println("forth .........") return } func Function2(c *gin.Context) { fmt.Println("five .........") return }
3.执行一下代码:
这样的写法能够保证,在多人协作的情况下,代码的合并不会出现很大的问题,而且路由管理也相方便。