Home >Backend Development >Golang >How to Handle Optional URL Variables in Gorilla Mux?
In Gorilla Mux, you can define optional URL variables by registering the handler with multiple paths.
For example, consider the following route:
func main() { r := mux.NewRouter() r.HandleFunc("/view/{id:[0-9]+}", MakeHandler(ViewHandler)) // Add a second handler for the optional URL variable r.HandleFunc("/view", MakeHandler(ViewHandler)) http.Handle("/", r) http.ListenAndServe(":8080", nil) }
The first route matches URLs with an integer id variable, while the second route matches URLs without an id variable.
When accessing variables from the request, check for the presence of the optional variable:
vars := mux.Vars(r) id, ok := vars["id"] if !ok { // Directory listing or some other action without an ID return } // Specific view with the ID
By registering the handler twice, you can handle both scenarios: URLs with and without the optional id variable.
The above is the detailed content of How to Handle Optional URL Variables in Gorilla Mux?. For more information, please follow other related articles on the PHP Chinese website!