Home >Backend Development >Golang >How to Create Optional URL Variables in Gorilla Mux?
Creating a Route with Optional URL Variable in Gorilla Mux
In Gorilla Mux, an optional URL variable can be achieved by registering the handler multiple times with different URL paths. For example, consider the following route:
r.HandleFunc("/view/{id:[0-9]+}", MakeHandler(ViewHandler))
This route matches URLs like "/view/1", where "{id}" is a required variable. To make this parameter optional, register the handler again without the required syntax:
r.HandleFunc("/view", MakeHandler(ViewHandler))
Now, both "/view/1" and "/view" will work.
When accessing variables, it's crucial to check for the presence of the optional parameter. Use mux.Vars(r) to retrieve the route variables and use ok variable to determine if a parameter is set:
vars := mux.Vars(r) id, ok := vars["id"] if !ok { // Directory listing return } // Specific view
With this approach, you can create routes with flexible and optional URL parameters in Gorilla Mux.
The above is the detailed content of How to Create Optional URL Variables in Gorilla Mux?. For more information, please follow other related articles on the PHP Chinese website!