Go 网络服务器未处理 POST 个请求

Go Webserver Not Handling POST Requests

我正在使用 Go 的 http 包创建一个简单的网络服务器。我只注册一个处理程序,用于对路径“/requests/”的请求。

它可以很好地处理 GET 请求,但是当我发送 POST 请求时,处理程序永远不会被调用,客户端会收到 301 Moved Permanently 响应。

我试过搜索这个,但看起来这不是人们通常面临的问题。

我的处理人是:

func requestHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello")
}

主要功能:

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/requests/", requestHandler)
    http.ListenAndServe(":8000", mux)
}

Curl 给出以下输出:

>> curl -i -X POST http://localhost:8000/requests
HTTP/1.1 301 Moved Permanently
Location: /requests/
Date: Thu, 12 Jan 2017 08:51:10 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8

Go自带的http客户端returns类似的响应对象:

 &{301 Moved Permanently 301 HTTP/1.1 1 1 map[Content-Type:[text/plain; charset=utf-8] Location:[/requests/] Date:[Thu, 12 Jan 2017 08:51:58 GMT] Content-Length:[0]] 0x339190 0 [] false false map[] 0xc4200cc0f0 <nil>}

同样,GET 请求的行为与我预期的一样,并调用了处理程序函数。我是否需要做一些不同的事情来处理 POST 请求?感谢您对此的任何帮助!

您正在查询 /requests

重定向将您指向 /requests/

你是这样使用 curl 的:

curl localhost:8000/requests

您需要在 mux.HandleFunc 中使用 /requests 而不是 /requests/

或使用

curl localhost:8000/requests/

另请注意,如果您的请求无需任何更改即可在浏览器上运行,因为它会自动处理重定向。

如果 mux.HandleFunc 中的路由没有尾部斜杠,则带有尾部斜杠的路由将 return 404。

PS :您的 requestHandler 处理所有方法,而不仅仅是 POST 请求。您需要检查 r.Method 以不同方式处理这些方法。