router.GET("/year/(?P<year>[0-9]*)", handler) or even
router.GET("/year/\\d{0,4}", handler)
does not work. Thanks!
No it does not. httprouter is using a tree structure to power its routing.
You can read about it here:
https://github.com/julienschmidt/httprouter#how-does-it-work
I Get It. Thanks for the answer!
So how do I use regexp in router? Anyone can give me a suggestion?
Create a custom noRoute (404) handler and parse the url with your custom regexp code there :)
I would make a parameter or catch all parameter then parse it inside the router with the regexp package:
In your routing:
router.GET("/myroute/:regex",regexMyrouteHandler)
Then in the handler:
RegString := c.Param("regex")
// Parse and pass to another handler based on match
On Aug 22, 2015, at 7:59 AM, Damon Zhao [email protected] wrote:
So how do I use regexp in router? Anyone can give me a suggestion?
—
Reply to this email directly or view it on GitHub.
@nazwa @TheRealKira both big thx~
@se77en here's a better example I was responding from my phone before.
//Route
r.GET("/users/:regex",UserHandler)
...
//Import regexp wherever your UserHandler function is
import "regexp"
...
func UserHandler(c *gin.Context) {
//Compile valid regular expression
r, err := regexp.Compile(`[a-zA-Z0-9]`)
if err != nil {
panic(err)
return
}
username := c.Param("regex")
if r.MatchString(username) == true {
//Param matches your regex
c.JSON(200,gin.H{"match":"true"})
} else {
//Write error header and body no match
c.JSON(400,gin.H{"match":"false"})
}
}
@TheRealKira Thank you very very much!
@TheRealKira the trouble is we can't use it in root router like this:
r.GET("/:any", Handler)
Most helpful comment
@se77en here's a better example I was responding from my phone before.