英文:
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?
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论