2

I have a validator function to check if a given path matches a path in array of paths.

Current Logic:

var allowed := String{"/users", "/teams"}
func Validator(path String) bool {
   for _, p := range allowed {
     if path == p {
        return true
     }
   }
   return false
}

I want to replace this using golang gorilla mux because I might have path variables. mux's github repo says "HTTP router and URL matcher". however, there aren't examples on how to use it for URL matching.

Sahith Vibudhi
  • 4,935
  • 2
  • 32
  • 34
  • The url matching is done by the router and it is done for the purposes of routing, not validation. gorilla/mux doesn't provide a standalone matcher for your convenience. You either use the mux.Router to route http requests to specific handlers or you don't. If all you need is a validator, not a router, then do not use gorilla/mux. – mkopriva Mar 10 '20 at 10:42
  • Does this answer your question? [golang mux, routing wildcard & custom func match](https://stackoverflow.com/questions/21664489/golang-mux-routing-wildcard-custom-func-match) – ifnotak Mar 10 '20 at 10:42
  • @SahithVibudhi that said, if you still want to use gorilla/mux (please don't) then take a look at the [mux.Router.Match](https://godoc.org/github.com/gorilla/mux#Router.Match) method, and as you can see, since this is an http request router the argument must be an http request, so if you want to use it you need to turn your path, the one you want to validate, into a request. – mkopriva Mar 10 '20 at 10:43
  • I solved using a similar approach. I had to validate paths like `/users/{id}` to check if developer token has access to this endpoint. Instead of rewriting logic, I wanted to re-user mux's "URL matcher". because it ships with one. – Sahith Vibudhi Mar 10 '20 at 12:57
  • @ifnotak that doesn't solve the problem. I have added answer. – Sahith Vibudhi Mar 10 '20 at 13:05

1 Answers1

4

Here is how I solved it going through the code:

// STEP 1: create a router
router := mux.NewRouter()

// STEP 2: register routes that are allowed
router.NewRoute().Path("/users/{id}").Methods("GET")
router.NewRoute().Path("/users").Methods("GET")
router.NewRoute().Path("/teams").Methods("GET")

routeMatch := mux.RouteMatch{}

// STEP 3: create a http.Request to use in Mux Route Matcher
url := url.URL { Path: "/users/1" }
request := http.Request{ Method:"GET", URL: &url }

// STEP 4: Mux's Router returns true/false
x := router.Match(&request, &routeMatch)
fmt.Println(x) // true

url = url.URL { Path: "/other-endpoint" }
request = http.Request{ Method:"GET", URL: &url }

x = router.Match(&request, &routeMatch)
fmt.Println(x) // false
Sahith Vibudhi
  • 4,935
  • 2
  • 32
  • 34