Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

解决多次调用SetCookies会导致cookies越来越长的问题 #69

Merged
merged 1 commit into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion util.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down