Go HTTP Client中的重定向和重定向Cookie的問題
最近在使用HTTP Client中的遇到的問題是在請求時,需要使用重定向中間的Cookie,但是默認自動重定向10次。
獲取重定向中的Cookie,有如下兩種方法:
- 禁止重定向,然后獲取response的cookie
- 創建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,
},)