-
Notifications
You must be signed in to change notification settings - Fork 8.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Does Gin support regexp in route? #229
Comments
No it does not. httprouter is using a tree structure to power its routing. You can read about it here: |
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")
|
@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: |
router.GET("/year/(?P<year>[0-9]*)", handler)
or evenrouter.GET("/year/\\d{0,4}", handler)
does not work. Thanks!
The text was updated successfully, but these errors were encountered: