Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a route with optional url var using gorilla mux?

Tags:

go

mux

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?

like image 1000
anlogg Avatar asked Aug 29 '13 05:08

anlogg


People also ask

What is Gorilla mux router?

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.

What is mux Vars?

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.

Should I use Gorilla mux?

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'.

What is a Subrouter?

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 .


1 Answers

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
like image 147
Kyle Lemons Avatar answered Sep 21 '22 01:09

Kyle Lemons