http - 如何使 Go HTTP 客户端不自动跟随重定向?

标签 http rest redirect go

我目前正在用 Go 编写一些与 REST API 交互的软件。我尝试查询的 REST API 端点返回一个 HTTP 302 重定向以及一个指向资源 URI 的 HTTP Location header 。

我正在尝试使用我的 Go 脚本来获取 HTTP Location header 以供以后处理。

这是我目前为实现此功能所做的工作:

package main

import (
        "errors"
        "fmt"
        "io/ioutil"
        "net/http"
)

var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"

func noRedirect(req *http.Request, via []*http.Request) error {
        return errors.New("Don't redirect!")
}

func main() {

        client := &http.Client{
            CheckRedirect: noRedirect
        }
        req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
        req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)

        resp, err := client.Do(req)

        // If we get here, it means one of two things: either this http request
        // actually failed, or we got an http redirect response, and should process it.
        if err != nil {
            if resp.StatusCode == 302 {
                fmt.Println("got redirect")
            } else {
                panic("HTTP request failed.")
            }
        }
        defer resp.Body.Close()

}

这对我来说有点像黑客。通过覆盖 http.ClientCheckRedirect 函数,我基本上被迫将 HTTP 重定向视为错误(它们不是)。

我已经看到其他几个地方建议使用 HTTP 传输而不是 HTTP 客户端 - 但我不确定如何进行这项工作,因为我需要 HTTP 客户端,因为我需要使用 HTTP Basic Auth 进行通信使用此 REST API。

你们谁能告诉我一种使用基本身份验证发出 HTTP 请求的方法 - 虽然不遵循重定向 - 不涉及抛出错误和错误处理?

最佳答案

现在有一个更简单的解决方案:

client := &http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    },
}

这样,http 包会自动知道:“啊,我不应该遵循任何重定向”,但不会抛出任何错误。来自源代码中的注释:

As a special case, if CheckRedirect returns ErrUseLastResponse, then the most recent response is returned with its body unclosed, along with a nil error.

关于http - 如何使 Go HTTP 客户端不自动跟随重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297520/

相关文章:

http - HTTP 内容协商是否尊重媒体类型参数

java - 自动生成 HTTP 屏幕抓取 Java 代码

php - 更改 http header 信息以隐藏服务器信息

java - Weblogic 12.1.3,Jersey 2.5.1,如何启用MultiPartFeature : WELD-001408 Unsatisfied dependencies for type [Providers]

javascript - 为什么 document.write() 在 Firefox 和 Chrome 中的行为不同?

c - Azure物联网中心: HTTP Device-to-Cloud Messages without SDK?

java - SmartGWT RestDateSource 和分页(大数据集)动态数据

c# - DataContract 不使用属性中指定的名称属性

重定向和谷歌问题

php header 位置与 php_redirect