我目前正在Go中编写一些与REST API交互的软件 . 我正在尝试查询的REST API endpoints 返回HTTP 302重定向以及指向资源URI的HTTP Location标头 .
我正在尝试使用Go脚本来获取HTTP Location标头以供以后处理 .
以下是我目前正在实现的功能:
package main
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var BASE_URL = "https://api.stormpath.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(STORMPATH_API_KEY_ID, STORMPATH_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.Client
的 CheckRedirect
函数,我'm essentially forced to treat HTTP redirects like errors (which they aren' t) .
我已经看到其他几个地方建议使用HTTP传输而不是HTTP客户端 - 但我不知道如何使这项工作,因为我需要HTTP客户端,因为我需要使用HTTP Basic Auth与此REST通信API .
您是否可以告诉我一种使用基本身份验证发出HTTP请求的方法 - 虽然不遵循重定向 - 但这不涉及抛出错误和错误处理?
谢谢 .
4 回答
要使用不遵循重定向的Basic Auth发出请求,请使用接受* Request的RoundTrip函数
这段代码
输出
现在有一个更简单的解决方案:
这样,
http
包自动知道:"Ah, I shouldn't follow any redirects",但不会抛出任何错误 . 从源代码中的注释:这是可能的,但解决方案稍微扭转了问题 . 这是一个写成golang测试的示例 .
您应该能够将上面的代码放入它自己的名为“redirects”的包中,并在使用后获取所需的依赖项后运行它
希望这可以帮助!
另一种选择,使用客户端本身,没有RoundTrip:
UPDATE: 此解决方案适用于<1.7