在 上一篇 Golang Gin 实战(二)| 简便的Restful API 实现 文章中,我们留了一个疑问,假如我们有很多用户,我们要为他们一个个注册路由(路径)吗?

路由路径

如下URL:

/users/123
/users/456
/users/23456

以上等等,我们有很多用户,如果我们都一个个为这些用户注册这些路由(URL),那么我们是很难注册完的,而且我们还会有新注册的用户,可见这种办法不行。

usersusersid
/users/id
idusersidid

路由参数

Gin
func main() {
    r := gin.Default()

    r.GET("/users/:id", func(c *gin.Context) {
        id := c.Param("id")
        c.String(200, "The user id is  %s", id)
    })
    r.Run(":8080")
}
http://localhost:8080/users/123
The user id is  123
http://localhost:8080/users/123123
Ginhttprouterhttprouter
/users/:id:idc.Param("id")
/users/:id
Pattern: /users/:id

/users/123          匹配
/users/哈哈        匹配
/users/123/go      不匹配
/users/             不匹配
/users/哈哈Gin
Gin/users/:id/users/:id
r.GET("/users/list", func(c *gin.Context) {
    //省略无关代码
})

这时候我们运行程序的话,会出现如下提示:

panic: 'list' in new path '/users/list' conflicts with existing wildcard ':id' in existing prefix '/users/:id'
Ginhttprouterhttprouter

星号路由参数

:*
/users/*id
Pattern: /users/*id

/users/123         匹配
/users/哈哈        匹配
/users/123/go      匹配
/users/            匹配

我们把上面的例子改下:

func main() {
    r := gin.Default()

    r.GET("/users/*id", func(c *gin.Context) {
        id := c.Param("id")
        c.String(200, "The user id is  %s", id)
    })
    r.Run(":8080")
}
http://localhost:8080/users/123
The user id is  /123
id123/123/
http://localhost:8080/users/123/go
The user id is  /123/go
/
http://localhost:8080/usershttp://localhost:8080/users/
The user id is  /
/users/users//users//users
r.GET("/users", func(c *gin.Context) {
    c.String(200, "这是真正的/users")
})
http://localhost:8080/users
这是真正的/users
/users/*id/usersGin
gin.RedirectTrailingSlashtruefalse
func main() {
    r := gin.Default()

    r.RedirectTrailingSlash = false
    r.GET("/users/*id", func(c *gin.Context) {
        id := c.Param("id")
        c.String(200, "The user id is  %s", id)
    })

    r.Run(":8080")
}
http://localhost:8080/users404 page not found

小结

*
?a=b&c=d

精彩文章推荐

为了答谢新老朋友的转发、阅读和点赞支持,我给大家包了个现金红包,关注我的公众号,即可参与抽奖。在看到50,下次抽奖增加金额!

flysnow_org