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
Barbara StreisandOriginal
2024-11-26 10:17:10919browse

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))

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

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!

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