处理Gorilla mux空变量

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

Handle Gorilla mux empty variable

问题

我正在使用gorilla mux来获取模式值。我该如何处理空变量,像这样:

Go:

  1. func ProductHandler(w http.ResponseWriter, r *http.Request) {
  2. vars := mux.Vars(r)
  3. a := vars["key"]
  4. if a == "" { //似乎无法识别空字符串
  5. //做一些事情
  6. } else {
  7. //做一些事情
  8. }
  9. }
  10. var r = mux.NewRouter()
  11. func main() {
  12. r.HandleFunc("/products/{key}", ProductHandler)
  13. http.Handle("/", r)
  14. http.ListenAndServe(":8080", nil)
  15. }

当我输入网址www.example.com/products或www.example.com/products/时,我得到一个404页面未找到的错误。我该如何在ProductHandler中处理空变量?

http://www.gorillatoolkit.org/pkg/mux

英文:

I'm using gorilla mux to get pattern values. How do I handle an empty variable like so:

Go:

  1. func ProductHandler (w http.ResponseWriter, r *http.Request) {
  2. vars := mux.Vars(r)
  3. a := vars["key"]
  4. if a = "" { //does not seem to register empty string
  5. //do something
  6. } else
  7. //do something
  8. }
  9. var r = mux.NewRouter()
  10. func main() {
  11. r.HandleFunc("/products/{key}", ProductHandler)
  12. http.Handle("/", r)
  13. http.ListenAndServe(":8080", nil)
  14. }

When I type the url www.example.com/products or www.example.com/products/ I get a 404 page not found error. How do i handle an empty variable in ProductHandler?

http://www.gorillatoolkit.org/pkg/mux

答案1

得分: 3

最简单的解决方案?添加:

  1. r.HandleFunc("/products", ProductHandler)

我很确定Gorilla会按照注册的顺序路由最长的匹配项。

这也是文档概述页面建议的用法:

然后在子路由器中注册路由:

  1. s.HandleFunc("/products/", ProductsHandler)
  2. s.HandleFunc("/products/{key}", ProductHandler)
  3. s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
英文:

Simplest solution? Add:

  1. r.HandleFunc("/products", ProductHandler)

I am pretty sure Gorilla will route <s>the longest match</s> in order of registration.

This is also the way the documentation's overview page suggest it be used:

>Then register routes in the subrouter:
>
s.HandleFunc("/products/", ProductsHandler)
s.HandleFunc("/products/{key}", ProductHandler)
s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)

huangapple
  • 本文由 发表于 2014年10月3日 22:50:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/26181282.html
匿名

发表评论

匿名网友

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

确定