【问题标题】:Wikipedia url stopped after 10 redirects error GoLang维基百科网址在 10 次重定向错误 GoLang 后停止
【发布时间】:2015-11-24 23:42:51
【问题描述】:

在执行 HTTP Get 请求时,我收到以下错误:

2015/08/30 16:42:09 Get https://en.wikipedia.org/wiki/List_of_S%26P_500_companies: 
stopped after 10 redirects

在以下代码中:

package main

import (
    "net/http"
    "log"
)

func main() {
    response, err := http.Get("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies")
    if err != nil {
        log.Fatal(err)
    }
}

我知道根据文档,

// Get issues a GET to the specified URL. If the response is one of
// the following redirect codes, Get follows the redirect, up to a
// maximum of 10 redirects:
//
//    301 (Moved Permanently)
//    302 (Found)
//    303 (See Other)
//    307 (Temporary Redirect)
//
// An error is returned if there were too many redirects or if there
// was an HTTP protocol error. A non-2xx response doesn't cause an
// error.

我希望有人知道这种情况下的解决方案是什么。这个简单的 url 导致十多个重定向似乎很奇怪。让我觉得幕后可能还有更多事情发生。

谢谢。

【问题讨论】:

  • 如果你只是想解决这个问题,我建议更改http包源。
  • 我觉得这里有些不对劲。该请求不仅可以从 telnet / curl 工作而无需单个重定向,而且您的示例程序(一旦我对响应做了一些事情)也可以在没有任何重定向的情况下工作。您是否正在通过某种代理,这就是导致重定向的原因?
  • 使用 curl 可以吗?

标签: redirect go https


【解决方案1】:

正如其他人所指出的,您应该首先考虑一下为什么会遇到如此多的 HTTP 重定向。 Go 的默认策略是在 10 个重定向处停止是合理的。超过 10 个重定向可能意味着您处于重定向循环中。这可能是在您的代码之外引起的。它可能是由您的网络配置、您与网站之间的代理服务器等引起的。

也就是说,如果您确实需要更改默认策略,则无需像有人建议的那样求助于编辑 net/http 源。

要更改重定向的默认处理,您需要创建一个客户端并设置 CheckRedirect。

供您参考: http://golang.org/pkg/net/http/#Client

// If CheckRedirect is nil, the Client uses its default policy,
// which is to stop after 10 consecutive requests.
CheckRedirect func(req *Request, via []*Request) error

【讨论】:

  • 他得到了一个重定向循环。检查重定向不会阻止导致服务器发送它们的任何原因。
  • 好点。我没有想过他为什么会违反 10 次重定向的默认策略。我将编辑我的答案。
【解决方案2】:

我对包含 %26 的 Wikipedia URL 有此问题,因为它们重定向到带有 & 的 URL 版本,然后 Go 编码为 %26,Wikipedia 重定向到 & 和 ...

奇怪的是,从我的 Arch 盒子中删除 gcc-go (v1.4) 并用 go (v1.5) 替换它已经解决了这个问题。

我猜这可以归结为 net/http 在 v1.4 和 v1.5 之间的变化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2014-11-14
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多