gorilla / mux

Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
20.93k stars 1.85k forks source link

Question about regular expressions in paths #687

Closed patrickjane closed 2 years ago

patrickjane commented 2 years ago

I am building a request handler like this:

router := mux.NewRouter()
route := router.PathPrefix(routeCfg.Match.Path)
...
route.HandlerFunc(...)

Right now I am writing automated tests for my webserver, and I am at the point where I want to test path matching using regular expressions. This means in the above, routeCfg.Match.Path will contain a regular expression.

Question 1: It is not 100% clear to me from the docs how to use regular expressions. According to the documentation on the front page: "Paths can have variables. They are defined using the format {name} or {name:pattern}. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:"

This means to me, that using curly braces is used to extract variables from the request URL in the first place. Yet, it seems like I am only able to use regular expressions in the path matcher when used inside curly braces. Is this correct usage?

Question 2: According to the documentation, if I want to use patterns inside the {} I must give the variable a dedicated name. In other words, I need to write something like: /service/v{foo:[0-9]*}/. This is pretty cumbersome, for something that I don't even want to use.

Is there another way to use regular expressions for path matching, or is this only available through the variables-syntax?

amustaque97 commented 2 years ago

Hi Patrik 👋🏻

Answer1: Yes, you're right. Here is the function if you want to learn more about it how the variables extract happens. https://github.com/gorilla/mux/blob/c889844abd3601217c96aabc4b2dd89f6d904c01/regexp.go#L41

Answer2:

Is there another way to use regular expressions for path matching, or is this only available through the variables-syntax?

Mux only supports variable-syntax

I hope I answer your questions. If you're satisfied then please close the issue or we can keep the discussion going. 😄