golang mux, routing wildcard & custom func match

themihai picture themihai · Feb 9, 2014 · Viewed 17.3k times · Source

I'm using the mux package which seems to work quite well except that it doesn't seem to support complex routes or at least I don't get it how it does. I have several routes as following:

router := mux.NewRouter()
router.HandleFunc("/{productid}/{code}", product)
router.HandleFunc("/{user}", userHome)
router.HandleFunc("/search/price", searchPage)

So I have two questions:

  • How can I define a wildcard route such /search/price/* so that a request such /search/price/29923/rage/200/color=red can match it ?

  • Is it possible to add custom conditions to an existing route ? e.g. if the route is /{productid}/{code} and function x returns true , use this handlerTrue, if it returns false use handlerFalse.

I've tried to add something like .MatcherFunc(myfunction(ip)bool) to the route but it complains that the router has no such method.

Currently I'm handling the 'custom' conditions inside the handler.

Answer

Toni Cárdenas picture Toni Cárdenas · Feb 11, 2014

You can use regexps. Something like

router.HandleFunc(`/search/price/{rest:[a-zA-Z0-9=\-\/]+}`, searchPage)

That way, rest will just capture everything, so in your example rest would be 29923/rage/200/color=red. You will need to parse that in your code.

You probably want some like optional arguments, though.

router.HandleFunc(`/search{price:(\/price\/[0-9]+)?}{rage:(\/rage\/[0-9]+)?}{color:(\/color=[a-z]+)?}`, searchPage)

After that, you get vars price = "/price/29923", rage = "/rage/200" and color = "/color=red", that you still need to parse, but its easier, and you get to control which parameters are valid. It works as expected if you skip some parameter, eg. /search/price/29923/color=red will just give an empty rage variable, but still match.

I don't quite get your second question.