如何正确使用`handleFunc`函数进行路由模式匹配?

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

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

huangapple
  • 本文由 发表于 2015年3月24日 21:37:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/29234122.html
匿名

发表评论

匿名网友

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

确定