猿问

如何获取第一个 HTTP(重定向)响应?

我使用 Go http 包开发了一个代码,以便我可以获取任何 url 的状态代码。但经过一番挖掘后,我检查了为什么请求需要很长时间,我发现 URL 一直在重定向,直到我得到状态 200 OK。

我想设法从 Web 服务器获得第一个响应。我不想总是得到 200 OK,无论它给我什么,我都想接受它。我该怎么办?

示例: 当我使用 cURL 获取代码时,https ://apple.com 响应 301 MOVED PERMANENTLY。这就是我想要的响应,而不是重定向到 200。


守着一只汪
浏览 408回答 1
1回答

慕仙森

http.Client提供了通过CheckRedirect成员控制它的可能性。从上面的链接:// CheckRedirect specifies the policy for handling redirects.// If CheckRedirect is not nil, the client calls it before// following an HTTP redirect. The arguments req and via are// the upcoming request and the requests made already, oldest// first. If CheckRedirect returns an error, the Client's Get// method returns both the previous Response and// CheckRedirect's error (wrapped in a url.Error) instead of// issuing the Request req.//// If CheckRedirect is nil, the Client uses its default policy,// which is to stop after 10 consecutive requests.ct func(req *Request, via []*Request) error
随时随地看视频慕课网APP

相关分类

Go
我要回答