创建 Gin 分组路由的步骤如下:
- 创建 gin.Engine 实例
r := gin.Default()
- 创建分组路由实例
api := r.Group("/api")
- 在分组路由 api 中添加具体路由和处理函数
api.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Welcome to API")
})
api.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.String(http.StatusOK, fmt.Sprintf("User ID is %s", id))
})
这里注意,在分组路由 api 中添加的路由的路径都是相对于 "/api" 的。例如,第二个路由的完整路径为 "/api/users/:id"。
完整示例代码如下:
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
api := r.Group("/api")
api.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Welcome to API")
})
api.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.String(http.StatusOK, fmt.Sprintf("User ID is %s", id))
})
r.Run(":8080")
}