Go的HTTP客户端不会自动跟随重定向。

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

Go http client not follow redirects

问题

我有一个用于检查URL的函数:

func Checkurl(url string) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    resp, err := client.Get(url)
}

在错误变量中:unexpected EOF

在tcpdump中,我看到了重定向和连接关闭:

15:53:41.510722 IP (tos 0x0, ttl 248, id 18315, offset 0, flags [none], proto TCP (6), length 123)
XXX.XXX.XXX.XXX.80 > XXX.XXX.XXX.XXX.53618: Flags [F.], cksum 0xb96f (correct), seq 85:168, ack 1, win 5840, length 83: HTTP, length: 83
HTTP/1.1 302 Moved Temporarily
Location: http://XXX.XXX.XXX.XXX
Connection: close

我如何获取Location?

英文:

I have a function for check url like that:

func Checkurl(url string) {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
resp, err := client.Get(url)

In error var: unexpected EOF

In tcpdump i see redirect and Connection close:

15:53:41.510722 IP (tos 0x0, ttl 248, id 18315, offset 0, flags [none], proto TCP (6), length 123)
XXX.XXX.XXX.XXX.80 > XXX.XXX.XXX.XXX.53618: Flags [F.], cksum 0xb96f (correct), seq 85:168, ack 1, win 5840, length 83: HTTP, length: 83
HTTP/1.1 302 Moved Temporarily
Location: http://XXX.XXX.XXX.XXX
Connection: close

How i can get Location?

答案1

得分: 1

使用Response.Location函数。

newUrl, err := resp.Location()

Client类型支持重定向。请查看CheckRedirect字段。根据您的需求,这可能是处理重定向的更好工具。

使用client.Do来调用Request对象的方法。

client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
// 检查错误
resp, err := client.Do(req)
// 检查错误
newURL, err := resp.Location()
// 检查错误

默认客户端默认处理重定向,因此我建议检查最终目标的响应。这很可能是您问题的根本原因。

英文:

Use Response.Location function.

newUrl, err := resp.Location()

Type Client has support for redirection. See CheckRedirect field. This might be a better tool for handling redirects, depending on what you are trying to achieve.

Use client.Do for Request object method

client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
// check error
resp, err := client.Do(req)
// check error
newURL, err := resp.Location()
// check error

The default client handles redirections by default, therefore I would check the response of the final destination. It is most probably the root cause of your problem.

huangapple
  • 本文由 发表于 2017年4月20日 21:15:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/43520655.html
匿名

发表评论

匿名网友

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

确定