英文:
how to correctly pattern match with routers handleFunc?
问题
我正在使用gorilla web toolkit和golang,并且有以下的代码:
func test(w http.ResponseWriter, r *http.Request) {
fmt.Println("test was called ..")
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
mx := mux.NewRouter()
mx.HandleFunc(?, test)
http.ListenAndServe(":8080", mx)
}
我的服务器将提供一个包含表单的HTML文档,该表单将执行一个GET请求并发送"/?id={something}"。我该如何设置mx.HandleFunc中的模式以匹配查询,以便调用test函数?
我尝试过以下方式:
- "/?id={something}"
- "/?id="
- mx.HandleFunc("/", test).Queries("id")
- mx.HandleFunc("/", test).Methods("POST")(最后一个我更改了相应的页面代码,使表单进行POST请求)
英文:
I am using gorilla web toolkit and golang, and have the following code
func test(w http.ResponseWriter, r *http.Request) {
fmt.Println("test was called ..")
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
mx := mux.NewRouter()
mx.HandleFunc(?, test)
http.ListenAndServe(":8080", mx)
}
My server will serve a html-document with a form that will do a get-request and send a "/?id={something}". How can I set up a pattern in the mx.HandleFunc to match the query so that test is called?
I have tried:
"/?id={something},
"/?id=",
mx.HandleFunc("/", test).Queries("id")
mx.HandleFunc("/", test).Methods("POST")
(the last one I changed the corresponding page code so that form makes a post instead).
答案1
得分: 2
当使用.Queries()
时,你需要给它提供一个键和一个值,例如:
mx.HandleFunc("/", test).Queries("id", "value")
你还可以将模式用作值,例如:
mx.HandleFunc("/", test).Queries("id", "{id:[0-9]+}")
详细信息请参见这里:http://godoc.org/github.com/gorilla/mux#Route.Queries
英文:
When using .Queries()
you need to give it both a key and a value, like:
mx.HandleFunc("/", test).Queries("id", "value")
You can also use a pattern as the value, like:
mx.HandleFunc("/", test).Queries("id", "{id:[0-9]+}")
See here for details: http://godoc.org/github.com/gorilla/mux#Route.Queries
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论