Gin: Does Gin support regexp in route?

Created on 2 Mar 2015  Â·  9Comments  Â·  Source: gin-gonic/gin

router.GET("/year/(?P<year>[0-9]*)", handler) or even
router.GET("/year/\\d{0,4}", handler)
does not work. Thanks!

question

Most helpful comment

@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"})
    }
}

All 9 comments

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)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sofish picture sofish  Â·  3Comments

oryband picture oryband  Â·  3Comments

olegsobchuk picture olegsobchuk  Â·  3Comments

xpbliss picture xpbliss  Â·  3Comments

iiinsomnia picture iiinsomnia  Â·  3Comments