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

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

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

问题

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

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

当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:

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

得分: 9

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

英文:

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

答案2

得分: 5

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

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

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

英文:

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.

答案3

得分: 0

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

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("没有提供id")
  } else {
      fmt.Println("提供了id")
  }
}
英文:

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

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:

确定