Optional URL Variable with Gorilla Mux
This question asks how to create a route with an optional URL variable using the Gorilla Mux package. The provided route defines a regex constraint for the id variable. However, it doesn't allow the route to work without an id.
Solution:
To make the route accept an optional id, register the handler a second time with the path you want without the variable:
r.HandleFunc("/view", MakeHandler(ViewHandler))
Ensure you check for the case where the id variable is not present when getting the variables:
vars := mux.Vars(r) id, ok := vars["id"] if !ok { // directory listing return } // specific view
This will allow the route to work both with and without the id URL variable.
The above is the detailed content of How to Create an Optional URL Variable with Gorilla Mux?. For more information, please follow other related articles on the PHP Chinese website!