处理Gorilla mux空变量

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

Handle Gorilla mux empty variable

问题

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

Go:

func ProductHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    a := vars["key"]
    if a == "" {       //似乎无法识别空字符串
        //做一些事情
    } else {
        //做一些事情
    }
}

var r = mux.NewRouter()

func main() {
    r.HandleFunc("/products/{key}", ProductHandler)

    http.Handle("/", r)

    http.ListenAndServe(":8080", nil)
}

当我输入网址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:

func ProductHandler (w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    a := vars["key"]
    if a = "" {       //does not seem to register empty string
       //do something
    } else 
       //do something
}

var r = mux.NewRouter()

func main() {
    r.HandleFunc("/products/{key}", ProductHandler)

    http.Handle("/", r)

    http.ListenAndServe(":8080", nil)
}

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

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

r.HandleFunc("/products", ProductHandler)

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

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

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

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

Simplest solution? Add:

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:

确定