Search code examples
goroutesmux

How to use Gorilla Mux for URL matching?


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.


Solution

  • 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