How to create route with optional var url using gorilla mux?

I want to have an optional URL variable in the route. I can't seem to find a way to use the mux package. Here is 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 localhost:8080/view/1 URL localhost:8080/view/1 . I want it to accept even if there is no id , so if I go into localhost:8080/view , it will work anyway. Thoughts?

+4
source share
2 answers

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

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

And let the RootHandler function do everything you need for this path.

+2
source

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

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

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

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

Source: https://habr.com/ru/post/1499538/


All Articles