使用Gorilla Mux如何创建带有可选URL变量的路由?

huangapple go评论116阅读模式
英文:

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

问题

我想在路由中添加一个可选的URL变量。我似乎找不到使用mux包的方法。这是我的当前路由:

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

当URL为localhost:8080/view/1时,它可以正常工作。我希望即使没有id,它也能接受URL,这样如果我输入localhost:8080/view,它仍然可以工作。你有什么想法?

英文:

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:

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

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

得分: 9

请问您需要将这段代码翻译成中文吗?

英文:

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

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

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

  1. vars := mux.Vars(r)
  2. id, ok := vars["id"]
  3. if !ok {
  4. // directory listing
  5. return
  6. }
  7. // specific view

答案2

得分: 5

你可以为根路径/view定义一个新的HandleFunc

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

然后,RootHandler函数可以根据你的需求处理该路径。

英文:

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

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

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

答案3

得分: 0

你可以使用?字符来表示id:[0-9]+模式是可选的,并在ViewHandler函数中处理是否传递了id

main:

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

ViewHandler:

  1. func ViewHandler(w http.ResponseWriter, r *http.Request) {
  2. vars := mux.Vars(r)
  3. id := vars["id"]
  4. if id == "" {
  5. fmt.Println("没有提供id")
  6. } else {
  7. fmt.Println("提供了id")
  8. }
  9. }
英文:

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:

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

ViewHandler:

  1. func ViewHandler(w http.ResponseWriter, r *http.Request) {
  2. vars := mux.Vars(r)
  3. id := vars["id"]
  4. if id == "" {
  5. fmt.Println("there is no id")
  6. } else {
  7. fmt.Println("there is an id")
  8. }
  9. }

huangapple
  • 本文由 发表于 2013年8月29日 13:49:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/18503189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定