imroc / req

Simple Go HTTP client with Black Magic
https://req.cool
MIT License
4.12k stars 334 forks source link

cookies问题 #357

Closed wengooooo closed 1 month ago

wengooooo commented 1 month ago

第一次请求的时候设置了一个cookies, a的值是123456,然后服务器的set-cookies返回了a的值是1,再次发起请求的时候会出现两个a的cookie,不应该是服务器的cookie覆盖旧的cookie吗?

复现代码

client := req.C()
    client.EnableDumpAllWithoutRequestBody()
    client.SetCommonRetryCount(3)
    client.SetCommonRetryCondition(func(resp *req.Response, err error) bool {
        return true
    })
resp, err := client.R().SetCookies(&http.Cookie{Name: "a", Value: "123456"}).Send("GET", "https://httpbin.org/cookies/set/a/1")

下面是日志

:authority: httpbin.org
:method: GET
:path: /cookies/set/a/1
:scheme: https
cookie: a=123456
cookie: a=1
accept-encoding: gzip
user-agent: req/v3 (https://github.com/imroc/req)
imroc commented 1 month ago

Request.SetCookies 是请求级别的设置,当前请求会带上;server响应的同名cookie会存入cookiejar,是client级别的属性,后续请求都会带上。 在重试的时候,两者就都带上了。

如果希望重试的时候不要请求级别的cookie,可以在hook里清理掉:

    client.SetCommonRetryHook(func(resp *req.Response, err error) {
        req := resp.Request
        if req.RetryAttempt > 0 {
            req.Cookies = nil
        }
    })
wengooooo commented 1 month ago

OK,明白了。