Skip to content
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

Closed
sshikaree opened this issue Mar 2, 2015 · 9 comments
Closed

Does Gin support regexp in route? #229

sshikaree opened this issue Mar 2, 2015 · 9 comments
Labels

Comments

@sshikaree
Copy link

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

@jbub
Copy link

jbub commented Mar 2, 2015

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

@sshikaree
Copy link
Author

I Get It. Thanks for the answer!

@se77en
Copy link
Contributor

se77en commented Aug 22, 2015

So how do I use regexp in router? Anyone can give me a suggestion?

@nazwa
Copy link

nazwa commented Aug 22, 2015

Create a custom noRoute (404) handler and parse the url with your custom regexp code there :)

@TheRealKira
Copy link

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 notifications@github.com 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.

@se77en
Copy link
Contributor

se77en commented Aug 23, 2015

@nazwa @TheRealKira both big thx~

@TheRealKira
Copy link

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

@se77en
Copy link
Contributor

se77en commented Aug 27, 2015

@TheRealKira Thank you very very much!

@dzpt
Copy link

dzpt commented Jun 21, 2018

@TheRealKira the trouble is we can't use it in root router like this:
r.GET("/:any", Handler)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

7 participants