Home >Backend Development >Golang >How to Handle Optional URL Variables in Gorilla Mux?

How to Handle Optional URL Variables in Gorilla Mux?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 16:30:11749browse

How to Handle Optional URL Variables in Gorilla Mux?

Optional URL Variables with 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn