路由
[[toc]]
介绍
Goravel 路由模块可以使用 facades.Route 进行操作,facades.Route 是知名 HTTP 框架 gin-gonic/gin 的一个实例,使用方法与 gin-gonic/gin 完全一致。
默认路由文件
所有路由文件都在 /routes 目录中进行定义。框架默认有一个示例路由 /routes/web.go,其中 func Web 方法被注册到 app/providers/route_service_provider.go 文件中,以实现路由的绑定。
你也可以根据这种方法进行更细颗粒的管理,可以在 routes 目录下新增路由文件,然后在 app/providers/route_service_provider.go 文件中进行注册。
启动 HTTP 服务器
在根目录下 main.go 中启动 HTTP 服务器
package mainimport ("github.com/goravel/framework/support/facades""goravel/bootstrap")func main() {//This bootstraps the framework and gets it ready for use.bootstrap.Boot()//Start http server by facades.Route.go func() {if err := facades.Route.Run(facades.Config.GetString("app.host")); err != nil {facades.Log.Errorf("Route run error: %v", err)}}()select {}}
基本路由
可以使用闭包的形式,定义一个很简单的路由:
facades.Route.GET("/", func(c *gin.Context) {c.JSON(200, gin.H{"message": "pong",})})
可用的路由方法
facades.Route.GET("/someGet", getting)facades.Route.POST("/somePost", posting)facades.Route.PUT("/somePut", putting)facades.Route.DELETE("/someDelete", deleting)facades.Route.PATCH("/somePatch", patching)facades.Route.HEAD("/someHead", head)facades.Route.OPTIONS("/someOptions", options)
路由参数
facades.Route.GET("/user/:name", func(c *gin.Context) {name := c.Param("name")c.String(http.StatusOK, "Hello %s", name)})
路由传参
router.GET("/welcome", func(c *gin.Context) {firstname := c.DefaultQuery("firstname", "Guest")lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")c.String(http.StatusOK, "Hello %s %s", firstname, lastname)})
