Skip to content

Commit 22efd91

Browse files
committed
use defer timer.Stop() instead
1 parent adda914 commit 22efd91

File tree

2 files changed

+7
-34
lines changed

2 files changed

+7
-34
lines changed

api/client.go

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

7070
var response *opcodes.RequestResponse
71-
timeout, timer := newTimeoutTimer(c.ResponseTimeout * time.Millisecond)
71+
72+
timer := time.NewTimer(c.ResponseTimeout * time.Millisecond)
73+
defer timer.Stop()
7274
select {
7375
case response = <-c.IncomingResponses:
74-
if timer != nil {
75-
timer.Stop()
76-
}
77-
case <-timeout:
76+
case <-timer.C:
7877
return fmt.Errorf("request %s: timeout waiting for response from server", name)
7978
}
8079

@@ -127,15 +126,3 @@ func (c *Client) SendRequest(requestBody Params, responseBody interface{}) error
127126

128127
return nil
129128
}
130-
131-
// newTimeoutTimer is an alternative to time.After with the possibility to cancel
132-
// the underlying time.Timer to achieve better efficiency.
133-
// time.Duration d <= 0 means no timeout or waiting forever.
134-
// See https://pkg.go.dev/time#After
135-
func newTimeoutTimer(d time.Duration) (timeout <-chan time.Time, timer *time.Timer) {
136-
if d > 0 {
137-
timer = time.NewTimer(d)
138-
timeout = timer.C
139-
}
140-
return
141-
}

client.go

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

175-
timeout, timer := newTimeoutTimer(c.ResponseTimeout * time.Millisecond)
175+
timer := time.NewTimer(c.ResponseTimeout * time.Millisecond)
176+
defer timer.Stop()
176177
select {
177178
case a := <-authComplete:
178-
if timer != nil {
179-
timer.Stop()
180-
}
181179
return a
182-
case <-timeout:
180+
case <-timer.C:
183181
return fmt.Errorf("timeout waiting for authentication: %dms", c.ResponseTimeout)
184182
}
185183
}
@@ -373,15 +371,3 @@ func (c *Client) Listen(f func(interface{})) {
373371
f(event)
374372
}
375373
}
376-
377-
// newTimeoutTimer is an alternative to time.After with the possibility to cancel
378-
// the underlying time.Timer to achieve better efficiency.
379-
// time.Duration d <= 0 means no timeout or waiting forever.
380-
// See https://pkg.go.dev/time#After
381-
func newTimeoutTimer(d time.Duration) (timeout <-chan time.Time, timer *time.Timer) {
382-
if d > 0 {
383-
timer = time.NewTimer(d)
384-
timeout = timer.C
385-
}
386-
return
387-
}

0 commit comments

Comments
 (0)