2

I'm using gorilla mux to get pattern values. How do I handle an empty variable like so:

Go:

func ProductHandler (w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    a := vars["key"]
    if a = "" {       //does not seem to register empty string
       //do something
    } else 
       //do something
}

var r = mux.NewRouter()

func main() {
    r.HandleFunc("/products/{key}", ProductHandler)

    http.Handle("/", r)

    http.ListenAndServe(":8080", nil)
}

When I type the url www.example.com/products or www.example.com/products/ I get a 404 page not found error. How do i handle an empty variable in ProductHandler?

http://www.gorillatoolkit.org/pkg/mux

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user3918985
  • 4,278
  • 9
  • 42
  • 63
  • possible duplicate of [How to create a route with optional url var using gorilla mux?](http://stackoverflow.com/questions/18503189/how-to-create-a-route-with-optional-url-var-using-gorilla-mux) – Sven Grosen Oct 03 '14 at 15:33
  • @SvenGrosen you're not supposed to write that by hand. When you cast a close-vote because of duplication, it's automatically posted for you :P – thwd Oct 03 '14 at 15:37
  • @tomwilde I didn't write it by hand, just flagged it. – Sven Grosen Oct 03 '14 at 15:39
  • Weird. Maybe they changed the system but I can only see one my own vote. I'll post on meta. – thwd Oct 03 '14 at 15:39

1 Answers1

3

Simplest solution? Add:

r.HandleFunc("/products", ProductHandler)

I am pretty sure Gorilla will route the longest match in order of registration.

This is also the way the documentation's overview page suggest it be used:

Then register routes in the subrouter:

s.HandleFunc("/products/", ProductsHandler)
s.HandleFunc("/products/{key}", ProductHandler)
s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
thwd
  • 23,956
  • 8
  • 74
  • 108