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

How to Handle Optional URL Variables in Gorilla Mux?

Susan Sarandon
Release: 2024-12-11 16:30:11
Original
751 people have browsed it

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)
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template