Skip to content

Commit 10ff16e

Browse files
authored
always use the latest cookies and add mutex protection (#23)
current implementation may use expired cookie, so need take the latest cookie. Also one client may be used in parallel, need mutex protection to prevent panic Signed-off-by: Leslie Qi Wang <qiwa@pensando.io>
1 parent 110fa41 commit 10ff16e

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

pkg/client/client.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"net"
2424
"net/http"
2525
"strings"
26+
"sync"
2627
"time"
2728
)
2829

@@ -127,6 +128,7 @@ type Client struct {
127128
secure bool
128129
useCookies bool
129130
cookies []*http.Cookie
131+
lock *sync.Mutex
130132
headerTimeout time.Duration
131133
clientTimeout time.Duration
132134
}
@@ -136,11 +138,14 @@ func NewClient() *Client {
136138
return &Client{
137139
port: 443,
138140
protocol: "https",
141+
lock: &sync.Mutex{},
139142
}
140143
}
141144

142145
// Logout resets client cookie and logout the session
143146
func (cli *Client) Logout() {
147+
cli.lock.Lock()
148+
defer cli.lock.Unlock()
144149
cli.cookies = nil
145150
}
146151

@@ -259,9 +264,11 @@ func (cli *Client) callAPI(contentType string, url string, payload []byte) ([]by
259264
if len(cli.cookies) == 0 || !cli.useCookies {
260265
req.SetBasicAuth(cli.username, cli.password)
261266
} else {
267+
cli.lock.Lock()
262268
for _, cookie := range cli.cookies {
263269
req.AddCookie(cookie)
264270
}
271+
cli.lock.Unlock()
265272
}
266273

267274
res, err := client.Do(req)
@@ -291,9 +298,9 @@ func (cli *Client) callAPI(contentType string, url string, payload []byte) ([]by
291298
return nil, fmt.Errorf("500 Server Internal Error")
292299
}
293300
}
294-
if cli.cookies == nil {
295-
cli.cookies = res.Cookies()
296-
}
301+
cli.lock.Lock()
302+
cli.cookies = res.Cookies()
303+
cli.lock.Unlock()
297304
return body, nil
298305
}
299306

0 commit comments

Comments
 (0)