Go HTTP Client中的重定向和重定向Cookie的问题

最近在使用HTTP Client中的遇到的问题是在请求时,需要使用重定向中间的Cookie,但是默认自动重定向10次。

获取重定向中的Cookie,有如下两种方法:

  1. 禁止重定向,然后获取response的cookie
  2. 创建CookieJar,实例化一个带CookieJar的client,存储重定向中间的cookie。

禁止重定向

代码如下:

client := &http.Client{
    // return http.ErrUseLastResponse。
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
        // return nil nil回重定向。
    },
}

创建CookieJar

var OpJar *cookiejar.Jar
OpJar, _ = cookiejar.New(nil)
Cli = resty.NewWithClient(
    &http.Client{
        Jar: OpJar,
},)