From bc3bfea33d95b94d3cd7917a0de81979646e0d66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=87=E8=91=A9=E3=81=AE=E7=81=B5=E6=A2=A6?= Date: Thu, 4 Jul 2024 16:06:39 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E5=A4=9A=E6=AC=A1=E8=B0=83?= =?UTF-8?q?=E7=94=A8SetCookies=E4=BC=9A=E5=AF=BC=E8=87=B4cookies=E8=B6=8A?= =?UTF-8?q?=E6=9D=A5=E8=B6=8A=E9=95=BF=E7=9A=84=E9=97=AE=E9=A2=98(fix=20#6?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- client.go | 17 +++++++++++++++-- util.go | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/client.go b/client.go index 3b3fe0f..a1f07f7 100644 --- a/client.go +++ b/client.go @@ -50,7 +50,7 @@ func (c *Client) GetCookiesString() string { // SetCookiesString 设置Cookies,但是是字符串格式,配合 GetCookiesString 使用。有些功能必须登录或设置Cookies后才能使用。 func (c *Client) SetCookiesString(cookiesString string) { - c.resty.SetCookies((&resty.Response{RawResponse: &http.Response{Header: http.Header{ + c.SetCookies((&resty.Response{RawResponse: &http.Response{Header: http.Header{ "Set-Cookie": strings.Split(cookiesString, "\n"), }}}).Cookies()) } @@ -64,9 +64,22 @@ func (c *Client) SetRawCookies(rawCookies string) { c.SetCookies(req.Cookies()) } +// SetCookie 设置单个cookie +func (c *Client) SetCookie(cookie *http.Cookie) { + for i, c0 := range c.resty.Cookies { + if c0.Name == cookie.Name { + c.resty.Cookies[i] = cookie + return + } + } + c.resty.Cookies = append(c.resty.Cookies, cookie) +} + // SetCookies 设置cookies func (c *Client) SetCookies(cookies []*http.Cookie) { - c.resty.SetCookies(cookies) + for _, cookie := range cookies { + c.SetCookie(cookie) + } } // GetCookies 获取当前的cookies diff --git a/util.go b/util.go index eb9cc93..07335ae 100644 --- a/util.go +++ b/util.go @@ -67,7 +67,7 @@ func execute[Out any](c *Client, method, url string, in any, handlers ...paramHa if resp.StatusCode() != 200 { return out, errors.Errorf("status code: %d", resp.StatusCode()) } - c.resty.SetCookies(resp.Cookies()) + c.SetCookies(resp.Cookies()) var cr commonResp[Out] if err = json.Unmarshal(resp.Body(), &cr); err != nil { return out, errors.WithStack(err)