gin
gin copied to clipboard
A routing bug?
Description
code:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/read_:id.htm", func(c *gin.Context) {
id := c.Param("id")
c.JSON(http.StatusOK, gin.H{
"message": "pong",
"id": id,
})
})
r.Run()
}
can match the following requests:
- /read_1
- /read_1.htm
- /read_1.html
- /read_1.aaaaaaaa
- ......
How to do a unique match?
Environment
- go version: go1.18.10
- gin version (or commit ref): v1.8.2
- operating system:
Strange usage, maybe you can write id := c.Param("id.htm")
Or you can control your route in middleware or function.
Routes should have unique properties
The router's properties are pretty unique. It just is not the properties we expect here 🙈
According to Gin's radix-tree router, a wild card starts with :
and ends at the next /
or at the end of the given string. In your example, the wild card is id.htm
and not id
.
I guess you expected the router to pars something like this:
- prefix:
/read_
- wildcard:
:id
- postfix:
.htm
But as the wildcard ends with the next /
or end of the string. So it actually is:
- prefix:
/read_
- wildcard:
:id.htm