I've been working on a Go project where gorilla/mux is used as the router.
I need to be able to have query values associated with a route, but these values should be optional.
That means that I'd like to catch both /articles/123
and /articles/123?key=456
in the same handler.
To accomplish so I tried using the r.Queries
method that accepts key/value pairs:
router.
Path("/articles/{id:[0-9]+}").Queries("key", "{[0-9]*?}")
but this makes only the value (456
) optional, but not the key
.
So both /articles/123?key=456
and /articles/123?key=
are valid, but not /articles/123
.
Edit: another requirement is that, after registering the route, I'd like to build them programatically, and I can't seem to work out how to use r.Queries
even though the docs specifically state that it's possible (https://github.com/gorilla/mux#registered-urls).
@jmaloney answer works, but doesn't allow to build URLs from names.
mux.Vars(req)["tab"]
in my Handler 2. it doesn't allow me to build registered URLs by name (I've updated the question) – Routinize