go - 在没有第三方路由库的情况下路由 PUT 请求

标签 go

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/

相关文章:

go - 为什么要命名返回参数?

go - 当参数不是 go 中的指针时,使用 reflect 通过引用更新值

Golang 反射 : passing a sturct member variable to a function and return its tag name

for-loop - Golang 赋值

for-loop - GO - for 循环中的子例程行为

go - 如何在golang中将bool转换为int8

unit-testing - 从 %APPDATA% 开始单元测试

go - Go中的父子上下文取消顺序

go - 如果一个 child 正在使用,垃圾会收集父类吗?

go - Go中的嵌套 map