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

How to Create Optional URL Variables in Gorilla Mux?

Patricia Arquette
Release: 2024-11-29 08:26:09
Original
430 people have browsed it

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

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

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

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!

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