在this Blake Mizerany 的 Golang 演讲的 Youtube 视频(大约 15:29),他谈到了如何在不使用第三方包的情况下构建路由器,详细介绍了如何构建具有可变组件(例如 id)的路由.这是他使用的处理程序,第一行显示如何获取路由的可变组件(即 key )
func productHandler(w http.ResponseWriter, r *http.Request){
key := r.URL.Path[len("/products/":]
switch r.Method{
case "GET":
//do stuff
case "POST"
//do stuff
default:
http.Error(w, "method not allowed", 405)
}
}
虽然他的实际路线是什么样子,但从他的介绍中并不清楚。
我正在尝试构建一个路由来处理带有 id 的放置请求。当我点击我页面上的一个元素时,它会向这条路线发送一个放置请求
http://localhost:8080/products/1433255183951
我有一条这样的路线
http.HandleFunc("/products/{id}", doSomethingWithProduct){
}
当然还有函数
func doSomethingWithProduct(res http.ResponseWriter, req *http.Request{
key := req.URL.Path[len("/products/"):]
log.Println(key, "is this logging?? nope")
}
问题。即使我设置了该路由和处理程序,当我单击该元素时,我仍未找到 404,并且没有迹象表明我的函数已被调用(即它没有记录)
问题:如何创建自定义路由/函数来处理对
的 PUT 请求http://localhost:8080/products/1433255183951
最佳答案
http.HandleFunc
不会像您尝试使用 {id}
那样处理“捕获组”。
http.HandleFunc("/products/", handler)
将匹配所有以此模式开头的路由。您必须自己解析其余部分。
参见 ServeMux .
ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.
Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.
Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".
Patterns may optionally begin with a host name, restricting matches to URLs on that host only. Host-specific patterns take precedence over general patterns, so that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without also taking over requests for "http://www.google.com/".
ServeMux also takes care of sanitizing the URL request path, redirecting any request containing . or .. elements to an equivalent .- and ..-free URL.
关于go - 在没有第三方路由库的情况下路由 PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30605500/