为什么在Go的http.Client中进行POST请求时不遵循301重定向?

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

Why do POST request in the Go http.Client not follow 301 redirects?

问题

我正在使用Go构建一个测试工具。该工具可以通过向一个端点发送POST请求来检索特定的URL,该端点返回一个带有Location的303重定向。有时,这个位置本身会被301重定向,我也想要跟随这个重定向。

测试工具 -> POST /get-url-to-test -> 303 Location: /other -> GET /other -> 301 Location: /new-other(因为初始请求是POST,所以停在这里)

正如我们在Go的源代码中看到的(241到257行),似乎GET请求会跟随301重定向,但POST请求不会:
http://golang.org/src/net/http/client.go

为什么会这样?这是HTTP规范的一部分吗?这是Go社区做出的决定吗?

我之所以问这个问题,是因为在我的情况下,我需要手动进行新的GET请求,以获取被/other重定向到的URL。


编辑1:我之前犯了一个错误:Go使用GET请求获取了/other资源。但由于它返回了一个301,而初始请求是POST,Go在301上停止了重定向。这看起来很奇怪。我是不是漏掉了什么?

编辑2:这可能是一个bug,我在Github上提了一个问题:https://github.com/golang/go/issues/9348

英文:

I'm building a test tool with Go. This tool can retrieve a specific URL by doing a POST request to an endpoint which returns a 303 with the Location to test. Sometimes this location itself is redirected with a 301 which I want to follow as well.

Test tool -> POST /get-url-to-test -> 303 Location: /other -> GET /other -> 301 Location: /new-other (stops here because initial request is POST)

As we can see in Go's source (lines 241 to 257), it seems like GET requests follow 301 redirects, but not POST requests:
http://golang.org/src/net/http/client.go

Why is that? Is that part of an HTTP spec? Is this an decision that was made by the Go community?

The reason I'm asking is because in my case, I'd have to manually do a new GET request to get to the URL redirected to by /other, I think.


EDIT 1: I made a mistake before: the /other resource is being fetched by Go with a GET request. But since it returns a 301 and the initial request was a POST, Go stops redirecting on the 301. That seems odd. Am I missing something?

EDIT 2: This may be a bug, I've opened an issue on Github: https://github.com/golang/go/issues/9348

答案1

得分: 3

HTTP RFC 2616中提到:

> 10.3 重定向 3xx
>
> 这个状态码类别表示用户代理需要采取进一步的操作才能完成请求。如果第二个请求中使用的方法是GET或HEAD,用户代理可以在不与用户交互的情况下执行所需的操作。

英文:

The HTTP RFC 2616 says:

> 10.3 Redirection 3xx
>
> This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent
> without interaction with the user if and only if the method used in
> the second request is GET or HEAD
.

huangapple
  • 本文由 发表于 2014年12月16日 20:49:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/27505066.html
匿名

发表评论

匿名网友

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

确定