I want to have an optional URL variable in route. I can't seem to find a way using mux package. Here's my current route:
func main() {
r := mux.NewRouter()
r.HandleFunc("/view/{id:[0-9]+}", MakeHandler(ViewHandler))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
It works when the url is localhost:8080/view/1
. I want it to accept even if there's no id
so that if I enter localhost:8080/view
it'll still work. Thoughts?
Gorilla Mux provides functionalities for matching routes, serving static files, building single-page applications (SPAs), middleware, handling CORS requests, and testing handlers. This tutorial will walk you through using the Gorilla Mux package as a router for your applications.
The name mux stands for "HTTP request multiplexer". Like the standard http. ServeMux, mux. Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions.
Given that the downsides of chi and gorilla/mux are similar, picking between the two is fairly straightforward: opt for gorilla/mux if you need support for custom routing rules, host-based routing or route 'reversing'.
Matching Routes Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". For example, let's say we have several URLs that should only match when the host is www.example.com .
Register the handler a second time with the path you want:
r.HandleFunc("/view", MakeHandler(ViewHandler))
Just make sure when you are getting your vars that you check for this case:
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
// directory listing
return
}
// specific view
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With