回答

收藏

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

技术问答 技术问答 358 人阅读 | 0 人回复 | 2023-09-12

我目前正在使用 Go 写一些和 REST API 交互软件。我试着查询 REST API 端点返回 HTTP 302 重定向和指向资源 URI 的 HTTP Location 标头。
' X2 N/ M9 d" Y7 f- b5 p我试着用我的 Go 脚本来获取 HTTP Location 标头供以后处理。' {9 ]7 J/ b5 V. P' S. ?$ l
这是我目前为实现这一功能所做的:2 q( K& \$ D% q, Y: {3 `4 n
    package mainimport (       "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()}
    3 w: v" u5 B* P; i) a0 @0 J8 x; F$ R
这对我来说有点像黑客。通过覆盖http.Client‘sCheckRedirect我基本上被迫使用 函数HTTP 重定向视为错误(不是)。8 H& s* y9 F2 U) w3 f! y
我已经看到其他地方建议使用 HTTP 传输而不是 HTTP 客户端-但我不知道如何做这项工作,因为我需要 HTTP 客户端,因为我需要使用 HTTP 基本身份验证与此 REST 通信应用程序接口。
. }' u$ d6 j# |2 y) K你们中的任何人都可以告诉我使用基本身份验证 HTTP 请求方法-不遵循重定向-不涉及抛出错误和错误处理?( g3 q) E/ \: W4 e; z
                                                               
  ~  d  b# ]- z1 i) P: j    解决方案:                                                               
" q% O5 a# u# f$ U  O% m; A                                                                现在有更简单的解决方案:- T, v- Y9 H* C" z
[code]client := &http.Client{    CheckRedirect: func(req *http.Request,via []*http.Request) error              return http.ErrUseLastResponse}code]这样,http包自动知道:啊,我不应该遵循任何重定向,但不会出错。源代码中的注释:
  v' j1 w% K3 |+ i$ s- B如果 作为一种特殊情况CheckRedirect 返回 ErrUseLastResponse,返回最新响应,其主体未关闭,并带有 nil 错误。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则