r.GET("/v1.0/:pageId/page", (&page.API{}).Get)
r.POST("/v1.0/:labelId/label", (&label.API{}).Post)
It is a famous problem of gin that this would result in wildcard route id conflicts with existing children in path
. However, I am writing this script for returning mock result for testing, so there is absolute need to keep this URL structure. Most solution out there just use 2 wildcard instead and handle the different part in the function it is pointing to. However, as this is using different HTTP method (GET and POST), so it is impossible to use that way to solve the problem. Is there other way to keep this URL structure?
Not sure whether it is the best way.This could work normally:
Use a Group:
v10Group := r.Group("/v1.0/:id", checkTheId)
{
v10Group.GET("/page", func(c *gin.Context) {
c.JSON(200, gin.H{
"msg":"Now you are trying to visit a page",
"id_page": c.Param("id"),
})
})
v10Group.GET("/label", func(c *gin.Context) {
c.JSON(200, gin.H{
"msg":"Now you are trying to visit a label",
"id_label": c.Param("id"),
})
})
}
And a middleware to check the id,Save it in the gin.Context
.
func checkTheId(c *gin.Context) {
id := c.Param("id")
b, err := strconv.Atoi(id) // judge whether it is a number
if err != nil{
c.JSON(400,gin.H{
"msg":"Parameter invalid, Please input a number",
})
c.Abort()
return
}
c.Set("id", b)
}
Result: