jlonganecker
jlonganecker

Reputation: 1198

How to use Gorilla Mux to match entire path with regex

I would like to be able to use regex to match the entire path not just a portion of it.

For Example:

/users.*

would match

/users
/users/bob
/users/bob/repos

Currently with Mux's HandleFunc you would have to match multiple paths

/users
/users/{.*}
/users/{.*}/{.*}
...

Upvotes: 3

Views: 2891

Answers (1)

jlonganecker
jlonganecker

Reputation: 1198

I ended up writing my own custom matcher function and used go's regex package. It was very easy to do and here is an example:

import (
  ...
    "net/http"
    "net/url"
    "regexp"
    "github.com/gorilla/mux"
  ...
)

...

muxRouter := mux.NewRouter()

muxRouter.
  Methods("GET", "POST").
  Schemes("https").
  MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
    match, _ := regexp.MatchString("/users.*", r.URL.Path)
    // TODO handle error from regex
    return match
  }).
  HandlerFunc(m.ServeHTTP)

The key is to use:
HandlerFunc(f func(http.ResponseWriter, *http.Request))

and not:
HandleFunc(path string, f func(http.ResponseWriter, *http.Request)).

HandlerFunc must come after your matchers. This will allow you to write your own custom matcher function.

Performance
For my use case this performs well, but if you want better performance you could try using a precompiled r, _ := regexp.Compile("p([a-z]+)ch").

You would probably need to use a struct with a f func(http.ResponseWriter, *http.Request) that already has a precompile regex pattern stored in the struct.

Go Regex Examples:
https://gobyexample.com/regular-expressions

Go to Town! Hope you guys find this helpful.

Upvotes: 2

Related Questions