How to create a route with optional url var using gorilla mux?
Asked Answered
B

3

10

I want to have an optional URL variable in route. I can't seem to find a way using mux package. Here's my current route:

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/view/{id:[0-9]+}", MakeHandler(ViewHandler))
    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)
}

It works when the url is localhost:8080/view/1. I want it to accept even if there's no id so that if I enter localhost:8080/view it'll still work. Thoughts?

Benedic answered 29/8, 2013 at 5:49 Comment(0)
T
5

You could define a new HandleFunc for the root /view path:

r.HandleFunc("/view", MakeHandler(RootHandler))

And have the RootHandler function do whatever you require for that path.

Typesetter answered 29/8, 2013 at 6:9 Comment(0)
O
10

Register the handler a second time with the path you want:

r.HandleFunc("/view", MakeHandler(ViewHandler))

Just make sure when you are getting your vars that you check for this case:

vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
  // directory listing
  return
}
// specific view
Olnay answered 29/8, 2013 at 6:10 Comment(0)
T
5

You could define a new HandleFunc for the root /view path:

r.HandleFunc("/view", MakeHandler(RootHandler))

And have the RootHandler function do whatever you require for that path.

Typesetter answered 29/8, 2013 at 6:9 Comment(0)
W
1

You can use the ? character to indicate that the id:[0-9]+ pattern is optional, and handle whenever there is an id is passed or not in your ViewHandler function.

main:

func main() {
  r := mux.NewRouter()
  r.HandleFunc("/view/{id:[0-9]+?}", MakeHandler(ViewHandler))
  http.Handle("/", r)
  http.ListenAndServe(":8080", nil)
}

ViewHandler:

func ViewHandler(w http.ResponseWriter, r *http.Request) {
  vars := mux.Vars(r)
  id := vars["id"]
  if id == "" {
      fmt.Println("there is no id")
  } else {
      fmt.Println("there is an id")
  }
}
Wirth answered 8/3, 2023 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.