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

夙愿已清 提交于 2019-12-23 09:58:33

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/18503189/how-to-create-a-route-with-optional-url-var-using-gorilla-mux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!