Home > Backend Development > Golang > How to Create an Optional URL Variable with Gorilla Mux?

How to Create an Optional URL Variable with Gorilla Mux?

Barbara Streisand
Release: 2024-11-26 10:17:10
Original
868 people have browsed it

How to Create an Optional URL Variable with Gorilla Mux?

Optional URL Variable with Gorilla Mux

This question asks how to create a route with an optional URL variable using the Gorilla Mux package. The provided route defines a regex constraint for the id variable. However, it doesn't allow the route to work without an id.

Solution:

To make the route accept an optional id, register the handler a second time with the path you want without the variable:

r.HandleFunc("/view", MakeHandler(ViewHandler))
Copy after login

Ensure you check for the case where the id variable is not present when getting the variables:

vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
  // directory listing
  return
}
// specific view
Copy after login

This will allow the route to work both with and without the id URL variable.

The above is the detailed content of How to Create an Optional URL Variable with 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