golang mux, routing wildcard & custom func match

Related searches

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.

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.

How to use wildcard or a variable in our URL for complex routing in , From Gorilla web toolkit the gorilla/mux is used to create flexible routes that allow regular expressions to dictate available variables for routers. The following� How to use wildcard or a variable in our URL for complex routing? From Gorilla web toolkit the gorilla/mux is used to create flexible routes that allow regular expressions to dictate available variables for routers. The following source code snippet shows an abbreviated program with a (very basic) regular expression in the handler. We're assigning any number of digits after /pages/ to a parameter named id in {id: [0-9]+} .This is the value we determine in pageHandler .

I'm not quite sure you need a "wildcard" route at all: you just need a route with multiple parameters:

/search/price/{price}/rage/{id}/color will work, noting that query strings don't need to be included in the matcher (you access those via request.URL.Query, whereas you access the mux variables via mux.Vars. You can also use regex to narrow down the accepted parameters.

It will also help to differentiate your user and product routes, perhaps by prefixing them with /user/{id} and /products/{id}/{code} (particularly for semantics).

As far as MatcherFunc goes, you need to make sure your function uses the same signature as MatcherFunc (which is a type): func MatchIPAddresses(*http.Request, *RouteMatch) bool would solve it. You can access the IP address via the Request struct by checking r.RemoteAddr or r.Header.Get("X-Forwarded-For") if you expect to be behind a proxy. I typically check both if one is empty ("").

i.e. (rough; you can clean this up a bit!)

func MatchIPAddresses(r *http.Request, rm *RouteMatch) bool {
    if r.RemoteAddr == 8.8.8.8 {
        return true
    } else if r.Header.Get("X-Forwarded-For") == 8.8.8.8 {
        return true
    }

    return false
}

gorilla/mux: A powerful HTTP router and URL matcher for , Package gorilla/mux implements a request router and dispatcher for matching Note that the path provided to PathPrefix() represents a "wildcard": calling� Golang has net/http package for managing HTTP. Then Why we need a third-party Golang package Gorilla Mux. The answer is Go’s net/http package offers a lot of features for HTTP requests routing but one thing it doesn’t do very well is Dynamic Routing.

With chi as router you can do the following:

Since the regex never matches a slash / you can simply match with *

e.g. for /search/price/29923/rage/200/color=red

router.Get(`/search/price/*`, priceHandler)

func DashboardFilesHandler(w http.ResponseWriter, r *http.Request) {
    path := myhandler.UrlParam(r, "*")
    // path will be '29923/rage/200/color=red'
}

See also: https://godoc.org/github.com/go-chi/chi

A placeholder with a name followed by a colon allows a regular expression match, for example {number:\d+}. The regular expression syntax is Go's normal regexp RE2 syntax, except that regular expressions including { or } are not supported, and / will never be matched. An anonymous regexp pattern is allowed, using an empty string before the colon in the placeholder, such as {:\d+}

The special placeholder of asterisk matches the rest of the requested URL. Any trailing characters in the pattern are ignored. This is the only placeholder which will match / characters.

Need help with wildcard mux routing : golang, Need help with wildcard mux routing. I'm guessing at this point that I'm just doing this the wrong way because I can't find shit about it elsewhere, although it's� gorilla/mux is a package which adapts to Go’s default HTTP router. It comes with a lot of features to increase the productivity when writing web applications.

To use a custom MatcherFunc with gorilla mux, you need to ensure that your matcher is actually of type mux.MatcherFunc. This is because MatcheFunc is not an interface type

// From mux/route.go line 303
// MatcherFunc is the function signature used by custom matchers.
type MatcherFunc func(*http.Request, *RouteMatch) bool

So you have to do something like:

var myMatcher mux.MatcherFunc = func(request *http.Request, match *mux.RouteMatch) bool {
  // Your custom logic
  return trueOrFalse
}

// You can then use it on your route like this.
router := mux.NewRouter()
router.HandleFunc("/{productid}/{code}", product).MatcherFunc(myMatcher)

Routing (using gorilla/mux), This example shows how to use the `gorilla/mux` package to create routes with named parameters, GET/POST handlers and domain restrictions. Golang has net/http package for managing HTTP. Then Why we need a third-party Golang package Gorilla Mux.The answer is Go’s net/http package offers a lot of features for HTTP requests routing but one thing it doesn’t do very well is Dynamic Routing, which will be achieved by Golang Gorilla Mux NewRouter Handle Function.

gorilla/mux, Package gorilla/mux implements a request router and dispatcher for matching Note that the path provided to PathPrefix() represents a “wildcard”: calling� golang mux, routing wildcard & custom func match. 1. Golang gorilla mux routes from class or file. 0. Type conflicts between projects. 1. Register Golang gorilla/mux

This is very strict, no wildcards, no url parameters, and not a very efficient datastructure choice for applications with lots of url routes. Gorilla Mux docs Gorilla Mux is another router implementation that takes care of the need for dynamic url routes pretty well.

) } func main() { mux := &MyMux{} http.ListenAndServe(":9090", mux) } Routing If you do not want to use a Router, you can still achieve what we wrote in the above section by replacing the second argument to ListenAndServe to nil and registering the URLs using a HandleFunc function which goes through all the registered URLs to find the best

Comments
  • Sorry. For the second solution, which involves subexpressions, I think you'd need this fork of mux: github.com/gorilla/mux/pull/11 which is what I used in my last project.
  • the regex throws an error: "unknown escape sequence"
  • Yeah, "" should be ``. Edited.
  • It doesn't throw out the error but the route is not handled either (I get 404 ) e.g. /search/price/0.000/asdasd/asdasd
  • The dot isn't matched, your initial example had no dot. Add it to the pattern: [a-zA-Z0-9=\-\/\.]+
  • undefined: RouteMatch, cannot use myfunction(<T>, *RouteMatch) (type bool) as type mux.MatcherFunc in function argument
  • I've fixed my example. I also highly recommend reading the Gorilla Mux docs, which have a similar example of how to write a MatcherFunc about halfway down the page: gorillatoolkit.org/pkg/mux
  • I've read the docs before to post the question. I think your answer is basically copied from the docs except the ip function.