Skip to content

Commit b67ee58

Browse files
afrizaandreykaipov
andauthored
Use time.NewTimer() instead of time.After() (#56)
* Use `time.NewTimer()` instead of `time.After()` For efficiency, cancel time.Timer after no longer needed. See https://pkg.go.dev/time#After * use defer timer.Stop() instead --------- Co-authored-by: Andrey Kaipov <[email protected]>
1 parent 67a7278 commit b67ee58

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

api/client.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,12 @@ func (c *Client) SendRequest(requestBody Params, responseBody interface{}) error
6868
}
6969

7070
var response *opcodes.RequestResponse
71+
72+
timer := time.NewTimer(c.ResponseTimeout * time.Millisecond)
73+
defer timer.Stop()
7174
select {
7275
case response = <-c.IncomingResponses:
73-
case <-time.After(c.ResponseTimeout * time.Millisecond):
76+
case <-timer.C:
7477
return fmt.Errorf("request %s: timeout waiting for response from server", name)
7578
}
7679

client.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,10 +172,12 @@ func (c *Client) connect() (err error) {
172172
go c.handleRawServerMessages(authComplete)
173173
go c.handleOpcodes(authComplete)
174174

175+
timer := time.NewTimer(c.ResponseTimeout * time.Millisecond)
176+
defer timer.Stop()
175177
select {
176178
case a := <-authComplete:
177179
return a
178-
case <-time.After(c.ResponseTimeout * time.Millisecond):
180+
case <-timer.C:
179181
return fmt.Errorf("timeout waiting for authentication: %dms", c.ResponseTimeout)
180182
}
181183
}
@@ -355,7 +357,7 @@ func (c *Client) writeEvent(event interface{}) {
355357
// incoming events was full (but might not be by now),
356358
// so safely read off the oldest, and write the latest
357359
select {
358-
case _ = <-c.IncomingEvents:
360+
case <-c.IncomingEvents:
359361
default:
360362
}
361363

0 commit comments

Comments
 (0)