英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论