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?
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)